""" run_tests.py Main test runner for automated chat testing and accuracy analysis. Orchestrates the full testing pipeline: execution -> validation -> reporting """ import argparse import sys import json import logging from pathlib import Path from typing import Optional # Add project to path test_dir = Path(__file__).parent project_src = test_dir.parent / "src" sys.path.insert(0, str(project_src)) sys.path.insert(0, str(test_dir)) from chat_automation import ChatAutomation from accuracy_validators import AccuracyAnalyzer from report_generator import ReportGenerator # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def main(): """Run complete testing pipeline.""" parser = argparse.ArgumentParser( description="Run automated chat testing and accuracy analysis for Data Dictionary Chatbot", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Run with mock service (no API costs) python run_tests.py --mock # Run with real service and generate reports python run_tests.py --real --report html # Run specific test cases only python run_tests.py --mock --test-cases tests/test_cases.json # Run tests and save results to custom location python run_tests.py --mock --output results/my_test_run.json """ ) parser.add_argument( "--mock", action="store_true", default=False, help="Use mock Azure OpenAI service (no API costs)" ) parser.add_argument( "--real", action="store_true", default=False, help="Use real Azure OpenAI service (requires credentials)" ) parser.add_argument( "--test-cases", default=None, help="Path to test_cases.json file" ) parser.add_argument( "--output", default=None, help="Output file for test results (JSON)" ) parser.add_argument( "--report", choices=["html", "markdown", "both"], default="html", help="Report format(s) to generate" ) parser.add_argument( "--skip-analysis", action="store_true", help="Skip accuracy analysis and reporting" ) parser.add_argument( "--verbose", "-v", action="store_true", help="Verbose output" ) args = parser.parse_args() if args.verbose: logging.getLogger().setLevel(logging.DEBUG) # Determine service type use_mock = args.mock or not args.real print("=" * 70) print("šŸ¤– Data Dictionary Chatbot - Testing Framework") print("=" * 70) print(f"Service: {'MOCK (No API costs)' if use_mock else 'REAL (Azure OpenAI)'}") print() # Step 1: Run chat automation print("šŸ“‹ STEP 1: Running Chat Automation") print("-" * 70) try: automation = ChatAutomation(use_mock=use_mock) results = automation.run_all_tests(args.test_cases) output_file = automation.save_results(args.output) print(f"āœ… Completed {len(results)} tests") print(f"šŸ“ Results saved to: {output_file}") print() except Exception as e: logger.error(f"Chat automation failed: {e}", exc_info=args.verbose) return 1 # Step 2: Load test cases for validation if not args.skip_analysis: print("šŸ“Š STEP 2: Running Accuracy Analysis") print("-" * 70) try: test_cases_file = args.test_cases or (Path(__file__).parent / "test_cases.json") with open(test_cases_file) as f: test_data = json.load(f) test_cases = test_data.get("chat_interface_tests", []) + test_data.get("area_insights_tests", []) # Create analyzer and run analysis analyzer = AccuracyAnalyzer() batch_analysis = analyzer.analyze_batch(results, test_cases) print(f"āœ… Analysis complete") print(f" Total: {batch_analysis['total_tests']} tests") print(f" Passed: {batch_analysis['passed_tests']} ({batch_analysis['pass_rate']:.1%})") print(f" Failed: {batch_analysis['failed_tests']}") print(f" Avg Score: {batch_analysis['average_score']:.2%}") print() # Step 3: Generate reports print("šŸ“ˆ STEP 3: Generating Reports") print("-" * 70) generator = ReportGenerator() if args.report in ["html", "both"]: html_report = generator.generate_html_report(batch_analysis) print(f"āœ… HTML Report: {html_report}") if args.report in ["markdown", "both"]: md_report = generator.generate_markdown_report(batch_analysis) print(f"āœ… Markdown Report: {md_report}") print() except Exception as e: logger.error(f"Analysis/reporting failed: {e}", exc_info=args.verbose) print("\nāš ļø Skipping analysis due to error") # Summary print("=" * 70) print("āœ… Testing pipeline completed successfully!") print("=" * 70) print() print("Next steps:") print("1. Review the generated report(s)") print("2. Check citation accuracy and hallucination detection results") print("3. Address any failing tests") print("4. For production deployment, ensure pass rate >= 90%") print() return 0 if __name__ == "__main__": sys.exit(main())