File size: 9,580 Bytes
1ab614e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd91248
1ab614e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd91248
1ab614e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd91248
1ab614e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env python3
"""
Batch Test Runner for DemoPrep

Runs a series of test cases through the demo pipeline and collects results.
Supports selective stage execution (research-only, full pipeline, etc.)

Usage:
    source ./demoprep/bin/activate
    python tests/batch_runner.py                           # Run all cases, full pipeline
    python tests/batch_runner.py --stages research,ddl     # Research + DDL only
    python tests/batch_runner.py --cases 1,3,5             # Specific cases only
    python tests/batch_runner.py --cases-file custom.yaml  # Custom cases file
"""

import os
import sys
import yaml
import json
import time
import argparse
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional

# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from dotenv import load_dotenv
load_dotenv(PROJECT_ROOT / '.env')
from llm_config import DEFAULT_LLM_MODEL


# Available pipeline stages (in order)
STAGES = ['research', 'ddl', 'population', 'deploy_snowflake', 'deploy_thoughtspot', 'liveboard']

DEFAULT_CASES_FILE = Path(__file__).parent / 'test_cases.yaml'


def load_test_cases(cases_file: str = None) -> List[Dict]:
    """Load test cases from YAML file."""
    path = Path(cases_file) if cases_file else DEFAULT_CASES_FILE
    if not path.exists():
        print(f"ERROR: Test cases file not found: {path}")
        sys.exit(1)
    
    with open(path) as f:
        data = yaml.safe_load(f)
    
    return data.get('test_cases', [])


def run_research(company: str, use_case: str, model: str = DEFAULT_LLM_MODEL) -> Dict:
    """Run the research stage for a test case."""
    from chat_interface import ChatDemoInterface
    
    controller = ChatDemoInterface()
    controller.settings['model'] = model
    
    result = {
        'stage': 'research',
        'success': False,
        'duration_ms': 0,
        'details': {},
    }
    
    start = time.time()
    try:
        # Run research (non-streaming version)
        research_result = controller.run_research(company, use_case)
        elapsed = int((time.time() - start) * 1000)
        
        result['duration_ms'] = elapsed
        
        if research_result and controller.demo_builder:
            result['success'] = True
            result['details'] = {
                'company_analysis_len': len(controller.demo_builder.company_analysis_results or ''),
                'industry_research_len': len(controller.demo_builder.industry_research_results or ''),
            }
        else:
            result['error'] = 'Research returned None or empty'
    except Exception as e:
        result['duration_ms'] = int((time.time() - start) * 1000)
        result['error'] = str(e)
    
    return result, controller


def run_ddl(controller) -> Dict:
    """Run DDL generation stage."""
    result = {
        'stage': 'ddl',
        'success': False,
        'duration_ms': 0,
        'details': {},
    }
    
    start = time.time()
    try:
        response, ddl_code = controller.run_ddl_creation()
        elapsed = int((time.time() - start) * 1000)
        
        result['duration_ms'] = elapsed
        
        if ddl_code and 'CREATE TABLE' in ddl_code.upper():
            result['success'] = True
            
            # Count tables
            import re
            tables = re.findall(r'CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)', ddl_code, re.IGNORECASE)
            result['details'] = {
                'tables': tables,
                'table_count': len(tables),
                'ddl_length': len(ddl_code),
            }
        else:
            result['error'] = 'No valid DDL generated'
    except Exception as e:
        result['duration_ms'] = int((time.time() - start) * 1000)
        result['error'] = str(e)
    
    return result


def run_test_case(case: Dict, stages: List[str]) -> Dict:
    """Run a single test case through specified stages."""
    company = case['company']
    use_case = case['use_case']
    model = case.get('model', DEFAULT_LLM_MODEL)
    context = case.get('context', '')
    
    print(f"\n{'='*60}")
    print(f"  {company} / {use_case}")
    print(f"  Model: {model}")
    if context:
        print(f"  Context: {context[:80]}...")
    print(f"{'='*60}")
    
    case_result = {
        'company': company,
        'use_case': use_case,
        'model': model,
        'started_at': datetime.now().isoformat(),
        'stages': {},
        'overall_success': True,
    }
    
    controller = None
    
    # Research
    if 'research' in stages:
        print(f"  [1/6] Research...", end=' ', flush=True)
        res, controller = run_research(company, use_case, model)
        case_result['stages']['research'] = res
        status = 'OK' if res['success'] else f"FAIL: {res.get('error', '')[:60]}"
        print(f"{status} ({res['duration_ms']}ms)")
        if not res['success']:
            case_result['overall_success'] = False
            return case_result
    
    # DDL
    if 'ddl' in stages and controller:
        print(f"  [2/6] DDL Generation...", end=' ', flush=True)
        res = run_ddl(controller)
        case_result['stages']['ddl'] = res
        tables = res.get('details', {}).get('tables', [])
        status = f"OK ({len(tables)} tables: {', '.join(tables)})" if res['success'] else f"FAIL: {res.get('error', '')[:60]}"
        print(f"{status} ({res['duration_ms']}ms)")
        if not res['success']:
            case_result['overall_success'] = False
    
    # TODO: Add population, deploy_snowflake, deploy_thoughtspot, liveboard stages
    # These require actual infrastructure connections
    
    case_result['finished_at'] = datetime.now().isoformat()
    
    return case_result


def print_summary(results: List[Dict]):
    """Print a summary table of all test case results."""
    print(f"\n\n{'='*80}")
    print(f"  BATCH TEST RESULTS SUMMARY")
    print(f"{'='*80}\n")
    
    passed = sum(1 for r in results if r['overall_success'])
    failed = len(results) - passed
    
    print(f"  Total: {len(results)}  |  Passed: {passed}  |  Failed: {failed}\n")
    
    for i, r in enumerate(results, 1):
        status = "PASS" if r['overall_success'] else "FAIL"
        company = r['company']
        use_case = r['use_case']
        
        # Collect stage summaries
        stage_notes = []
        for stage_name, stage_data in r.get('stages', {}).items():
            if stage_data['success']:
                details = stage_data.get('details', {})
                if stage_name == 'research':
                    stage_notes.append(f"research({details.get('company_analysis_len', 0)} chars)")
                elif stage_name == 'ddl':
                    tables = details.get('tables', [])
                    stage_notes.append(f"ddl({len(tables)} tables: {', '.join(tables[:3])})")
            else:
                stage_notes.append(f"{stage_name}(FAILED)")
        
        notes = ' | '.join(stage_notes) if stage_notes else 'No stages run'
        print(f"  [{status}] {i}. {company} / {use_case}")
        print(f"         {notes}")
        print()
    
    print(f"{'='*80}")


def main():
    parser = argparse.ArgumentParser(description='DemoPrep Batch Test Runner')
    parser.add_argument('--cases-file', '-f', default=None,
                       help='Path to test cases YAML file (default: tests/test_cases.yaml)')
    parser.add_argument('--cases', '-c', default=None,
                       help='Comma-separated case numbers to run (e.g., 1,3,5)')
    parser.add_argument('--stages', '-s', default='research,ddl',
                       help=f'Comma-separated stages to run: {",".join(STAGES)} (default: research,ddl)')
    parser.add_argument('--output', '-o', default=None,
                       help='Output JSON file for results')
    
    args = parser.parse_args()
    
    # Load test cases
    cases = load_test_cases(args.cases_file)
    
    # Filter cases if specified
    if args.cases:
        indices = [int(x.strip()) - 1 for x in args.cases.split(',')]
        cases = [cases[i] for i in indices if i < len(cases)]
    
    # Parse stages
    stages = [s.strip() for s in args.stages.split(',')]
    
    print(f"\n{'#'*60}")
    print(f"  DemoPrep Batch Test Runner")
    print(f"  Cases: {len(cases)}")
    print(f"  Stages: {', '.join(stages)}")
    print(f"  Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'#'*60}")
    
    # Run all cases
    results = []
    for i, case in enumerate(cases, 1):
        print(f"\n--- Case {i}/{len(cases)} ---")
        result = run_test_case(case, stages)
        results.append(result)
    
    # Print summary
    print_summary(results)
    
    # Save results
    output_file = args.output or f"tests/batch_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    output_path = PROJECT_ROOT / output_file
    output_path.parent.mkdir(parents=True, exist_ok=True)
    
    with open(output_path, 'w') as f:
        json.dump({
            'run_at': datetime.now().isoformat(),
            'stages': stages,
            'total_cases': len(results),
            'passed': sum(1 for r in results if r['overall_success']),
            'failed': sum(1 for r in results if not r['overall_success']),
            'results': results,
        }, f, indent=2)
    
    print(f"\nResults saved to: {output_path}")
    
    # Exit with error code if any failed
    if any(not r['overall_success'] for r in results):
        sys.exit(1)


if __name__ == '__main__':
    main()