Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: using doctests for classes

Is it possible to use Python's doctest concept for classes, not just functions?

If so, where shall I put the doctests - at the class' docstring, or at the constructor's docstring?

To clarify, I'm looking for something like:

class Test:     """     >>> a=Test(5)     >>> a.multiply_by_2()     10     """     def __init__(self, number):         self._number=number      def multiply_by_2(self):         return self._number*2 

Thanks in advance,

Adam

like image 662
Adam Matan Avatar asked Apr 25 '10 12:04

Adam Matan


People also ask

What is the correct way to run all the Doctests in a given file from the command?

To run the tests, use doctest as the main program via the -m option to the interpreter. Usually no output is produced while the tests are running, so the example below includes the -v option to make the output more verbose.

What is doctest function in Python?

doctest is a module included in the Python programming language's standard library that allows the easy generation of tests based on output from the standard Python interpreter shell, cut and pasted into docstrings.

Which Python module Do you need to subclass the built in TestCase class?

A testcase is created by subclassing unittest. TestCase . The three individual tests are defined with methods whose names start with the letters test . This naming convention informs the test runner about which methods represent tests.


1 Answers

Instead of instantiating the object in every method, you can use the extraglobs argument:

class Test:     def multiply_by_2(self):         """         >>> t.multiply_by_2()         10         """         return self._number*2  if __name__ == '__main__':     import doctest     doctest.testmod(extraglobs={'t': Test()}) 
like image 156
Ari Avatar answered Sep 24 '22 01:09

Ari