The
doctest module is part of the Python standard library. There is no need to write separate test functions/methods in doctest, you simply copy the expected results and paste them in the docstring that corresponds to the tested function.
class Counter:
def __init__(self, value = 0):
"""
>>> Counter().value
0
>>> Counter(100).value
100
"""
self.value = value
def add(self, x):
"""
>>> c = Counter()
>>> c.add(5)
5
>>> c.value
5
>>> c.add(0)
Traceback (most recent call last):
...
ValueError
>>> c.skip_me # doctest: +SKIP
"""
if not x:
raise ValueError
self.value += x
return self.value
if __name__ == '__main__':
import doctest
doctest.testmod()
In order to execute all tests just run the following (on success no output is given):
python doctestexample.py
Alternatively you can run doctest with
unittest:
if __name__ == '__main__':
import doctest, unittest
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(__name__))
runner = unittest.TextTestRunner()
runner.run(suite)
Read more about doctest
here.
No comments :
Post a Comment