to write unit tests, we need to introduce Python's own unittest module.
When writing unit tests, we need to write a test class from unittest. TestCase inheritance.
The method that begins with test is a method of testing, and a method that does not begin with test is not considered a test method and is not executed when it is tested.
UnitTest. TestCase provides a number of built-in conditional judgments:
Self.assertequal (ABS (-1), 1) # assertion function returns the same result as 1
Another important assertion is that the assertion throws a keyerror when it expects to throw a specified type of error, such as accessing a nonexistent key via d[' empty ':
With Self.assertraises (keyerror):
value = d[' Empty ']
And by D.empty access to nonexistent key, we expect to throw Attributeerror:
With Self.assertraises (attributeerror):
value = D.empty
Run unit Tests
The simplest way to do this is to add in the unit test py file:
if __name__ = = ' __main__ ':
unittest.main ()
Then it's OK to run the test script normally.
Another approach is to run unit tests directly on the command line via parameter- m unittest , which is recommended because you can run many unit tests at once, and there are a number of tools that can automatically run these unit tests. Setup and teardown
You can write two special setUp () and teardown () methods in a unit test. The two methods are executed separately before and after each call to a test method .