Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
preface
We usually choose UnitTest or PyTest to do unit tests, but the code is relatively large. We want to find a tool that can complete unit tests synchronously while writing the code. Today, it’s here, Doctest.
Doctest
It is a built-in document testing library for Python. You will find that many Python built-in libraries use this tool for unit testing. You can think of it as implementing unit tests in the form of comment documents.
Take a chestnut
def add(x,y): ''' calc x add y... Example: > > > add (1, 1) 2 > > > add (1, 1) 0 ' ' 'return x + y if __name__ = =' __main__ ': import doctest doctest.testmod(verbose=True)Copy the code
The results
PS C:\Users\ XXX \Desktop\study> python.\doct.py Trying: add(1,1) Expecting: 2 ok Trying: add(-1,1) Expecting: 0 ok 1 items had no tests: __main__ 1 items passed all tests: 2 tests in __main__.add 2 tests in 2 items. 2 passed and 0 failed. Test passed.Copy the code
As mentioned above, if you are the development team’s white-box test, you can ask the development team to annotate the test cases in the format above, and then you can easily conduct unit tests.
Q&A
About how to test someone else’s code
Suppose someone writes code in A. py that looks like this:
def execDouble(x) :
''' exec num double... Example: # Case1: >>> execDouble(1) 2 # Case2: >>> execDouble(3) 6 '''
return x*2
Copy the code
We import and test the methods in A. py in B. py.
import doctest
from a import execDouble
doctest.testmod(verbose=True)
Copy the code
Run the test: Python B.py
The method under test is not identified. Why is this? By querying the official doctest documentation, we know that if we want to execute the imported object, we need to define the __test__ dictionary in the test code to specify it.
Add the following line to b.py:
import doctest
from a import execDouble
__test__={'execDouble':execDouble}
doctest.testmod(verbose=True)
Copy the code
Re-execute the test:
That’s all for today, thank you for reading, and we’ll see you next time.