# 使得;linux环境可用 #!/usr/bin/env python3 """ 自动化测试框架主入口 支持运行Web测试、API测试、性能测试、安全测试等 """ import argparse import time import sys from datetime import datetime from pathlib import Path # 添加项目根目录到Python路径 project_root = Path(__file__).parent sys.path.append(str(project_root)) from core.config.config_manager import ConfigManager from core.driver.driver_factory import DriverFactory from modules.database.db_client import DBClient from utils.report.report_generator import ReportGenerator from utils.report.email_notifier import EmailNotifier def run_web_tests(): """运行Web测试""" print("运行Web测试...") # 这里可以使用pytest.main()或者自定义测试运行逻辑 import subprocess result = subprocess.run([ "pytest", "tests/web_tests/", "-v", "--alluredir=resources/reports/allure-results" ], capture_output=True, text=True) return parse_test_results(result) def run_api_tests(): """运行API测试""" print("运行API测试...") import subprocess result = subprocess.run([ "pytest", "tests/api_tests/", "-v", "--alluredir=resources/reports/allure-results" ], capture_output=True, text=True) return parse_test_results(result) def run_performance_tests(): """运行性能测试""" print("运行性能测试...") from modules.performance.performance_tester import PerformanceTester tester = PerformanceTester() return tester.run_tests() def run_security_tests(): """运行安全测试""" print("运行安全测试...") from modules.security.security_tester import SecurityTester tester = SecurityTester() return tester.run_tests() def run_database_tests(): """运行数据库测试""" print("运行数据库测试...") import subprocess result = subprocess.run([ "pytest", "tests/database_tests/", "-v", "--alluredir=resources/reports/allure-results" ], capture_output=True, text=True) return parse_test_results(result) def parse_test_results(pytest_result): """解析pytest测试结果""" # 这里需要根据实际测试结果格式进行解析 # 简化实现,实际应用中应该使用pytest的插件或API获取详细结果 return [ { 'name': '示例测试', 'status': 'PASS' if pytest_result.returncode == 0 else 'FAIL', 'duration': 1.5, 'start_time': datetime.now().isoformat(), 'end_time': datetime.now().isoformat(), 'module': 'web' } ] def main(): """主函数""" parser = argparse.ArgumentParser(description='自动化测试框架') parser.add_argument('--tests', nargs='+', choices=['web', 'api', 'performance', 'security', 'database', 'all'], default=['all'], help='选择要运行的测试类型') parser.add_argument('--report', choices=['html', 'json', 'excel', 'all'], default='all', help='选择报告格式') parser.add_argument('--email', action='store_true', help='是否发送邮件报告') parser.add_argument('--browser', choices=['chrome', 'firefox', 'edge'], help='指定浏览器类型') parser.add_argument('--headless', action='store_true', help='是否使用无头模式') args = parser.parse_args() # 初始化配置 config = ConfigManager() # 设置浏览器参数 if args.browser: os.environ['BROWSER'] = args.browser if args.headless: os.environ['HEADLESS'] = 'true' all_results = [] start_time = time.time() try: # 执行选择的测试 if 'all' in args.tests or 'web' in args.tests: all_results.extend(run_web_tests()) if 'all' in args.tests or 'api' in args.tests: all_results.extend(run_api_tests()) if 'all' in args.tests or 'performance' in args.tests: all_results.extend(run_performance_tests()) if 'all' in args.tests or 'security' in args.tests: all_results.extend(run_security_tests()) if 'all' in args.tests or 'database' in args.tests: all_results.extend(run_database_tests()) # 生成报告 report_generator = ReportGenerator() report_paths = [] if args.report in ['html', 'all']: html_report = report_generator.generate_test_report(all_results, 'html') report_paths.append(html_report) if args.report in ['json', 'all']: json_report = report_generator.generate_test_report(all_results, 'json') report_paths.append(json_report) if args.report in ['excel', 'all']: excel_report = report_generator.generate_test_report(all_results, 'excel') report_paths.append(excel_report) # 发送邮件报告 if args.email: report_generator.send_report_by_email(report_paths) # 生成Allure报告 try: import subprocess subprocess.run([ "allure", "generate", "resources/reports/allure-results", "-o", "resources/reports/allure-report", "--clean" ], check=True) print("Allure报告已生成: resources/reports/allure-report/index.html") except Exception as e: print(f"生成Allure报告失败: {e}") # 输出测试摘要 execution_time = time.time() - start_time passed = sum(1 for r in all_results if r['status'] == 'PASS') failed = sum(1 for r in all_results if r['status'] == 'FAIL') success_rate = (passed / len(all_results)) * 100 if all_results else 0 print("\n" + "=" * 50) print("测试执行完成!") print(f"总测试数: {len(all_results)}") print(f"通过: {passed}") print(f"失败: {failed}") print(f"通过率: {success_rate:.2f}%") print(f"总执行时间: {execution_time:.2f}秒") print("=" * 50) # 返回适当的退出代码 sys.exit(failed) except Exception as e: print(f"测试执行过程中发生错误: {e}") sys.exit(1) finally: # 清理资源 DriverFactory().quit_all_drivers() DBClient().close() if __name__ == "__main__": main()