When writing a function or class , You can also write tests for it . Pass the test , You can be sure that the code will work as required for various inputs . When adding new code to a program , You can also test it , Make sure they don't break the behavior of the program .
Use Python modular unittest To test the code
【 Be careful 】: The class where the test code resides , Must inherit unittest.TestCase Inheritance class
(1) Unit tests and test cases
Python Modules in the standard library unittest Provides code testing tools .
1、 unit testing Used to verify the function In some way No problem ;
2、 The test case yes A set of unit tests , Together, these unit tests verify that the function behaves as expected under various circumstances .
Good test cases take into account the various inputs that the function may receive , Include tests for all of these situations .
3、 Full coverage test cases contain A complete set of unit tests , Covers a variety of possible ways to use functions .
For large projects , It can be difficult to achieve full coverage . Usually , Initially, just write tests for important behavior of the code , When the project is widely used, consider full coverage .( You can't do it in general )
(2) A passable test
The syntax for creating test cases takes a while to get used to , But after the test case is created , It's easy to add unit tests for functions .
【 Write function test module Syntax 】:
To write test cases for functions , You can import modules first unittest And the function to test , Create another inheritance unittest.TestCase Class , And write a series of methods to test different aspects of function behavior .
import unittest # Import the test module
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase): # Must inherit unittest.TestCase class
""" test name_function.py"""
def test_first_last_name(self): # All with test The leading methods will be Python Automatic execution ( In test class , Inherit unittest.TestCase The class of represents the test class )
""" Be able to handle things like Janis Joplin Such a name ?"""
formatted_name = get_formatted_name('janis', 'joplin')# Functions to be tested ( Custom function ) The result
self.assertEqual(formatted_name, 'Janis Joplin') # call unittest Methods assertEqual() assert methods
# Compare the result of your own function with the correct result , If correct , The output ok, On the contrary, output error
unittest.main()# Run test code
(3) assert methods
Used unittest One of the most useful functions of class : An assertion method . Assertion method is used to verify whether the result is consistent with the expected result , That is, check whether the conditions you think should be met are indeed met .
for example :
self.assertEqual(formatted_name, ‘Janis Joplin’)
We call unittest Methods assertEqual() , And pass it on formatted_name and ’Janis Joplin’ . Lines of code self.assertEqual(formatted_name, ‘Janis Joplin’) It means say :“ take formatted_name The value of is the same as the string ’Janis Joplin’ Compare .
(4) Repeat the test
Modify your own functions , It can realize repeated test
(5) Run test files
Lines of code unittest.main() Give Way Python Run the test code in this file .
A、 adopt The test results are as follows :
. # A period means that a test has passed n A little bit , representative n One test passed
----------------------------------------------------------------------
Ran 1 test in 0.000s # Express Python Run a test . It takes less time 0.001 second
OK # Indicates that all unit tests in the test case have passed
B、 Cannot pass The test results are as follows :
E # The output has only one letter E, Indicates that only one unit test in the test case caused an error . That is to say n Letters E, That is to say n A single test resulted in an error
======================================================================
ERROR: test_first_last_name (__main__.NamesTestCase) # error location NamesTestCase Medium test_first_last_name() Led to a mistake
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_name_function.py", line 8, in test_first_last_name
formatted_name = get_formatted_name('janis', 'joplin')
TypeError: get_formatted_name() missing 1 required positional argument: 'last'
# The reason for the error Missing an essential positional argument
-----------------------------------------------------------------------
Ran 1 test in 0.000s # Run a test unit
FAILED (errors=1) # Point out that the entire test case fails Because an error occurred while running the test case
# This message is at the end of the output , So you can see at a glance
(6) What if the test fails ?
If the conditions you check are correct , Passing the test means that the behavior of the function is correct , And the failure of the test means that the new code you write is wrong . therefore , When the test fails , Do not modify the test , Instead, fix the code that causes the test to fail : Check the changes you just made to the function , Find the changes that cause the function to behave as expected .
(7) Add a new test function
It can be developed according to specific project requirements , Write multiple test functions , Conduct method test
(8) Class test
The previous section mainly introduced the testing for a single function , Let's write a test for the class . Classes are used in many programs , So it would be helpful to be able to prove that your class works correctly . If the test for the class passes 了 , You can be sure that the improvements made to the class do not accidentally destroy its original behavior .
A、 Common assertion methods : Must be in unittest Class , So you have to inherit
Python stay unittest.TestCase class Many assertion methods are provided in . As I said before , The assertion method checks whether the conditions you think should be met are indeed met . If this condition is indeed met , Your assumptions about the behavior of the program get confirm , You can be sure there are no mistakes . If the conditions you think should be met are actually not met ,Python Exception will be thrown .
The main examples in the above table , Must be in unittest.TestCase Class
B、 Test class implementation
Class tests are similar to function tests —— Most of what you do is test the behavior of the methods in your classes , But there are some differences .
import unittest # Import the test module
from survey import AnonymousSurvey
class TestAnonmyousSurvey(unittest.TestCase): # Must inherit unittest.TestCase class
""" in the light of AnonymousSurvey Class testing """
def test_store_single_response(self):#test start Automatic operation
""" Test individual answers will be stored properly """
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses) # assert methods verify item Whether in list in return true or false
unittest.main()# Test function start
【 Small tips】:
The main process of class testing and function testing is the same , Class testing is to test every function in a class , Test every method in the class , To implement the final class test .
When a method is called , You need to instantiate the class first , Then the method in the class is called through the instantiated object , To test .
(9) Method setUp()
unittest.TestCase Class contains methods setUp(), Let's just create these objects once , And use them in every test method . If you are in the TestCase Class contains methods setUp() ,Python Will run it first , Then run each to test_ The way to start .
rewrite unittest.TestCase class ( Parent class ) Medium setUp() function , Create an object in this function . Use setup() function , Sure Simplify the process of creating objects , Every time you run the test code ,Python Will run first setup() function , Then run each test_ The way to start .
【 advantage 】:
When testing your own classes , Method setUp() Make it easier to write test methods : Can be found in setUp() Method to create a series of instances and set their properties , Then use these examples directly in the test method . Compared to every Test methods create instances and set their properties , It's much easier .