preface
our last article introduced Code testing ; It mainly introduces the function testing, including unit testing and passable testing, and how to modify the code to make the test class pass when we encounter that the test fails. This paper introduces the test class; First of all, we introduce the methods of testing various assertions in the class;
Test class
the previous article is aimed at testing a single function; Our article mainly tests the classes we write. Classes are used in many programs, so it's helpful to prove that your classes work 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.
1. Various assertion methods
Python in unittest Many assertion methods are provided in the testcase class. As mentioned in the above article, the assertion method checks whether the conditions you think should be met are indeed met, your assumptions about program behavior are confirmed, and you can be sure that there are no errors. If the condition you think should be met is not actually met, python will throw an exception.
the following table describes six common assertion methods. Use these methods to verify that the returned value is equal to or not equal to the expected value, that the returned value is True or False, and that the returned value is in or not in the list. You can only inherit unittest These methods are used in the testcase class, and one of them is used when testing the class:
2. A class to test
class testing is similar to function testing - most of your work is to test the behavior of class methods, but there are some differences. Let's write a class for testing. Take a look at a class that helps manage anonymous surveys:
class AnonymousSurvery(): """Collect answers to anonymous questionnaires""" def __init__(self, question): """Store a question without storing an answer for preparation""" self.question = question self.responses = [] def show_question(self): """Show questionnaire""" print(self.question) def store_response(self, new_response): """Store individual survey answers""" self.responses.append(new_response) def show_results(self): """Show all collected answers""" print("Suvery result:") for response in self.responses: print('- ' + response)
this class first stores a survey question you specify, and creates an empty list to store answers. This class contains methods for printing survey questions, adding new answers to the answer list, and printing all the answers stored in the list. To create an instance of this class, simply provide a question. After you have an instance representing the survey, you can use show_question() to display the questions. You can use store_response() to store the answer and use show_results() to display the survey results.
to prove that the AnonymousSurvey class works correctly, let's write a program using it:
from survey import AnonymousSurvery # Define a question and create an anonymous survey object that represents the survey question = "What language did you first learn to speak?" my_survey = AnonymousSurvery(question) # Display questions and store answers 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) # Display survey results print("\nThank you to everyone who participated in the survey!") my_survey.show_results()
this program defines a question ("What language did you first learn to speak?"), And use this problem to create an anonymous survey object. Next, the program calls show_question() to display the question and prompt the user for an answer. Store each answer as it is received. When the user enters all the answers (after entering q to exit), call show_. Results() to print the survey results:
the AnonymousSurvey class can be used for simple anonymous surveys. Suppose we put it in the module survey and want to improve it; Allow each user to enter multiple answers; Write a method that lists only different answers and indicates how many times each answer appears; Write another class to manage non anonymous surveys.
there is a risk that making the above modifications may affect the current behavior of the AnonymousSurvey class. For example, allowing each user to enter multiple answers may inadvertently modify the way a single answer is processed. To ensure that the existing behavior is not broken when developing the module, you can write tests for this class.
3. Test the AnonymousSurvey class
let's write a test to verify one aspect of the behavior of the AnonymousSurvey class: if the user provides only one answer to the survey question, the answer can also be properly stored. To this end, after the answer is stored, we will use the method assertIn() to verify that it is included in the answer list:
import unittest from survey import AnonymousSurvery class TestAnonymousSurvey(unittest.TestCase): """in the light of AnonymousSurvey Class""" def test_store_single_response(self): """Test individual answers will be stored properly""" question = "What language did you first learn to speak?" my_survey = AnonymousSurvery(question) my_survey.store_response('English') self.assertIn('English', my_survey.responses) unittest.main
we first imported the module unitest and the class AnonymouseSurvey to be tested. We name the test case test anonymous survey, which also inherits unittest TestCase. The first test method verifies that after a single answer to the survey question is stored, it will be included in the survey result list. A good descriptive name for this method is tset_store_single)response(). If this test fails, we can know from the method noun in the output that there is a problem in storing a single survey answer.
to test the behavior of a class, we need to create its instance. We use the problem to create a named my_ An instance of survey, and then use the method store_response() stores a single answer in English. Next, we check whether English is included in the list_ survey_ Response to verify that the answer is properly stored. When we run test_survey.py, the test passed:
of course, this is very good, but the survey that can only collect one answer is of little use. Let's verify that when users provide three answers, they will also be properly stored. To do this, we add some more methods in testanonmoussurey:
import unittest from survey import AnonymousSurvery class TestAnonymousSurvey(unittest.TestCase): """in the light of AnonymousSurvey Class""" def test_store_single_response(self): """Test individual answers will be stored properly""" question = "What language did you first learn to speak?" my_survey = AnonymousSurvery(question) my_survey.store_response('English') self.assertIn('English', my_survey.responses) def test_store_three_response(self): """The three answers to the test will be stored properly""" question = "What language did you first learn to speak?" my_survey = AnonymousSurvery(question) responses = ['Chinese', 'Rushion', 'English'] for response in responses: my_survey.store_response(response) for response in responses: self.assertIn(response, my_survey.responses) unittest.main
we name this method test_store_three_response() and like test_ store_ single_ Like response (), create a survey object in it. We define a list of three different answers, and then call store for each answer_ response(). After storing these answers, we use a loop to confirm that each answer is included in my_ In response. When we run test again_ survey. Py, both tests (for a single answer and for three answers) passed:
. the results of the above methods are very good, but there are some repetitions in these tests. Let's use another function of unittest to improve their efficiency.
4. Method setUp()
test in front_ survey. Py, we created an anonymous survey instance in each test method and created answers in each method. unittest. The TestCase class contains the method setUp(), which allows us to create these objects only once and use them in each test method. If you include the method setUp() in the TestCase class, Python will run it first, and then run each to test_ The way to start. In this way, the object created in the method setUp() can be used in every test method you write.
let's use setUp() to create a survey object and a set of answers for the method tset_store_single_response() and test_store_three_response() uses:
import unittest from survey import AnonymousSurvery class TestAnonymousSurvey(unittest.TestCase): """in the light of AnonymousSurvey Class""" def setUp(self): """Create a survey object and a set of answers for the test method used""" quetion = "What language did you first learn to speak?" self.my_survey = AnonymousSurvery(quetion) self.responses = ['Chinese', 'Rushion', 'English'] 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): """The three answers to the test will be stored properly""" 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
the method setUp() does two things: create a survey object; Create a list of answers. The variable names that store these two things contain the prefix self (that is, stored in attributes), so they can be used anywhere in this class. This makes both test methods easier because they don't have to create objects and answers. Method test_store_single_response() verify self The first answer in responses - self Responses [0] - stored properly, and method test_store_three_responses() verify self All three answers in responses are properly stored.
self.responses run test again_ survey. Py, both tests passed:
these tests are useful if you want to extend anonymous survey to allow each user to enter multiple answers. After modifying the code to accept multiple answers, you can run these tests to verify that the behavior of storing a single answer or a series of answers is not affected.
when testing a class written by yourself, the method setUp() makes it easier to write the test; You can create a series of instances and set their properties in the setUp() method, and then use these instances directly in the test method. This is much easier than creating instances and setting their properties in each test method.
here we need to pay attention to: when running test cases, Python prints a character every time a unit test is completed: a period is printed when the test passes; An E is printed when the test causes an error; An F is printed when the test causes the assertion to fail. This is why when you run the test case, you see different numbers of periods and characters in the first line of output. If the test case contains many unit tests and needs to run for a long time, you can know how many tests have passed by observing these results.
summary
our last article introduced Code testing ; It mainly introduces the function testing, including unit testing and passable testing, and how to modify the code to make the test class pass when we encounter that the test fails. This paper introduces the test class; It mainly includes various assertion methods and a test case, and tests the case. Finally, it introduces the setUp() method in class testing. Python is a language that pays attention to practical operation. It is the simplest and the best entry among many programming languages. When you learn the language, it's easier to learn java, go and C. Of course, Python is also a popular language, which is very helpful for the implementation of artificial intelligence. Therefore, it is worth your time to learn. Life is endless and struggle is endless. We work hard every day, study hard, and constantly improve our ability. I believe we will learn something. come on.