If you have such a file in your project mylib.py, there are a number of methods written in the file for the outside people to call
defAdd (x, y):returnx+ydefDivision (x, y):returnx/ydefmutiply (x, y):returnx*ydefsubtract (x, y):returnX-ydefMain ():Passif __name__=='__main__': Main ()
So how do we write unit test code to verify the correctness of these methods?
Take a look at the following file testadd.py (filename must begin with test)
Import Mylib Import UnitTest class TestCase (unittest. TestCase): def Test_add (self): self.assertequal (Mylib.add (2,3), 5) def Main (): unittest.main ()if__name__'__main__' : main ()
The class name testcase can be arbitrarily taken, but the method name Test_add must start with test, so that when running testadd.py, the program will know to run this method.
The results of the operation are as follows:
1 Test in. 564sOK
If we have another I ah a file testsub.py
Import UnitTest Import arithmetic class MyTest (unittest. TestCase): def test_sub (self): self.assertequal (Arithmetic.subtract (4,2), 1) def Main (): unittest.main ()if__name__'__ main__': main ()
And we want to run testadd.py with testsub.py, just execute this command.
Python-m UnitTest Discover
UnitTest will recursively look for files that match test*.py in the current directory and will unittest them. All subclasses of TestCase are instantiated, and then the appropriate test method is called for testing.
Python Unit Test