#!/usr/bin/env python3 """ Allure测试运行主入口文件 - Windows专用版 用于运行Tests文件夹中的所有测试用例并生成Allure报告 """ import os import subprocess import sys from pathlib import Path # 配置路径 TESTS_DIR = "Tests" # 测试用例目录 ALLURE_RESULTS_DIR = "Reports/allure-results" # Allure原始数据目录 ALLURE_REPORT_DIR = "Reports/allure-report" # Allure报告输出目录 def run_command(cmd, description=""): """运行命令并处理Windows下的编码问题""" if description: print(f"\n{description}") print("-" * 50) # 在Windows上使用特定的编码处理 if sys.platform == "win32": # 使用shell=True可以避免一些Windows上的路径问题 process = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, # 以文本模式处理输出 encoding='utf-8', # 强制使用UTF-8编码 errors='replace' # 替换无法解码的字符 ) else: process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) stdout, stderr = process.communicate() return process.returncode, stdout, stderr def run_tests(): """运行测试并生成Allure报告""" # 确保目录存在 Path(ALLURE_RESULTS_DIR).mkdir(exist_ok=True) Path(ALLURE_REPORT_DIR).mkdir(exist_ok=True) print("=" * 50) print("开始运行测试...") print("=" * 50) # 构建pytest命令 pytest_cmd = [ sys.executable, "-m", "pytest", TESTS_DIR, f"--alluredir={ALLURE_RESULTS_DIR}", "--clean-alluredir", # 清理之前的测试结果 "-v" # 详细输出 ] # 运行测试 returncode, stdout, stderr = run_command(pytest_cmd, "运行测试用例") # 输出测试结果 print(stdout) if stderr: print("错误信息:", stderr) # 检查测试是否成功 if returncode not in [0, 1]: # 0: 所有测试通过, 1: 有测试失败 print(f"测试执行失败,退出码: {returncode}") return False print("=" * 50) print("测试执行完成,正在生成Allure报告...") print("=" * 50) # 生成Allure报告 allure_cmd = [ "allure", "generate", ALLURE_RESULTS_DIR, "-o", ALLURE_REPORT_DIR, "--clean" ] # 运行Allure生成命令 returncode, stdout, stderr = run_command(allure_cmd, "生成Allure报告") if returncode == 0: print("=" * 50) print("Allure报告生成成功!") print(f"报告位置: {os.path.abspath(ALLURE_REPORT_DIR)}") print("=" * 50) else: print("Allure报告生成失败:") print(stderr) return False return True if __name__ == "__main__": success = run_tests() sys.exit(0 if success else 1)