[Pytest interface automation] Use the main function main() to start Pytest

1. Background:

The operation mode of Pytest includes the command line mode and the main function of main(). This article mainly introduces the driving of Pytest through the main function.

2. Code introduction:

2.1. Code details:

# 创建main.py文件,主函数执行框架用例并生成allure测试报告
if __name__ == '__main__':
    # 按配置清除测试报告
    clearReports().clear_reports()
    file_name = os.path.basename(__file__).split('.')[0]  # 获取档前的文件名称(不带后缀),作为存放
    time_stamp = str(int(time.time()))  # 用时间戳生成一串不重复的数字
    html_path = f'{
      
      BASE_DIR}/report/html/'
    if not os.path.exists(html_path):
        os.makedirs(html_path)
    new_dir_name = str(file_name) + time_stamp  # 生成测试报告文件名称
    new_html_path = f'{
      
      BASE_DIR}/report/html/' + new_dir_name  # 生成html报告文件名称
    os.mkdir(new_html_path)

    pytest.main(['-s', '-v', f'--env={
      
      ENV_Default}', f'{
      
      BASE_DIR}/conftest.py::test_start'])
    pytest.main(['-s', '-v', f'{
      
      BASE_DIR}/test_cases/test_product/tax',
                 f'{
      
      BASE_DIR}/test_cases/test_product/credit',
                 '--reruns=1', '--reruns-delay=2',  # 对失败用例重跑一次,重跑前间隔2s
                 '--alluredir', f'{
      
      BASE_DIR}/report/xml/' + new_dir_name])  # 生成xml
    # 此时就在项目report文件下生成以:当前文件名称+时间戳生成的.xml和.html文件,在html下即可查看生成的allure报告文件
    command_word = f'allure generate {
      
      BASE_DIR}/report/xml/{
      
      new_dir_name} -o {
      
      BASE_DIR}/report/html/{
      
      new_dir_name} --clean'
    os.system(command_word)  # 执行cmd命令,生成html
    # 清除根目录下含有:interface-autotest-pytest路径的文件
    clearReports().clear_interface()
    # 直接打开生成的allure报告
    os.system(f'allure open {
      
      BASE_DIR}/report/html/{
      
      new_dir_name}')

After the allure report is generated, it can be opened directly in the local browser, and the URL can be shared in the LAN to achieve sharing

2.2. Recursively delete path files:

2.2.1, code introduction

Use the os function to judge whether the path exists, so as to make corresponding logic for the path, shutil- execute recursive action

    def clear_interface():
        # 清除根目录下含有:interface - autotest - pytest路径的文件
        if os.path.exists(INTERFACE): # 判断是否存在该路径
            shutil.rmtree(INTERFACE) # 将目录及目录下的文件执行递归删除
            self.log.info(f"清理路径:{
      
      INTERFACE}完成")

In this way, the directories and files under the specified path can be effectively cleared

2.3. The hook function obtains the test case name and use case node:

2.3.1. Code introduction:

Through this function, write it in the conftest.py folder without importing and collecting the test cases and execute it automatically

def pytest_collection_modifyitems(items):
    list_node_credit = []
    list_node_tax = []
    for item in items:
        item1 = str(item.name.encode("utf-8").decode("unicode-escape")).split("::")[0]
        item2 = str(item.nodeid.encode("utf-8").decode("unicode-escape")).split("::")[0]
        # list_name.append(item.name)
        if 'test_product/credit' in item2:
            list_node_credit.append(item2)
        if 'test_product/tax' in item2:
            list_node_tax.append(item2)

    print(f"搜集tax测试用例节点:{
      
      list_node_tax}")
    print(f"搜集credit测试用例节点:{
      
      list_node_credit}")
    print(f"搜集tax测试用例个数:{
      
      len(list_node_tax)}")
    print(f"搜集credit测试用例个数:{
      
      len(list_node_credit)}")

After the execution is complete, you will clearly see the number of test cases for each domain
insert image description here

Guess you like

Origin blog.csdn.net/weixin_52358204/article/details/127392610