If you've heard of "test-driven Development" (Tdd:test-driven development), unit testing is no stranger.
Unit tests are used to test the correctness of a module, a function, or a class.
For example, for the function abs (), we can write the following test cases:
- Enter a positive number, such as 1, 1.2, 0.99, expecting the return value to be the same as the input;
- Enter negative numbers, such as-1,-1.2,-0.99, expecting the return value to be the opposite of the input;
- Enter 0, expect to return 0;
- Enter non-numeric types, such as none, [], {}, and expect to throw typeerror.
Putting the above test cases into a test module is a complete unit test.
If the unit test passes, it means that the function that we are testing is working correctly. If the unit test does not pass, either the function has a bug, or the test condition is entered incorrectly, in short, a repair is required to enable the unit test to pass.
What does it mean after unit tests are passed? If we make modifications to the ABS () function code, we just need to run the unit test again, and if it does, our changes will not affect the original behavior of the ABS () function, if the test does not pass, it means that our changes are inconsistent with the original behavior, either modify the code or modify the test.
The greatest benefit of this test-driven development model is to ensure that the behavior of a program module conforms to the test cases we have designed. In the future, it can be greatly ensured that the module behavior is still correct.
Let's write a dict class that behaves the same as dict, but can be accessed through attributes, as follows:
>>> d = Dict (A=1, b=2) >>> d[' a ']1>>> d.a1
The mydict.py code is as follows:
Class Dict (Dict): def __init__ (self, **kw): super (Dict, self). __init__ (**kw) def __getattr__ (self, key): try: return Self[key] except Keyerror: raise Attributeerror (r "' Dict ' object has no attribute '%s '"% Key) def __setattr__ (self, Key, value): Self[key] = value
In order to write unit tests, we need to introduce Python's own unittest module and write mydict_test.py as follows:
Import unittestfrom mydict import Dictclass testdict (unittest. TestCase): def test_init (self): d = Dict (a=1, b= ' test ') self.assertequals (D.A, 1) self.assertequals (d.b, ' test ') Self.asserttrue (Isinstance (d, Dict)) def test_key (self): d = dict () d[' key ' = ' value ' Self.assertequals (D.key, ' value ') def test_attr (self): d = Dict () D.key = ' value ' self.asserttrue (' key ' in D) Self.assertequals (d[' key '), ' value ') def test_keyerror (self): d = Dict () with self.assertraises ( Keyerror): value = d[' empty ' def test_attrerror (self): d = Dict () with self.assertraises ( Attributeerror): value = D.empty
When writing unit tests, we need to write a test class from UnitTest. TestCase inheritance.
The method that begins with test is the method of testing, and the method that does not begin with test is not considered a test method and is not executed when the test is performed.
You need to write a test_xxx () method for each type of test. Due to unittest. TestCase provides a lot of built-in conditional judgments, and we just need to call these methods to assert that the output is what we expect. The most common assertion is assertequals ():
Self.assertequals (ABS (-1), 1) # The Assertion function returns a result equal to 1
Another important assertion is that the assertion throws keyerror when it is expected to throw an error of the specified type, such as accessing a nonexistent key through d[' empty '):
With Self.assertraises (keyerror): value = d[' Empty ']
When accessing a nonexistent key through d.empty, we expect to throw Attributeerror:
With Self.assertraises (attributeerror): value = D.empty
Run unit Tests
Once the unit tests have been written, we can run the unit tests. The simplest way to run is to add two lines of code at the end of the mydict_test.py:
if __name__ = = ' __main__ ': unittest.main ()
This allows the mydict_test.py to be run as a normal Python script:
$ python mydict_test.py
Another more common approach is to run unit tests directly at the command line through the parameter-M unittest:
$ python-m unittest mydict_test ...----------------------------------------------------------------------Ran 5 Tests in 0.000sOK
This is recommended because it allows you to run many unit tests in batches at once, and there are many tools that can run these unit tests automatically.
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.
What does the SetUp () and teardown () methods do? Assuming your test needs to start a database, you can connect to the database in the Setup () method and close the database in the Teardown () method, so that you do not have to repeat the same code in each test method:
Class Testdict (UnitTest. TestCase): def setup (self): print ' Setup ... ' def tearDown (self): print ' TearDown ... '
You can run the test again to see if the setup will print out before and after each test method call ... and teardown ....
Summary
Unit testing can effectively test the behavior of a program module and is a confidence guarantee for future refactoring code.
Test cases for unit tests overwrite common input combinations, boundary conditions, and exceptions.
Unit test code is very simple, if the test code is too complex, then the test code itself may have a bug.
Unit testing does not mean that the program is not a bug, but not through the program must have a bug.