Files
FrameTour-RenderWorker/run_tests.py
2025-09-24 09:21:03 +08:00

267 lines
7.1 KiB
Python

#!/usr/bin/env python
"""
测试运行器脚本
支持不同类型的测试运行和报告生成
"""
import os
import sys
import subprocess
import argparse
import tempfile
from pathlib import Path
def run_command(cmd, cwd=None):
"""运行命令并返回结果"""
print(f"Running: {' '.join(cmd)}")
try:
result = subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
check=False
)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
return result.returncode == 0
except Exception as e:
print(f"Error running command: {e}", file=sys.stderr)
return False
def check_dependencies():
"""检查依赖是否安装"""
print("Checking dependencies...")
# 检查pytest
if not run_command([sys.executable, "-c", "import pytest"]):
print("pytest not found. Installing test dependencies...")
if not run_command([sys.executable, "-m", "pip", "install", "-r", "requirements-test.txt"]):
print("Failed to install test dependencies", file=sys.stderr)
return False
# 检查FFmpeg
ffmpeg_available = run_command(["ffmpeg", "-version"])
if not ffmpeg_available:
print("Warning: FFmpeg not found. Integration tests may be skipped.")
return True
def run_unit_tests(args):
"""运行单元测试"""
print("\n=== Running Unit Tests ===")
cmd = [
sys.executable, "-m", "pytest",
"tests/test_effects/",
"tests/test_ffmpeg_builder/",
"-v",
"-m", "not integration"
]
if args.coverage:
cmd.extend([
"--cov=entity",
"--cov=services",
"--cov-report=xml:coverage.xml",
"--cov-report=html:htmlcov",
"--cov-report=term-missing",
"--cov-branch"
])
if args.xml_report:
cmd.extend(["--junitxml=unit-tests.xml"])
if args.html_report:
cmd.extend(["--html=unit-tests.html", "--self-contained-html"])
return run_command(cmd)
def run_integration_tests(args):
"""运行集成测试"""
print("\n=== Running Integration Tests ===")
# 检查FFmpeg
if not run_command(["ffmpeg", "-version"]):
print("FFmpeg not available, skipping integration tests")
return True
cmd = [
sys.executable, "-m", "pytest",
"tests/test_integration/",
"-v",
"-m", "integration",
"--timeout=300"
]
if args.coverage:
cmd.extend([
"--cov=entity",
"--cov=services",
"--cov-report=xml:integration-coverage.xml",
"--cov-report=html:integration-htmlcov",
"--cov-branch"
])
if args.xml_report:
cmd.extend(["--junitxml=integration-tests.xml"])
if args.html_report:
cmd.extend(["--html=integration-tests.html", "--self-contained-html"])
return run_command(cmd)
def run_all_tests(args):
"""运行所有测试"""
print("\n=== Running All Tests ===")
cmd = [
sys.executable, "-m", "pytest",
"tests/",
"-v"
]
if args.coverage:
cmd.extend([
"--cov=entity",
"--cov=services",
"--cov-report=xml:coverage.xml",
"--cov-report=html:htmlcov",
"--cov-report=term-missing",
"--cov-branch"
])
if args.fail_under:
cmd.extend([f"--cov-fail-under={args.fail_under}"])
if args.xml_report:
cmd.extend(["--junitxml=all-tests.xml"])
if args.html_report:
cmd.extend(["--html=all-tests.html", "--self-contained-html"])
return run_command(cmd)
def run_effect_tests(effect_name=None):
"""运行特定特效测试"""
if effect_name:
print(f"\n=== Running {effect_name} Effect Tests ===")
cmd = [
sys.executable, "-m", "pytest",
f"tests/test_effects/test_{effect_name}_effect.py",
"-v"
]
else:
print("\n=== Running All Effect Tests ===")
cmd = [
sys.executable, "-m", "pytest",
"tests/test_effects/",
"-v"
]
return run_command(cmd)
def run_stress_tests():
"""运行压力测试"""
print("\n=== Running Stress Tests ===")
env = os.environ.copy()
env['RUN_STRESS_TESTS'] = '1'
cmd = [
sys.executable, "-m", "pytest",
"tests/test_integration/",
"-v",
"-m", "stress",
"--timeout=600"
]
return subprocess.run(cmd, env=env).returncode == 0
def create_test_video():
"""创建测试视频文件"""
print("\n=== Creating Test Video Files ===")
if not run_command(["ffmpeg", "-version"]):
print("FFmpeg not available, cannot create test videos")
return False
test_data_dir = Path("tests/test_data/videos")
test_data_dir.mkdir(parents=True, exist_ok=True)
# 创建短视频文件
video_path = test_data_dir / "sample.mp4"
cmd = [
"ffmpeg", "-y",
"-f", "lavfi",
"-i", "testsrc=duration=5:size=640x480:rate=25",
"-c:v", "libx264",
"-preset", "ultrafast",
"-crf", "23",
str(video_path)
]
if run_command(cmd):
print(f"Created test video: {video_path}")
return True
else:
print("Failed to create test video")
return False
def main():
parser = argparse.ArgumentParser(description="RenderWorker Test Runner")
parser.add_argument("test_type", choices=[
"unit", "integration", "all", "effects", "stress", "setup"
], help="Type of tests to run")
parser.add_argument("--effect", help="Specific effect to test (for effects command)")
parser.add_argument("--coverage", action="store_true", help="Generate coverage report")
parser.add_argument("--xml-report", action="store_true", help="Generate XML test report")
parser.add_argument("--html-report", action="store_true", help="Generate HTML test report")
parser.add_argument("--fail-under", type=int, default=70, help="Minimum coverage percentage")
parser.add_argument("--no-deps-check", action="store_true", help="Skip dependency check")
args = parser.parse_args()
# 检查依赖
if not args.no_deps_check and not check_dependencies():
sys.exit(1)
# 运行相应的测试
success = True
if args.test_type == "unit":
success = run_unit_tests(args)
elif args.test_type == "integration":
success = run_integration_tests(args)
elif args.test_type == "all":
success = run_all_tests(args)
elif args.test_type == "effects":
success = run_effect_tests(args.effect)
elif args.test_type == "stress":
success = run_stress_tests()
elif args.test_type == "setup":
success = create_test_video()
if success:
print("\n✅ Tests completed successfully!")
if args.coverage:
print("📊 Coverage report generated in htmlcov/")
sys.exit(0)
else:
print("\n❌ Tests failed!")
sys.exit(1)
if __name__ == "__main__":
main()