pytestuiautomationallure Excel 数据驱动桌面自动化一、安装依赖pipinstallpytest uiautomation allure-pytest openpyxlopenpyxl专门读写xlsx 格式Excel二、调整项目结构desktop_automation/ ├── config/setting.py ├── data/ │ └── case_data.xlsx # Excel测试数据 ├── common/ │ └── read_excel.py # 封装读取Excel工具类 ├── page/ │ ├── base_page.py │ └── notepad_page.py ├── testcase/test_notepad.py ├── conftest.py └── pytest.ini三、Excel 测试数据格式新建data/case\_data\.xlsx工作表名input\_datacase_nameinput_contentexpect_content普通文本输入桌面自动化 Excel 数据驱动桌面自动化 Excel 数据驱动特殊字符输入123#$ 测试123#$ 测试空值输入长文本输入基于 pytestuiautomation 做桌面 UI 自动化基于 pytestuiautomation 做桌面 UI 自动化四、封装 Excel 读取工具 common/read\[_excel.py](_excel.py)fromopenpyxlimportload_workbookclassReadExcel:staticmethoddefget_excel_data(file_path,sheet_name): 读取Excel用例数据返回列表字典格式 :param file_path: excel路径 :param sheet_name: 工作表名 :return: [{},{},...] wbload_workbook(filenamefile_path)wswb[sheet_name]# 获取表头headers[cell.valueforcellinws[1]]data_list[]# 遍历行数据跳过表头forrowinws.iter_rows(min_row2,values_onlyTrue):row_dictdict(zip(headers,row))data_list.append(row_dict)wb.close()returndata_list五、配置文件 config/[setting.py](setting.py)# 被测应用APP_PATHnotepad.exe# 全局等待IMPLICIT_WAIT3# Excel数据路径EXCEL_DATA_PATH./data/case_data.xlsx# Excel工作表名EXCEL_SHEETinput_data六、页面层代码不变base\[_page.py](_page.py) 不变notepad\[_page.py](_page.py) 不变七、Excel 数据驱动测试用例 testcase/test\[_notepad.py](_notepad.py)importpytestfromcommon.read_excelimportReadExcelfrompage.notepad_pageimportNotePadPagefromconfig.settingimportAPP_PATH,EXCEL_DATA_PATH,EXCEL_SHEET# 读取Excel所有测试数据defget_excel_case_data():returnReadExcel.get_excel_data(EXCEL_DATA_PATH,EXCEL_SHEET)classTestNotePadExcelDDT:defsetup_class(self):self.pageNotePadPage()self.page.start_app(APP_PATH)defteardown_class(self):self.page.close_app()# Excel数据驱动参数化pytest.mark.parametrize(case,get_excel_case_data(),idslambdax:x[case_name])deftest_input_by_excel(self,case):Excel数据驱动-记事本输入测试in_textcase[input_content]exp_textcase[expect_content]self.page.input_edit_content(in_text)actualself.page.get_edit_content()assertactualexp_text,f失败预期{exp_text}实际{actual}八、[conftest.py](conftest.py) 失败截图不变importpytestimportallureimportuiautomationasautopytest.hookimpl(tryfirstTrue,hookwrapperTrue)defpytest_runtest_makereport(item,call):outcomeyieldreportoutcome.get_result()ifreport.whencallandreport.failed:try:imgauto.CaptureToImage()allure.attach(img,失败截图,allure.attachment_type.PNG)except:pass九、pytest.ini 不变[pytest] testpaths testcase python_files test_*.py python_classes Test* python_functions test_* addopts -vs --alluredir./report/temp --clean-alluredir十、运行命令# 执行用例pytest# 生成并打开allure报告allure generate ./report/temp-o./report/html--cleanallureopen./report/html十一、扩展用法增加用例状态控制Excel 新增列is\_run值为1执行0跳过读取数据时过滤data_list[dfordindata_listifd.get(is_run)1]区分正向 / 逆向用例Excel 加case\_type字段用例内做不同业务逻辑登录场景直接套用Excel 填账号、密码、预期结果页面写登录方法即可十二、注意事项只支持.xlsx不支持老版.xlsExcel 表头名称必须和代码取值字段完全一致空单元格读取为None代码可自行转为空字符串