11 Test Code
When writing functions and classes, you can also write test functions that can be tested to determine that the code works correctly with various inputs. When you add new code to your program, you can also test it to make sure that they do not break the program's existing programs. To test the module frequently.
Test your code with the tools in Python's module unittest. Will understand how the test passed, what did not pass, know how to improve the code without passing the test, know how many tests to write for the project. Know how to test functions and classes.
In the process of running the program, you will always encounter a variety of errors. Some errors are caused by problems with programming, such as the output of an integer output string, which we often call bug,bug must be fixed.
11.1 test function 11.1.1 unit tests and test cases
The UnitTest module in Python provides code testing tools that are used by unit tests to verify that there is no problem with a function. A test case is a set of unit tests that ensure that the function has no problems in all aspects.
The full-coverage test case includes a complete set of test cases that cover a variety of possible function usage patterns.
11.1.2 can pass the test
To write a test function for a function, first import the module unittest and the number of the culvert to be tested, creating an inherited unittest. TestCase class and write a series of methods to test the different aspects of function behavior. The name is best with test.
name_function.py
|
Def get_formatted_name (First, last):
"" To obtain the full name. "" "
Full_name = first + "+ Last
Return Full_name.title () |
names.py
|
From name_function import Get_formatted_name
Print ("Enter ' Q ' at any time to quit.")
While True:
First = input ("\nplease give me a first name:")
If first = = ' Q ':
Break
last = input ("Give me a Last name:")
If last = = ' Q ':
Break
Formatted_name = Get_formatted_name (First, last)
Print ("\tneatly formatted name:" + Formatted_name + '. ') |
test_name_function.py
|
Import UnitTest
From name_function import Get_formatted_name
Class Namestestcase (UnitTest. TestCase):
"" "Test name_function.py" ""
def test_first_last_name (self):
"" Can you properly handle names like Janis Joplin? """
Formatted_name = Get_formatted_name (' Janis ', ' Joplin ') self.assertequal (Formatted_name, ' Janis Joplin ')
Unittest.main () |
UnitTest one of the most useful features: an assertion method, Assertequal assertion method used to verify that the resulting result is the same as the expected value.
11.1.3 tests that cannot be passed
The test did not pass, do not modify the test, and you should fix the code that caused the test to fail: Check the changes you just made to the function to find the changes that caused the function behavior to not conform to the expected.
Various assertion methods in the 11.2.1 module
6 Common assertions
|
Method |
Use |
|
Assertequal (A, B) |
Verify A = = B |
|
Assertnotequal (A, B) |
Verify A! = B |
|
Asserttrue (x) |
Verify that X is True |
|
Assertfalse (x) |
Verify that X is False |
|
Assertin (item, list) |
Verify that item is in list |
|
Assertnotin (item, list) |
Verify that item is not in list |
11.2.2 Method Setup ()
UnitTest. The TestCase class contains method Setup (), which allows us to create objects once and use them in each test method.
survey.py
|
Class Anonymoussurvey ():
"" "collection of answers to anonymous questionnaires" "
def __init__ (self, question):
"" Stores an issue and prepares to store the answer "" "
Self.question = question
Self.responses = []
def show_question (self):
"" "Show Questionnaire" ""
Print (question)
def store_response (self, new_response):
"" To store a single survey answer "" "
Self.responses.append (New_response)
def show_results (self):
"" Displays all collected answers "" "
Print ("Survey results:")
For response in responses:
Print ('-' + response)
|
language_survey.py
|
From survey import Anonymoussurvey
#定义一个问题 and create a Anonymoussurvey object that represents the survey
Question = "What language do you first learn to speak?"
My_survey = Anonymoussurvey (question)
#显示问题并存储答案 my_survey.show_question ()
Print ("Enter ' Q ' at any time to quit.\n")
While True:
Response = input ("Language:")
If response = = ' Q ':
Break
My_survey.store_response (response)
# Show Survey Results
Print ("\nthank-everyone who participated in the survey!")
My_survey.show_results () |
test_survey.py
|
Import UnitTest
From survey import Anonymoussurvey
Class Testanonymoussurvey (UnitTest. TestCase):
"" "Test for the Anonymoussurvey class" "
def setUp (self):
"" Creates a survey object and a set of answers that are used by the test method using "" "
Question = "What language do you first learn to speak?"
Self.my_survey = Anonymoussurvey (question)
self.responses = [' 中文版 ', ' Spanish ', ' Mandarin ']
def test_store_single_response (self):
"" "Test individual answers will be stored properly" "" "Self.my_survey.store_response (Self.responses[0])
Self.assertin (Self.responses[0], self.my_survey.responses)
def test_store_three_responses (self):
"" "Test three answers will be properly stored" ""
For response in Self.responses:
Self.my_survey.store_response (response)
For response in Self.responses:
Self.assertin (response, self.my_survey.responses)
Unittest.main ()
|
method Setup () two things are done: Create a Survey object, and create an answer list. the variable name that stores these two things contains the prefix self (which is stored in the attribute), so it can be used anywhere in the class. This makes the two test methods simpler because none of them need to create a survey object and an answer.
Python Basic Learning Summary (ix)