代码改变世界

批量将excle文档用例转为python脚本

2024-04-23 17:25  Tanwheey  阅读(17)  评论(0编辑  收藏  举报
# -*- coding: utf-8 -*-
import time

import pandas as pd
import os

allure_param = {
    "epic": "用例版本名",
    "feature": "用例特性名",
    "story": "用例场景名"
}

df = pd.read_excel(r'D:\aaaaaa.xlsx', index_col=0)


def write_in(f, word='', num=1, space=0):
    if space > 0:
        for i in range(4 * space):
            f.write(' ')
    if word:
        f.write(str(word))
    for i in range(num):
        f.write('\n')


df['目录名称'].fillna(method='ffill', inplace=True)
df.dropna(subset=["用例编号"], inplace=True)

p = df['用例编号']
for index, value in enumerate(p):
    print('##')
    if value.startswith('PROD_') or value.startswith('CHIP_') or value.startswith('MONO_'):
        name = ''
        fun_name = ''
    else:
        name = 'Test_'
        fun_name = 'test_'
    with open(f'{fun_name}{value}.py', 'w+', encoding='utf-8') as f:
        write_in(f, '#!/usr/bin/env python')
        write_in(f, '# -*- coding: utf-8 -*-')
        write_in(f, '"""')
        write_in(f, f'@time : {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}')
        write_in(f, f'@author :  ')
        write_in(f, f'@file : {fun_name}{value}.py')
        write_in(f, '"""')
        write_in(f)
        write_in(f, 'import allure')
        write_in(f, 'import os')
        write_in(f, 'import loguru')
        write_in(f, 'import pytest')
        write_in(f)
        write_in(f, 'log = loguru.logger')
        write_in(f, num=2)
        epic = allure_param.get('epic', df.目录名称.values[index])
        feature = allure_param.get('feature', df.特性标签.values[index])
        story = allure_param.get('story', df.用例名称.values[index])
        write_in(f, f"@allure.epic('{epic}')")
        write_in(f, f"@allure.feature('{feature}')")
        write_in(f, f"@allure.story('{story}')")
        class_data = f"{name}{str(df.用例编号.values[index])}".split("_")
        class_name = ''.join([i.capitalize() for i in class_data])
        write_in(f, f'class {class_name}:')
        write_in(f, '"""', space=1)
        write_in(f, f'casename:\t\t{df.用例名称.values[index]}', space=1)
        write_in(f, f'caseID:  \t\t{df.用例编号.values[index]}', space=1)
        write_in(f, f'runLevel:\t\t{df.用例等级.values[index]}', space=1)
        # write_in(f, f'version: \t\t{df.当前所属版本.values[index]}', space=1)
        write_in(f, f'version: \t\t8030产品化', space=1)
        write_in(f, 'caseDescription:', space=1)
        write_in(f, f'{df.用例名称.values[index]}', space=2)
        write_in(f, 'casePrecondition:', space=1)
        if isinstance(df.预置条件.values[index], str):
            for i in df.预置条件.values[index].split('\n'):
                write_in(f, i, space=2)
        write_in(f, 'caseStep:', space=1)
        if '测试步骤' in df.columns:
            case_step = '测试步骤'
        elif '用例步骤' in df.columns:
            case_step = '用例步骤'
        if isinstance(df[case_step].values[index], str):
            for i in df.测试步骤.values[index].split('\n'):      # 两种情况 excel编写不规范使用 这里
            # for i in df[case_step].values[index].split(' '):
                if i:
                    write_in(f, i.strip(), space=2)
        write_in(f, 'caseExpect:', space=1)
        for i in df.预期结果.values[index].split('\n'):  # 两种情况 excel编写不规范使用 这里
        # for i in df.预期结果.values[index].split(' '):
            if i:
                write_in(f, i.strip(), space=2)

        write_in(f, '"""', space=1)
        write_in(f, num=1)
        write_in(f, "@pytest.fixture(name='pcie')", space=1)
        write_in(f, "def environment_operation(self):", space=1)
        write_in(f, "yield", space=2)
        write_in(f, num=1)

        write_in(f, f"@allure.title('{class_name}')", space=1)

        write_in(f, f"def {fun_name}{str(df.用例编号.values[index]).lower()}(self, pcie):", space=1)

        write_in(f, f'allure.dynamic.description(self.__doc__)', space=2)
        write_in(f, num=1)

        if isinstance(df[case_step].values[index], str):
            for i in df[case_step].values[index].split('\n'):
                write_in(f, f"with allure.step('测试步骤: {i}'):", space=2)
                write_in(f, 'pass', space=3)

        write_in(f, num=2)

        write_in(f, "if __name__ == '__main__':")
        write_in(f, f"pytest.main(['-s', '-v', './{fun_name}{df.用例编号.values[index]}.py',", space=1)
        write_in(f, "'--alluredir', './utils/allure_results'])", space=4)
        write_in(f, 'os.system(r"allure generate ./utils/allure_results/ -o ./utils/allure_report/ --clean ")', space=1)
        print(f'{value}脚本生成成功!')
print('所有用例生成完毕')