A python standard library for running simple tests
Just write the execution content and the correct return value as a set in the docstring
def add(a, b):
'''
>>> add(1, 2)
3
>>> add(-8, -2)
-10
'''
pass
if __name__ == '__main__':
import doctest
doctest.testmod()
terminal
python hoge.py
output
**********************************************************************
File "__main__", line 3, in __main__.add
Failed example:
add(1, 2)
Expected:
3
Got nothing
**********************************************************************
File "__main__", line 5, in __main__.add
Failed example:
add(-8, -2)
Expected:
-10
Got nothing
**********************************************************************
1 items had failures:
2 of 2 in __main__.add
***Test Failed*** 2 failures.
TestResults(failed=2, attempted=2)
Correct it so that it returns correctly
hoge.py
def add(a, b):
'''
>>> add(1, 2)
3
>>> add(-8, -2)
-10
'''
return a + b
if __name__ == '__main__':
import doctest
doctest.testmod()
terminal
python hoge.py
No output if all tests are successful
output
You can use doctest.testmod () to test all functions, but if you want to test only specific functions, use doctest.run_docstring_examples (). If you write as follows, only add () will be tested.
hoge.py
import doctest
doctest.run_docstring_examples(add, globals())
It's the same to test all the functions defined by doctest.testmod (), so just run it normally in the cell.
jupyter_notebook
def add(a, b):
'''
>>> add(1, 2)
3
>>> add(-8, -2)
-10
'''
pass
import doctest
doctest.testmod()
Recommended Posts