سؤال

I can put python doctests in the bodies of each function, which I sometimes like for small libraries, because they are in the same file as the function.

Or I can put them all together into a seperate file and execute the separate file, which is nice in case I do not want the doctest in between the functions. Sometimes I find the code is easier to work on if the docstrings are small.

Is there also a way to keep the python doctests in the same file, but put them all together at the end of the file?


EDIT: A solution, based on the accepted answer below:

def hello_world():
  return u'Hello World'


def hello(name):
  return u'Hello %s' % name


def doctest_container():
  """
  >>> hello_world()
  u'Hello World'

  >>> hello(u'Guido')
  u'Hello Guido'
  """
  pass


if __name__ == "__main__":
    import doctest
    doctest.testmod()

In fact it is simple, a dummy function is created as the last function that contains all the doctests in one docstring.

هل كانت مفيدة؟

المحلول

doctest is to test that examples in your documentation are in sync with the implementation.

if there are many tests; unit tests written as code might be easier to maintain than doctest-based tests.

You could add a test function at the end of the module with desired doctests to avoid polluting docstrings of non-test code:

def test():
    """
    ..
    """
    import doctest
    doctest.testmod()

if __name__=="__main__": 
    test()  # if the module is called as a script then run tests

نصائح أخرى

You can append the doctests to the docstring at the end of file like that:

def myfunc():
    """This is a docstring without a doctest
    """
    pass

# ... some other code here

# Add docstrings for doctest:
myfunc.__doc__ += """
>>> myfunc()
>>> repr(myfunc())
None
"""
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top