Search code examples
pythonunit-testingdoctestdocstring

Put python doctest at the end of the code file?


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.


Solution

  • 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