Python + unittest Learning notes for unit testing

Source: Internet
Author: User

Unit testing plays an important role in ensuring development efficiency, maintainability and software quality, so-called unit testing is a test method for correctness detection of a class, a module or a function.

Here are some of the learning notes that are done by using Python + unitest as a unit test.

UnitTest provides test cases, test suites, test Fixtures,test Runner:

    • Test Case: By inheriting the TestCase class, we can create a test, or a set of tests
    • Test Suites : Testing suite, loading test case into the testing suite when used
    • Test Fixtures : Setup + Test case + teardown, which runs Setup->test_case->teardown each test case executes, so setup and tear Down can be used to do the initialization of the environment. For example, write a class about data manipulation, Setup places a connection database, and TearDown closes the database connection.

First, use of Unittest.main ()

All test case starts with test, such as Def test_pass_case (self)

Examples of specific unit tests are as follows:

ImportUnitTestdefCalc (x, y):returnX +yclassTestcalc (unittest. TestCase):deftest_pass_case (self):" "This is the test case passed" "        Print('This is through use cases') Res= Calc () self.assertequal (3, Res) self.assertnotequal (2,3)    defSetUp (self):#it executes before each use case executes        Print('I'm setup .')    defTearDown (self):#Each use case executes after it is run        Print('I'm teardown .') @classmethoddefSetupClass (CLS):#all use cases are executed before setUp ()        Print('I'm SetupClass .')#Once all the use cases have run, after Setdown@classmethoddefTeardownclass (CLS):#After all the use cases are executed once, after Setdown ()        Print('I'm Teardownclass .')    deftest_a (self):" "This is a normal test case." "        Print('a')    deftest_fail_case (self):" "This is a failed test case" "        Print('This is a failed test case.') Res= Calc (9,8) self.assertequal (98, Res)defTest_haha (self):" "this is haha" "Self.assertequal (The)if __name__=='__main__': Unittest.main ()#It will help you run all of the current test cases in this Python

As you can see, the order of execution is: Static method SetupClass (), Setup, test case, Setdown->, .... testdo, testcase, Setup, WN-static method Setdownclass ().

So you can use SetupClass, teardownclass to do all use cases of the predecessor initialization and end.

Unittest.main () #它会帮你运行当前这个python里面所有的测试用例

II. application of Htmltestrunner to generate test report

if __name__=='__main__': Suite= UnitTest. TestSuite ()#define a test suiteSuite.addtest (Testcalc ('Test_pass_case'))#Add test Cases to the test suiteSuite.addtest (Testcalc ('test_a')) F= Open ('report.html','WB')#Open an HTML file that saves the resultsRunner = Htmltestrunner.htmltestrunner (stream=f,title='Test Report', description='Test Situation')#the object that generated the execution caseRunner.run (Suite)#Run

You can add a few test case to test suite, so that only the results of these two test examples are generated in the report.

Specific as follows:

You can add all of the test case in the class to test suite, as follows

Suite.addtests (Unittest.makesuite (Testcalc))# Add all the test cases in the class to the test suite

The results obtained from the test report are:

C. Test case for the entire project, generate testing reports

For example, there are the following structures:

Test_buy about the purchase of cases, Test_login is about the cases of login, Test_reg is about the registration of cases, run_all_cases perform all cases

Note that in Test_buy, the case in Test_login,test_reg needs to start with test so that it is executed, and that the three files do not necessarily start with test, but only for the sake of convenience, but must have the same rules, For example, the filenames here start with Test_.

The run_all_cases.py code looks like this:

ImportUnittest,htmltestrunnersuite=UnitTest. TestSuite () all_cases= Unittest.defaultTestLoader.discover ('.','test_*.py')#first parameter: from which directory, the second parameter: Define a rule#For case in all_cases:#suite.addtests (case)[Suite.addtests (case) forCaseinchAll_cases]#list generation, as in the above notationf = open ('new_report.html','WB')#Open an HTML file that saves the resultsRunner = Htmltestrunner.htmltestrunner (stream=f,title='Test Report', description='Test Situation')#the object that generated the execution caseRunner.run (Suite)#Run

Iv. Integrated Jenkins to generate a test report that Jenkins can identify

The Xmlrunner module is used here, and Jenkins can recognize the XML format.

Runner = Xmlrunner. Xmltestrunner ('. ') # current directory

The above is a brief summary of UnitTest, follow-up will continue to update.

Python + unittest to do Unit test learning notes

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.