Chapter 2 test code, 11 test code

Source: Internet
Author: User
Tags how to write test cases

Chapter 2 test code, 11 test code

You can also write and test functions or classes. Through testing, you can determine that the code can work as required for various inputs. The test gives us full confidence that even more people use our

Program, it can also work correctly. When adding new code to a program, we can also test it to ensure that they do not disrupt the program's existing behavior. Programmers Make mistakes, so every programmer must always

Test the code and find out the code before the user discovers the problem.

In this chapter, we will learn how to use the tool in the Python unittest module to test the code. We will learn how to write test cases and verify that a series of inputs will get the expected output. We will see what the test passes, what the test fails, and how the code can be improved if the test fails. We will learn how to test functions and classes and know how many tests should be written for the project.

11.1 test functions

To test a function, you must have the code to test. The following simple amount function accepts the first and last names and returns a neat name:

Name_funcition.py

Def get_formatted_name (first, last ):
''' Obtain the complete user name '''
Full_name = first + "" + last
Return full_name.title ()
The get_formatted_name () function combines the names and surnames into names, adds a space between the names and surnames, and upper-case the first letters of the names before returning the results. To verify the get_formatted_name () Image

As expected, we will compile a program that uses this function. The program names. py allows the user to enter the name and surname and display the neat Full name:

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 ("Please give me a last name :")
If last = 'q ':
Break

Formatted_name = get_formatted_name (first, last)
Print ("\ tNeatly formatted name:" + formatted_name + ".")

This program imports get_formatted_name () from name_function.py (). Enter a series of names and surnames and see the neat Full name:

Enter 'q' at any time to quit.

Please give me a first name: geng
Please give me a last name: changxue
Neatly formatted name: Geng Changxue.

Please give me a first name: jains
Please give me a last name: joplin
Neatly formatted name: Jains Joplin.

Please give me a first name: q

From the above output, we can see that the merged names are correct. Now let's assume we want to modify get_formatted_name () so that it can process the intermediate name. In this case, make sure that this function is only used to process the names of the first and last names. Therefore, we can run the program names. py every time we modify get_formatted_name () and enter a name like Janis Joplin,

This is too troublesome. Fortunately, Python provides an efficient way to automatically test function output. If we perform an automatic test on get_formatted_name (), we are always confident that this function can run correctly when providing our test name.

11.1.1 unit test and test cases

In the Python standard libraryModule unittestProvides code testing tools.Unit TestIt is used to verify that a function has no problems;Test CasesIs a groupUnit TestThese unit tests work together to verify that the behavior of the function meets the requirements in various circumstances. Good test cases take into account various input that a function may receive, including tests for all of these scenarios.Full coverage test casesIncludes a set of unit tests that cover various possible function usage methods. For large projects, full coverage testing may be difficult. Generally, you only need to write and test the important behaviors of the code at the beginning, so that the project can be fully covered when it is widely used.

11.1.2 tests that can pass

It takes some time to get used to the syntax for creating a test case. However, after creating a test case, it is easy to add a unit test for the function. To write test cases for a function, you can first import the unittest module and the function to be tested, and then create a function that inherits unittest. testCase class, and write a series of methods to test different aspects of function behavior.

The following is a test case that contains only one method. It checks whether the get_formatted_name () function works correctly when the given name and surname are used:

Import unittest

From name_function import get_formatted_name

Class NameTestCase (unittest. TestCase): -- (1)
'''Test name_function.py '''

Def test_first_last_name (self ):
''' Can I handle names like janis joplin correctly? '''
Formatted_name = get_formatted_name ('janis ', 'jobin') -- (2)
Self. assertEqual (formatted_name, "Janis Joplin") -- (3)

Unittest. main ()
First, we imported the unittest module and the get_formatted_name () function to be tested (). At (1), we created a class named NamesTestCase, which contains a series _
Formatted_name () unit test. We can name this class at will, but it is better to make it look related to the function to be tested and contain the word "Test. This class must inherit the unittest. TestCase class
So that Python can know how to run the test we have compiled.
NamesTestCase only contains one method to test one aspect of get_formatted_name. We name this method test_first_last_name (), because what we want to verify is
Only the first and last names can be correctly formatted. When test_name_function.py is run, all methods headers with test _ will run automatically. In this method, we call the function to be tested.
And stores the returned values to be tested. In this example, we call get_formatted_name () using the real parameters 'janis 'and 'jobin', and store the results in the variable formatted_name.
In section (3), we use one of the most useful functions of the unittest class:Assertion Method. The assertion method is used to verify whether the obtained result is consistent with the expected result. Here, we know that get_forma
Tted_name () should return such a name, that is, the first letter of the first and last names is capitalized, and there is a space between them, so we expect the value of formatted_name to be Janis Joplin. To check whether it is true, as shown in figure
Here, we call the unittest method assertEqual () and pass it formatted_name and 'janis joplin '. Code line self. assertEqual (formatted_name, 'janis joplin'
) Means: Compare the value of formatted_name with the string 'janis joplin'. If they are equal, everything is fine. If they are not equal, let me say it! "
The code line unittest. main () allows Python to run the test in this file. When test_name_function.py is run, the output is as follows:
The period in line 1 indicates that a test has passed. The next line shows that Python runs a test, which consumes less than 0.001 seconds. The final OK indicates all unit tests in the test case.
All passed.
The above output indicates that the get_formatted_name () function can always be correctly processed when the include name and surname are given. After get_formatted_name () is modified, run the test case again. If it
After the call, we know that this function can still be correctly processed when a name such as Janis Joplin is given.

11.1.3 failed tests
If the test fails, what is the result? Let's modify get_formatted_name () so that it can process the intermediate name, but in doing so, we intentionally make this function unable to process properly like Janis Joplin
In this way, only the first and last names are available.
The following is a new version of get_formatted_name ().
It contains a lot of information, because the test is not passed, there may be a lot of things to let us know. The 1st row output only contains the letter E, which indicates that a unit test in the test case causes an error. Next
In NamesTestCase, test_first_last_name () causes an error. When a test case contains multiple unit tests, it is important to know that the test fails. At (3), we can see
A standard traceback that indicates that the function call get_formatted_name ('janis ', 'jobin') is faulty because it lacks an essential location real parameter.
We can see that a unit test is run. Finally, a message is displayed, indicating that the entire test case failed because an error occurred while running the test. This message is at the end of the output,
Let's see at a glance-we don't want to read the long output to learn how many tests failed.

11.1.4 What should I do if the test fails?
What if the test fails? If the conditions we check are correct, if the test passes, it means that the function behavior is correct. If the test fails, it means that the new code we write is wrong. Therefore, the test is not
When passing the test, do not modify the test. Instead, fix the code that causes the test to fail: Check the modifications just made to the function to find out the changes that cause the function behavior to be invalid.
In this example, get_formatted_name () requires only two real parameters -- the first and last names, but now it requires the first, middle, and last names. The new intermediate name parameter is required, which causes
Get_formatted_name () does not meet the expectation. Here, the best choice is to make the intermediate name optional. After this is done, when a test is performed using a name similar to Janis Joplin
Yes, and the function can accept the intermediate name. Modify get_formatted_name (), set the intermediate name as optional, and then run the test case again. If it passes, we proceed
Make sure that this function can properly process the intermediate name.

11.1.5 add new test
After you confirm that get_formatted_name () can properly process a simple name, we will write a test to test the name containing the intermediate name. To this end, we add
One method:

11.2 test class
In the first half of this chapter, we have compiled a test for a single function. Next we will compile a test for the class. Classes are used in many programs, so it is helpful to prove that our classes can work correctly.
. If the test for the class is passed, we can be sure that the improvements made to the class do not accidentally damage its original behavior.

11.2.1 various asserted Methods
Python provides many asserted methods in the unittest. TestCase class. As mentioned above, the assertion method checks whether the conditions we think should be met are indeed met. If this condition is true
The assumption of program behavior is confirmed, and we can be sure that there are no errors. If we believe that the conditions that should be met are not actually met, Python will cause an exception.
Table 11-1 describes six common asserted methods. You can use these methods to verify that the returned value is equal to or not equal to the expected value, the returned value is True or False, and the returned value is in the list or not in the list. Me
You can only use these methods in the class that inherits unittest. TestCase. Let's take a look at how to use one of them in the test class.

Method Purpose
AssertEqual (a, B) Verify a = B
AssertNotEqual (a, B) Verify! = 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) Verifying that item is not in list

Conclusion 11.3
In this chapter, we learned how to use tools in the unittest module to write tests for functions and classes, how to compile classes that inherit unittest. TestCase, and how to compile test methods
Verify that the actions of functions and classes are as expected; How to Use setUp () to efficiently create instances based on classes and set their attributes so that they can be used in all test methods of classes.
Testing is a topic that many beginners are not familiar. As a beginner, it is not necessary to write tests for all your projects. However, when you are involved in a project with a large workload, you should compile your own functions and classes.
Tests important behaviors. In this way, we can be more sure that our work will not damage other parts of the project, and we can improve the existing code as we like. If the original function is accidentally damaged
So that you can easily fix the problem. It is much easier to take measures when the test fails than wait for an unsatisfied user to report a bug.
If we include a preliminary test in the project, other programmers will admire you more, and they will be more comfortable trying to use the code we have written and willing to work with you to develop the project. If we want
To share code with projects developed by other programmers, we must prove that the code we have compiled has passed both tests, and we usually need to write tests for your new behaviors.
Familiarize yourself with the code testing process by conducting more tests. For functions and classes compiled by yourself, write tests for important behaviors. However, do not try to write full-coverage test cases in the early stages of the project.
There is no sufficient reason to do so.


 

 

 

Enter 'q' at any time to quit.

Please give me a first name: geng
Please give me a last name: changxue
Neatly formatted name: Geng Changxue.

Please give me a first name: jains
Please give me a last name: joplin
Neatly formatted name: Jains Joplin.

Please give me a first name: q

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.