Python Basics
- Python Basics – Introduction and environment configuration
- Python Basics _2 Basic syntax and variable types
- Basics of Python _3 Conditional Statements and Iterative Loops
- Python Basics _4 function
- Python Basics _5 Object-oriented Basics
- Python Basics 6_ Files and exceptions
This article, the seventh and final installment in this basic primer series, briefly covers how to write test cases using the UnitTest model.
Test functions
The first is to give the code for the test, as shown below. This is a function that takes a first and last name and returns a clean first name:
def get_formatted_name(first, last):
full_name = first + ' ' + last
return full_name.title()
Copy the code
Simple test code:
first = 'kobe'
last = 'bryant'
print(get_formatted_name(first, last)) # Output Kobe Bryant
Copy the code
The module Unittest in the Python standard library provides code testing facilities. Here are the meanings of some nouns:
- Unit tests: used to verify that an aspect of a function is ok;
- Test case: A set of unit tests that together verify that a function behaves as required in various situations.
- Full coverage test cases: A set of unit tests covering the various possible ways in which functions can be used.
Typically, you only need to write tests for the important behavior of a function initially, and only consider full coverage when the item is widely used.
Let’s start by showing you how to test your code using UnitTest.
TestCase class, and write a series of class methods to test the different behavior of the function, as shown in the following code:
import unittest
class NamesTestCase(unittest.TestCase):
Tests classes that generate name functions.
def test_first_last_name(self):
formatted_name = get_formatted_name('kobe'.'bryant')
self.assertEqual(formatted_name, 'Kobe Bryant')
unittest.main()
Copy the code
The following output shows that one test example is run, and the test time is 0.001s.
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Copy the code
The above is an example that can be passed, but if the test does not pass, the output will look like this:
# add middle name
def get_formatted_name(first, middel, last):
full_name = first + ' ' + middle + ' ' + last
return full_name.title()
class NamesTestCase(unittest.TestCase):
Tests classes that generate name functions.
# Failed examples
def test_first_name(self):
formatted_name = get_formatted_name('kobe'.'bryant')
self.assertEqual(formatted_name, 'Kobe Bryant')
unittest.main()
Copy the code
The output is as follows, where the error occurred and why:
E
======================================================================
ERROR: test_first_last_middle_name (__main__.NamesTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "E:/Python_Notes/Practise/unittest_practise.py", line 39.in test_first_last_middle_name
formatted_name = get_formatted_name('kobe'.'bryant')
TypeError: get_formatted_name() missing 1 required positional argument: 'middle'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Copy the code
It is obvious that the middle argument is missing. If you want to pass the test, you can modify the original function as follows:
def get_formatted_name(first, last, middle=' '):
"Receives first and last name and returns the full name :param first: :param last: :return:"
if middle:
full_name = first + ' ' + middle + ' ' + last
else:
full_name = first + ' ' + last
return full_name.title()
Copy the code
Then add a new test method, keep running, and the test passes.
def test_first_last_middle_name(self):
formatted_name = get_formatted_name('kobe'.'bryant'.'snake')
self.assertEqual(formatted_name, 'Kobe Snake Bryant')
Copy the code
The test class
The previous section looked at the code to write tests for functions, followed by how to write tests for classes.
Assertion method
The unitest.TestCase class provides a number of assertion methods. AssertEqual, which determines whether a given two parameters are equal, is used in the previous section.
methods | use |
---|---|
assertEqual(a, b) | Verify that 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 the list |
assertNotIn(item, list) | Verify that item is not in the list |
These methods can only be used in classes that inherit from UnitTest. TestCase.
Write tests for classes
First, write a test class that manages anonymous survey answers as follows:
class AnonymousSurvey(a):
Collect answers to anonymous questionnaires.
def __init__(self, question):
''' :param question: '''
self.question = question
self.responses = []
def show_question(self):
"Display questionnaire :return:"
print(self.question)
def store_response(self, new_response):
"Store a single questionnaire :param new_response: :return:"
self.responses.append(new_response)
def show_results(self):
Display all answers :return:"
print('Survey results:')
for response in self.responses:
print(The '-' + response)
Copy the code
This class contains three methods to display the question, store a single questionnaire, and display all the questionnaires. Here is an example:
def use_anonymous_survey(a):
question = "What is the best language in the world?
language_survey = AnonymousSurvey(question)
# display problem
language_survey.show_question()
# Add a questionnaire
language_survey.store_response('php')
language_survey.store_response('python')
language_survey.store_response('c++')
language_survey.store_response('java')
language_survey.store_response('go')
Display all questionnaires
language_survey.show_results()
if __name__ == '__main__':
use_anonymous_survey()
Copy the code
The following output is displayed:
What is the world's best language? Survey results: - php - python - c++ - java - goCopy the code
TestCase: unitTest.testCase: unitTestCase: unitTestCase: unitTestCase: unitTestCase: unitTestCase: unitTestCase
import unittest
class TestAnonmyousSurvey(unittest.TestCase):
def test_store_single_response(self):
"Test method of saving a single questionnaire :return:"
question = "What is the best language in the world?
language_survey = AnonymousSurvey(question)
language_survey.store_response('php')
self.assertIn('php', language_survey.responses)
unittest.main()
Copy the code
The above code uses the assertIn assertion method to test the function store_response().
Here you can continue to test whether you can store more questionnaires, as shown below, and test to store three questionnaires:
def test_store_three_response(self):
question = "What is the best language in the world?
language_survey = AnonymousSurvey(question)
responses = ['c++'.'php'.'python']
for response in responses:
language_survey.store_response(response)
for response in responses:
self.assertIn(response, language_survey.responses)
Copy the code
Finally, unittest.testCase actually contains a method setUp(), which acts like the class’s initializer __init()__. It runs before any other methods start with test_, so you can create objects in this method. To avoid having to create each test method, the above code can be modified to:
class TestAnonmyousSurvey(unittest.TestCase):
def setUp(self):
Create a survey object and a set of answers :return: ""
question = "What is the best language in the world?
self.language_survey = AnonymousSurvey(question)
self.responses = ['c++'.'php'.'python']
def test_store_single_response(self):
"Test method of saving a single questionnaire :return:"
self.language_survey.store_response(self.responses[1])
self.assertIn('php', self.language_survey.responses)
def test_store_three_response(self):
for response in self.responses:
self.language_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.language_survey.responses)
Copy the code
The output is as follows:
. ---------------------------------------------------------------------- Ran2 tests in 0.000s
OK
Copy the code
Notice that it ran successfully, printing a period, because it ran two test methods successfully, printing two periods; If something goes wrong, print an E; The test results in an assertion failure, printing an F.
reference
- Python Programming — From Getting Started to Doing It
summary
So much for the basics of Python series. The initial initial plan for the first installment is as follows:
- Introduction and environment configuration
- Variables and simple data types
- Lists and tuples
- The dictionary
- If conditional statement
- For/while loop statement
- function
- class
- Files and exceptions
- The test code
Just generally introduce the ten aspects of knowledge, the subsequent will have advanced knowledge, including the advanced knowledge functions and classes, regular expressions, thread and process such as the knowledge of network programming, of course also will introduce Python skills summary or translate some good articles, and some methods of use of the library, Examples include numpy, pandas, matplotlib, and so on.
And, of course, work hard on interesting projects.
The code examples for this article are also uploaded to my Github:
- Github.com/ccc013/Pyth…
- Github.com/ccc013/Pyth…
Welcome to follow my wechat official account — the growth of algorithmic ape, or scan the QR code below, we can communicate, learn and progress together!