Python:discover () method batch execution use case

Source: Internet
Author: User

During automated testing, the relationship between the functional points of automation coverage and the corresponding test cases is basically 1 VS N, and if each test case is executed individually each time, it is not only inefficient,

The test results cannot be quickly fed back and are cumbersome to maintain. In the Python unit Test framework UnitTest, a method for batch execution of test cases is provided.

This blog, describes the common classes and methods of the UnitTest framework, and the method of using the Discover () method to execute test cases in bulk ...

Official document: UnitTest Unit Test framework

First, the UnitTest framework

Let's start by introducing the UnitTest framework and several modules that are related to executing test cases:

1, TestCase () class

An instance of the TestCase class represents a logical test unit in UnitTest, which is intended to be used as a base class, and the specific test is implemented by a specific subclass. This class implements the interface required by the test runner to allow it to drive the test,

and test code can be used to examine and report on various types of failure methods. Each instance will run a basic method named MethodName for UnitTest.

2. SetUp () method

The main function of this method is to initialize the test environment, which is called immediately before the test case executes, except for Assertionerror or skiptest, any exceptions generated by this method will be considered to be wrong.

Only the test executes successfully, it is called, and nothing is done by default.

3. TearDown () method

The main purpose of this method is to record test results and restore the test environment after the test case has been executed, and this method is called even if an exception occurs.

4. Run () method

The function of this method is to run the test case and collect the test results into the TestResult as the passed object.

If you omit the result or create a temporary result object with none (by calling the Defaulttestresult () method), the resulting object is returned to the caller of Run ().

5. Defaulttestresult () method

The method returns the test result that should be used for this test case class as an instance (if there are no other results, the instance should be returned to the run () method).

6, TestSuite () class

This class represents a collection of individual test cases and test suites. It provides the interfaces required to run tests so that they can run like other tests. Testsuite instances and traversal suites run each test case separately.

The behavior of Testsuite is very similar to testcase, but it does not actually perform the test, but is used to aggregate the test cases together, and the following 2 methods are used to add test cases to the Testsuite instance:

Addtest (): Add test Case to testcase or Testsuite suite;

Addtests (): Adds all the test cases in the iteration testcase and Testsuite instances to this test component, which is equivalent to invoking each element of Addtest ().

7, Testloader () class

The Testloader class is used to create a test suite of classes and modules. You typically do not need to create an instance of the class. The UnitTest framework provides an instance unittest.defaulttestloader that can be shared.

8. Discover () method

Discover (start_dir, pattern = ' Test *.py ', Top_level_dir = None )

start_dir: the module name or test case directory to be tested;

pattern= ' test*.py ': indicates the matching principle of use case file name, the following example matches the file name ". py" file that starts with "test", and the asterisk "*" denotes any number of characters;

Top_level_dir=none: The top-level directory of the test module, if there is no top-level directory, the default is None;

This method finds all test modules recursively from the specified start directory to subdirectories, and returns the Testsuite object that contains them, only the test file that matches the pattern and the name of the module that can be imported are loaded.

All test modules must be imported from the top level of the project, and if the starting directory is not a top-level directory, the top-level directory must be specified separately.

If the name of a test file conforms to pattern, it checks whether the file contains the load_tests () function, and if the load_tests () function exists, it is the function that is responsible for loading the test cases in this file.

If it does not exist, it executes loadtestsfrommodule (), looking for a method in the file that derives from the TestCase class that contains the test.

9, TestResult () class

This class is used to record information about which tests succeeded or failed. A TestResult object stores the results of a set of tests, guaranteeing that the results are correctly recorded in TestCase and Testsuite.

The test framework U nittest needs to access TestResult to run the objects generated by a set of tests for reporting purposes, and TestRunner.run() returns an instance of TestResult and methods for this purpose.

Ii. examples of addtest ()

For example, if the test case has the following:

Use the Addtest () method to execute the test case, as shown in the sample code:

#Coding=utf-8ImportUnitTest#Load Test CasesImportTest_userImportTest_mobileImportTest_mobcodeImportTest_txtcodeImporttest_pwdImportTest_signupImportTest_loginImportTest_vipcenterImportTest_search#to add a test case to a test collectionSuite =UnitTest. TestSuite () suite.addtest (Test_user. Usertest ("Test_user"))#User nameSuite.addtest (Test_mobile. Mobiletest ("Test_mobile"))#Mobile phone numberSuite.addtest (Test_mobcode. Mobcodetest ("Test_mobcode"))#mobile phone Verification CodeSuite.addtest (Test_txtcode. Txtcodetest ("Test_txtcode"))#Graphics Verification CodeSuite.addtest (test_pwd. Passwordtest ("test_pwd"))#PasswordSuite.addtest (Test_signup. Signuptest ("Test_signup"))#Registration FunctionSuite.addtest (Test_login. Logintest ("Test_loggin"))#Login FunctionSuite.addtest (Test_vipcenter. Viptest ("TEST_VIP"))#Member CenterSuite.addtest (Test_search. Searchtest ("Test_search"))#search Function#Run test CasesRunner =UnitTest. Texttestrunner () Runner.run (suite)

You can see a lot of use case import and add operations, if the use case hundreds of thousands of articles, then it will be a disaster!!!

Third, Discover () Use example

Or the above test cases, this time use the Discover () method to bulk execute the use case, the sample code is as follows:

#Coding=utf-8ImportUnitTest fromUnitTestImportDefaulttestloader#test Case Storage PathCase_path ='./testcase/case'   #get all test Casesdefget_allcase (): Discover= Unittest.defaultTestLoader.discover (Case_path, pattern="test*.py") Suite=UnitTest. TestSuite () suite.addtest (Discover)returnSuiteif __name__=='__main__':    #Run test CasesRunner =UnitTest. Texttestrunner () Runner.run (Get_allcase ())

The Discover () method is more convenient and efficient than the Addtest () method, and can also improve the test feedback rate.

PS: using the Discover () method, remember that the test method that needs to be executed in the testing case must start with test, otherwise it cannot be loaded!!!

The above is a description of some common classes and methods of the UnitTest framework, as well as 2 ways to execute test cases in bulk, for reference only ...

Python:discover () method batch execution use case

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.