Python unit testing-in-depth understanding of unittest

Source: Internet
Author: User
Tags shuffle

The importance of unit testing is not much to say, hateful is that there are too many unit testing frameworks and tools in Python, what unittest, TestTools, subunit, coverages, testrepository, Nose, MOX, mock, Fixtures, Discover, plus setuptools, distutils, and so on, don't say how to write unit tests, just how to run unit tests there are n many ways, again because it is testing rather than function, is a lot of people are not interested in touching things. But as a good programmer, not only to write good function code, write good test code to show your strength. There are so many frameworks and tools that are confusing and confusing because they don't understand the fundamentals, and if some basic concepts are unclear, how can you write a clear test code?

Today's theme is UnitTest, as a module in standard Python, is the basis for other frameworks and tools, and reference is its official document: http://docs.python.org/2.7/library/ Unittest.html and source code, the document has been written very well, I am here to record mainly some of its important concepts, key points and may encounter some of the pits, the purpose is to deepen understanding of unittest, rather than stay on the general surface layer.

UnitTest is a python version of the junit,junit is the unit test framework in Java, the unit test for Java, one sentence is very appropriate: Keep the bar green, I believe that the use of Eclipse written Java unit test the hint. UnitTest implements many of the concepts in junit, such as the test case, test suite, and so on that we are very familiar with, in short, the principle is the same, but in different languages expressed.

At the beginning of the document, we introduced the 4 important concepts in UnitTest: Test fixture, test case, test suite, Test runner, and I think that only by understanding these concepts can I really understand the fundamentals of unit testing, The following is the main focus on these concepts to expand this article.

    • An example of a testcase is a test case. What is a test case? is a complete test process that includes the setup of the pre-test preparation environment, the execution of the test code (run), and the restoration of the post-test environment (TearDown). The nature of the meta-Test (unit test) is here, a test case is a complete test unit, which can be verified by running the test unit.
    • Multiple test cases are assembled together, which is testsuite, and testsuite can also nest testsuite.
    • Testloader is used to load testcase into Testsuite, and there are several loadtestsfrom__ () methods that are looking for testcase from various places, creating instances of them, and then add to Testsuite, Returns a Testsuite instance.
    • Texttestrunner is to execute the test case, where run (test) executes the run (Result) method in Testsuite/testcase.
    • The results of the test are saved to the Texttestresult instance, including information about how many test cases were run, how many succeeded, and how many failed.

So the whole process is clear, first of all to write good testcase, and then by Testloader load TestCase to Testsuite, then texttestrunner to run Testsuite, The results of the run are saved in Texttestresult, and the entire process is integrated in the Unittest.main module.

Now that we've covered the three concepts of test case, test suite, Test runner, and test fixture not mentioned, what is test fixture?? In the docstring of TestCase, there is this passage:

Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test ' s environment (' fixture ') can be implemented by overriding the ' SetUp ' and ' Te Ardown ' methods respectively.

As can be seen, the construction and destruction of a test case environment is a fixture, implemented by overwriting the TestCase setup () and teardown () methods. What's the use of this? For example, in this test case you need to access the database, you can establish a database connection in Setup () and some initialization, clear the data generated in the database in Teardown (), and then close the connection. Note that the process of teardown is very important, to leave a clean environment for the future testcase. About fixture, there is also a special library function called fixtures, more powerful, will be introduced in the future.

At this point, the concept and the process is basically clear, the following through a simple example to practice, take unittest The example of the document:

ImportRandomImportUnitTestclasstestsequencefunctions (unittest. TestCase):defsetUp (self): Self.seq= Range (10)    deftest_shuffle (self):#Make sure the shuffled sequence does no lose any elementsrandom.shuffle (SELF.SEQ) Self.seq.sort () self.assertequal (SELF.SEQ, Range (10))        #should raise an exception for an immutable sequenceSelf.assertraises (TypeError, Random.shuffle,))    defTest_choice (self): element=Random.choice (SELF.SEQ) self.asserttrue (elementinchself.seq)deftest_sample (self): with self.assertraises (valueerror): Random.sample (Self.seq,20)         forElementinchRandom.sample (SELF.SEQ, 5): self.asserttrue (Elementinchself.seq)if __name__=='__main__': Unittest.main ()

Testsequencefunctions inherits from Unittest.testcase, rewrites the Setup () method, and defines three methods that begin with ' test ', what exactly is this testsequencefunctions class? Is it a test case or a three test case? Said to be three test cases, it itself inherits from TestCase, said is a test case, there are three test_* () methods, obviously three test cases. In fact, we just have to look at some testloader how to load test cases, it is clear, in loader. There is a loadtestsfromtestcase () method in the Testloader class:

    defloadtestsfromtestcase (Self, testcaseclass):"""Return A suite of all tests cases contained in Testcaseclass"""        ifIssubclass (Testcaseclass, Suite. TestSuite):RaiseTypeError ("Test cases should not being derived from TestSuite."                                 "maybe meant to derive from TestCase?") Testcasenames=self.gettestcasenames (Testcaseclass)if  notTestcasenames andHasattr (Testcaseclass,'runtest'): Testcasenames= ['runtest'] Loaded_suite=Self.suiteclass (Map (Testcaseclass, testcasenames))returnLoaded_suite

Gettestcasenames () is to find all the methods that begin with "test" from the TestCase class, and then take note of Line 9th, whose parameters use a map method when constructing Testsuite objects, that is, for each element in the Testcasenames, Using Testcaseclass to construct the object, the result is a collection of TestCase objects, which can be explained in step by line with the following code:

Testcases = [] for in testcaenames:    = self.suiteclass (tuple (testcases))

It can be seen that for each method that starts with test, a TestCase object is built for it, and it is worth noting that if you do not define the method at the beginning of test, but instead write the code in a method called Runtest, The TestCase object is then constructed for the Runtest method, and the Runtest method is ignored if the method at the beginning of the test is defined.

At this point, the basic is clear, every method beginning with test, will build TestCase object for it, that is to say testsequencefunctions class in fact defined three testcase, the reason is written like this, is for convenience, Because the fixture of these test cases are the same, there will be a lot of redundant code if each test case is written separately as a testcase.

Understand this, the document can be easily understood, as to how to run the test cases, as well as other content, read the document directly

Reference: http://blog.csdn.net/hackerain/article/details/24095117

Python unit testing-in-depth understanding of unittest

Related Article

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.