首页 > 编程语言 >批量将excle文档用例转为python脚本

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

时间:2024-04-23 17:34:38浏览次数:33  
标签:index space python write 用例 values df excle

# -*- 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('所有用例生成完毕')

  

标签:index,space,python,write,用例,values,df,excle
From: https://www.cnblogs.com/Tanwheey/p/18153356

相关文章

  • python 基础习题2--字符串切片技术
    1. 有如下字符串str='123456789'字符串切片技术,例如,返回输出从第三个开始到第六个的字符(不包含)即得到:345利用字符串切片技术,代码可以这么写:print(str[2:5])如果想返回如下八行结果,利用字符串切片技术,如何编写代码?12345678912345678134534567892412345678912345678......
  • python 基础习题1--基础语法
    1.书写代码,输出结果为: 答案:print("Hello,Python!")ViewCode 2. ......
  • Python——Reflex安装
    Reflex 是一个开源框架,用于在纯Python 中快速构建美观的交互式Web应用程序。安装环境:Ubuntu23.04(完成软件更新)安装虚拟环境sudoapt-getinstallpython3-venv创建项目mkdirmy_app_namecdmy_app_name 进入虚拟环境python3-mvenv.venvsource.venv/bin/act......
  • Pycharm报错:ReadTimeoutError: HTTPSConnectionPool(host=‘files.pythonhosted.org‘
    今天在pycharm里面pipinstall库的时候报了这个错,如图所示:第一种,设置超时时间,命令如下:pip--default-timeout=1000install-U模块名第二种,用镜像网站进行下载,这种方法下载的速度超快的哦=.=,命令如下:pip--default-timeout=100install库名称-ihttp://pypi.douban.com/......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-39-highlight() 方法之追踪定位
    1.简介在之前的文章中宏哥讲解和分享了,为了看清自动化测试的步骤,通过JavaScript添加高亮颜色,就可以清楚的看到执行步骤了。在学习和实践Playwright的过程中,偶然发现了使用Playwright中的highlight()方法也突出显示Web元素。与之前的方法有异曲同工之妙。而且很简单。highlight()......
  • python 常用内置函数
    len()len(iterable):返回给定序列(可迭代对象)的长度或元素个数。list1=[1,2,3,4,5]print("列表长度:",len(list1))issubclass()issubclass(class,classinfo):检查一个类是否是另一个类的子类,返回True或False。classBase:passclassDerived(Base):pass......
  • AgileTC --滴滴开源测试用例管理平台环境搭建
    一、前言之前看到公司别的部门有分享自己做的用例管理平台,看了下也是基于开源部署的,于是自己也查了下比较主流且开源的用例管理平台,最后选择了滴滴的AgileTC。先在本地环境搭建好试用下,后续考虑用docker部署到服务器上。AgileTC是一套敏捷的测试用例管理平台,支持测试用......
  • 记一个简单测试端口的python脚本
    脚本的简单功能:支持IPv4和IPv6支持TCP和UDP端口importsocket,ipaddressfromenumimportEnumclassMode(Enum):TCP=0UDP=1def__repr__(self):returnself.name__str__=__repr__defis_port_open(ip:str,port:int,mode:......
  • python随机点名-图片版
    先创建图片文件夹,图片名就是用户名fromtkinterimport*fromPILimportImage,ImageTkimporttime,random,osclassRandomName(Frame):def__init__(self,parent=None,**kw):Frame.__init__(self,parent,kw)self._timer=Noneself.......
  • python实现随机点名
    新建txt文本,输入名字,每个进行换行fromtkinterimport*importtimeclassRandomName(Frame):def__init__(self,parent=None,**kw):Frame.__init__(self,parent,kw)self._timer=Noneself._start=0.0self._elapsedtime=0......