Python-discover () method and execution order supplement

Source: Internet
Author: User

Can create different test files according to different functions, even different test directories, test files can also be divided into different small functions into different test classes, under the class to write test cases, to make the overall structure clearer

But adding and removing test cases through addtest () becomes cumbersome

The Discover () method provided in the Testloader class can automatically identify test cases

Discover (start_dir,pattern= ' test*.py ', top_level_dir= None)

Find all the test modules in the specified directory and recursively check the test module under subdirectories, only load when matching to file name

Start_dir: The module name or test case catalog to be tested

Pattern= ' test*.py ': represents the matching principle for use case filenames. This matches a. py type file that starts with "test", * 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

Example 1:

Import UnitTest
Test_dir = './'
#定义测试目录为当前目录
Discover = Unittest.defaultTestLoader.discover (test_dir,pattern= ' test*.py ')

if __name__ = = ' __main__ ':
Runner = UnitTest. Texttestrunner ()
Runner.run (Discover)
The Discover () method automatically finds the test case file based on the test catalog Test_dir match and assembles the found test case into the test suite, so you can go directly through the
The run () method performs discover, which greatly simplifies the search and execution of test cases.

Example 2:
Suite = UnitTest. TestSuite ()
all_cases = Unittest.defaultTestLoader.discover (Py_path, ' test*.py ')
The #discover () method automatically finds the test case file (test*.py) based on the test catalog match and assembles the found test case into the test suite
[Suite.addtests (case) for case in all_cases]
report_html = Beautifulreport.beautifulreport (Suite)
Second, the order of use case execution

If you want a test case to execute first, you cannot use the default main () method, which needs to be loaded in a certain order by the Addtest () method of the Testsuite class.

Discover (start_dir,pattern= ' test*.py ', Top_level_dir=none)
Find all the test modules under the specified directory, and recursively check the test blocks under subdirectories, only the matching filenames will be loaded. If you are not starting a top-level directory, the top-level directory must be specified separately.

    • Start_dir: The directory of the module name or test case to be tested.
    • Pattent= ' test*.py ': represents the matching principle for use case filenames. This matches all the. PY type files that begin with the file name a test, * 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.
Import unittest  Import JSON  import requests from  Htmltestrunner import htmltestrunner  import time            #定义测试用例的目录为当前目录  test_dir = './'  discover = unittest.defaultTestLoader.discover (Test_dir,pattern = ' Test *.py ')        if __name__== "__main__":                      #按照一定的格式获取当前的时间 now      = Time.strftime ("%y-%m-%d%h-%m-%s")                    # Define the report storage path      filename = './' + now + ' test_result.html '                fp = open (filename, "WB")          #定义测试报告      runner = Htmltestrunner (stream =  fp,                              title = "XXX Interface Test Report",                              description = "Test Case execution:")          #运行测试      Runner.run (Discover)      fp.close () #关闭报告文件  

The following is a direct illustration of discover usage:

First, the preparatory work

Directory structure:

discovercase.py File Code:

Import Unittestimport osdef discover_case (case_dir):    # Directory testcase = UnitTest of the case to be executed    . TestSuite ()    discover = Unittest.defaultTestLoader.discover (case_dir,pattern= "*.py",top _level_dir=none)    # Discover method filter out the use case, loop add to test suite    print (Discover) for    Test_suite in Discover:        For test_case in Test_suite:            print (Test_case)            # Add case to TestCase            #testcase. addtests (test_case)            Testcase.addtests (test_case)    return (testcase) path = Os.path.join (OS.GETCWD (), "Test Cases") Case = Discover_case ( case_dir=path) print (case)

Test1 Code (TEST2~4 code is basically the same):

Note: The execution case in each testcase (that is, the function that starts with test) must be greater than or equal to two, or it will be an error.

Second, after writing this, we'll run the program and see the results.

The file name, class name, and function name of the post-run use case will be traversed.

Note: If the use case name is all Chinese and cannot be loaded, you must start with a letter, such as "I login. Py"

Python-discover () method and execution order supplement

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.