代码改变世界

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

  Tanwheey  阅读(23)  评论(0编辑  收藏  举报
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# -*- 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('所有用例生成完毕')

  

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2021-04-23 使用 Cygwin 在 Windows 中使用 Linux 命令
点击右上角即可分享
微信分享提示