testRun.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env python3
  2. """
  3. Allure测试运行主入口文件 - Windows专用版
  4. 用于运行Tests文件夹中的所有测试用例并生成Allure报告
  5. """
  6. import os
  7. import subprocess
  8. import sys
  9. from pathlib import Path
  10. # 配置路径
  11. TESTS_DIR = "Tests" # 测试用例目录
  12. ALLURE_RESULTS_DIR = "Reports/allure-results" # Allure原始数据目录
  13. ALLURE_REPORT_DIR = "Reports/allure-report" # Allure报告输出目录
  14. def run_command(cmd, description=""):
  15. """运行命令并处理Windows下的编码问题"""
  16. if description:
  17. print(f"\n{description}")
  18. print("-" * 50)
  19. # 在Windows上使用特定的编码处理
  20. if sys.platform == "win32":
  21. # 使用shell=True可以避免一些Windows上的路径问题
  22. process = subprocess.Popen(
  23. cmd,
  24. shell=True,
  25. stdout=subprocess.PIPE,
  26. stderr=subprocess.PIPE,
  27. universal_newlines=True, # 以文本模式处理输出
  28. encoding='utf-8', # 强制使用UTF-8编码
  29. errors='replace' # 替换无法解码的字符
  30. )
  31. else:
  32. process = subprocess.Popen(
  33. cmd,
  34. stdout=subprocess.PIPE,
  35. stderr=subprocess.PIPE,
  36. universal_newlines=True
  37. )
  38. stdout, stderr = process.communicate()
  39. return process.returncode, stdout, stderr
  40. def run_tests():
  41. """运行测试并生成Allure报告"""
  42. # 确保目录存在
  43. Path(ALLURE_RESULTS_DIR).mkdir(exist_ok=True)
  44. Path(ALLURE_REPORT_DIR).mkdir(exist_ok=True)
  45. print("=" * 50)
  46. print("开始运行测试...")
  47. print("=" * 50)
  48. # 构建pytest命令
  49. pytest_cmd = [
  50. sys.executable, "-m", "pytest",
  51. TESTS_DIR,
  52. f"--alluredir={ALLURE_RESULTS_DIR}",
  53. "--clean-alluredir", # 清理之前的测试结果
  54. "-v" # 详细输出
  55. ]
  56. # 运行测试
  57. returncode, stdout, stderr = run_command(pytest_cmd, "运行测试用例")
  58. # 输出测试结果
  59. print(stdout)
  60. if stderr:
  61. print("错误信息:", stderr)
  62. # 检查测试是否成功
  63. if returncode not in [0, 1]: # 0: 所有测试通过, 1: 有测试失败
  64. print(f"测试执行失败,退出码: {returncode}")
  65. return False
  66. print("=" * 50)
  67. print("测试执行完成,正在生成Allure报告...")
  68. print("=" * 50)
  69. # 生成Allure报告
  70. allure_cmd = [
  71. "allure", "generate",
  72. ALLURE_RESULTS_DIR,
  73. "-o", ALLURE_REPORT_DIR,
  74. "--clean"
  75. ]
  76. # 运行Allure生成命令
  77. returncode, stdout, stderr = run_command(allure_cmd, "生成Allure报告")
  78. if returncode == 0:
  79. print("=" * 50)
  80. print("Allure报告生成成功!")
  81. print(f"报告位置: {os.path.abspath(ALLURE_REPORT_DIR)}")
  82. print("=" * 50)
  83. else:
  84. print("Allure报告生成失败:")
  85. print(stderr)
  86. return False
  87. return True
  88. if __name__ == "__main__":
  89. success = run_tests()
  90. sys.exit(0 if success else 1)