#!/usr/bin/env python # -*- coding: utf-8 -*- """ Coverage test runner for MCP Gateway. This script runs all tests and generates coverage reports in multiple formats. """ import os import subprocess import sys # Fix Windows console encoding if sys.platform == 'win32': import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') def build_coverage_commands(): """Build coverage commands using the current Python interpreter.""" return [ ( [sys.executable, '-m', 'coverage', 'run', '-m', 'unittest', 'discover', '-s', 'tests', '-p', 'test_*.py'], 'Running tests with coverage', ), ( [sys.executable, '-m', 'coverage', 'report'], 'Generating console coverage report', ), ( [sys.executable, '-m', 'coverage', 'html'], 'Generating HTML coverage report', ), ( [sys.executable, '-m', 'coverage', 'xml'], 'Generating XML coverage report (for CI/CD)', ), ] def run_command(cmd, description): """Run a command and print status.""" print(f"\n{'='*60}") print(f"[*] {description}") print(f"{'='*60}\n") result = subprocess.run(cmd, shell=False) if result.returncode != 0: print(f"\n[X] {description} failed!") return False print(f"\n[OK] {description} completed successfully!") return True def main(): """Main test runner.""" print("\n=== MCP Gateway Coverage Test Runner ===") print("=" * 60) # Change to script directory script_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(script_dir) # Step 1: Clean old coverage data if os.path.exists('.coverage'): os.remove('.coverage') print("[*] Cleaned old coverage data") for cmd, description in build_coverage_commands(): if not run_command(cmd, description): return 1 # Summary print("\n" + "=" * 60) print("=== Coverage Reports Generated ===") print("=" * 60) print(" [*] Console: (shown above)") print(f" [*] HTML: {os.path.join(script_dir, 'htmlcov', 'index.html')}") print(f" [*] XML: {os.path.join(script_dir, 'coverage.xml')}") print("=" * 60) # Open HTML report (optional) if '--open' in sys.argv or '-o' in sys.argv: html_path = os.path.join(script_dir, 'htmlcov', 'index.html') print("\n[*] Opening HTML report in browser...") if sys.platform == 'win32': os.startfile(html_path) elif sys.platform == 'darwin': subprocess.run(['open', html_path]) else: subprocess.run(['xdg-open', html_path]) print("\n[OK] All coverage reports generated successfully!") print("[TIP] Run 'python run_coverage.py --open' to open HTML report automatically\n") return 0 if __name__ == '__main__': sys.exit(main())