-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerate_test_cases.py
More file actions
executable file
·760 lines (641 loc) · 31.6 KB
/
Copy pathgenerate_test_cases.py
File metadata and controls
executable file
·760 lines (641 loc) · 31.6 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
#!/usr/bin/env python3
"""
Test Case Generation Pipeline for Game Source Codes
This script analyzes Python game repositories and generates comprehensive test cases
using OpenAI API with customizable configuration.
"""
import sys
import os
import json
import time
import random
import argparse
import ast
import uuid
import tempfile
import shutil
import subprocess
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, asdict
from pathlib import Path
import traceback
from tqdm import tqdm
import openai
from datetime import datetime
import hashlib
import conda_env_utils as _conda
from game_config_utils import load_game_configs_from_path
@dataclass
class TestCase:
"""Container for a single test case"""
test_id: str
test_name: str
test_description: str
test_type: str # 'unit', 'integration', 'functional', 'edge_case'
test_code: str
expected_behavior: str
prerequisites: List[str]
input_parameters: Dict[str, Any]
expected_output: Any
difficulty_level: str # 'basic', 'intermediate', 'advanced'
estimated_runtime: float
tags: List[str]
@dataclass
class GameTestSuite:
"""Container for test cases generated for a game"""
game_path: str
repository: str
game_name: str
source_file_hash: str
generation_timestamp: str
source_code_lines: int
source_code_size: int
api_model_used: str
test_cases: List[TestCase]
game_description: str
main_functions: List[str]
dependencies: List[str]
game_type: str
complexity_score: int
class TestCaseGenerator:
"""AI-powered test case generator for game source codes"""
def __init__(self,
base_directory: str = "repos_GAME_python_demo",
config_file: str = "game_config.json",
api_config_file: str = "openai_config.json",
model: str = None):
self.base_directory = Path(base_directory)
self.config_file = config_file
self.api_config_file = api_config_file
self.game_configs = {}
self.python_extensions = {'.py'}
self.excluded_files = {'__pycache__', '.git', '.gitignore', 'requirements.txt', 'setup.py'}
self.excluded_dirs = {'__pycache__', '.git', '.github', 'node_modules', 'venv', 'env'}
self.model = model
self.active_conda_envs = set() # Track active conda environments for cleanup
self.load_game_configs()
self.load_api_config()
self.setup_openai_client()
def load_game_configs(self):
"""Load game-specific configurations from JSON file"""
self.game_configs = load_game_configs_from_path(
self.config_file, style="minimal"
)
def load_api_config(self):
"""Load OpenAI API configuration"""
default_config = {
"api_key": "your-openai-api-key-here",
"base_url": "https://api.openai.com/v1",
"model": "gpt-4o-mini",
"max_tokens": 4000,
"temperature": 0.7
}
try:
if os.path.exists(self.api_config_file):
with open(self.api_config_file, 'r', encoding='utf-8') as f:
self.api_config = json.load(f)
if self.model:
self.api_config["model"] = self.model
print(f"Loaded API configuration from {self.api_config_file}")
else:
self.api_config = default_config
if self.model:
self.api_config["model"] = self.model
with open(self.api_config_file, 'w', encoding='utf-8') as f:
json.dump(default_config, f, indent=2)
print(f"Created default API configuration: {self.api_config_file}")
print("Please update the API key and base_url in the configuration file.")
except Exception as e:
print(f"Error loading API configuration: {e}")
self.api_config = default_config
def setup_openai_client(self):
"""Setup OpenAI client with custom configuration"""
try:
self.client = openai.OpenAI(
api_key=self.api_config["api_key"],
base_url=self.api_config["base_url"]
)
print(f"OpenAI client configured with base_url: {self.api_config['base_url']}")
except Exception as e:
print(f"Error setting up OpenAI client: {e}")
self.client = None
def find_repo_root(self, file_path: Path) -> Path:
"""
Find the repository root directory by looking for common indicators
Args:
file_path: Path to a file within the repository
Returns:
Path to the repository root directory
"""
current_path = file_path.parent
# Look for common repository indicators
repo_indicators = ['.git', 'README.md', 'requirements.txt', 'setup.py', 'pyproject.toml']
# Walk up the directory tree
while current_path != current_path.parent: # Stop at filesystem root
# Check if this directory contains repository indicators
for indicator in repo_indicators:
if (current_path / indicator).exists():
return current_path
# Check if we've reached the base directory (common repository container)
if current_path == self.base_directory:
# If we're at the base directory, look for the immediate subdirectory
# that contains the file (this is likely the repository root)
try:
relative_path = file_path.relative_to(self.base_directory)
repo_dir = self.base_directory / relative_path.parts[0]
return repo_dir
except ValueError:
break
current_path = current_path.parent
# If no repository root found, return the immediate parent directory
return file_path.parent
def create_conda_environment(self, env_name: str, requirements: List[str], python_version: str = "3.9") -> Tuple[bool, str]:
"""
Create a conda environment with specified requirements and Python version
Args:
env_name: Name of the conda environment
requirements: List of pip packages to install
python_version: Python version to use (e.g., "3.8", "3.9", "3.10")
Returns:
Tuple of (success, error_message)
"""
cfg = _conda.CondaEnvCreateConfig(
python_version=python_version,
install_pytest_first=True,
)
return _conda.create_conda_environment(
env_name, requirements, self.active_conda_envs, cfg
)
def cleanup_conda_environment(self, env_name: str) -> bool:
"""
Remove a conda environment
Args:
env_name: Name of the environment to remove
Returns:
Success status
"""
return _conda.cleanup_conda_environment(env_name, self.active_conda_envs)
def cleanup_all_conda_environments(self):
"""Clean up all conda environments created during test generation"""
_conda.cleanup_all_conda_environments(self.active_conda_envs)
def validate_test_case_with_pytest(self, test_code: str, game_path: str, repo_root: Path, config: Dict[str, Any]) -> Tuple[bool, str]:
"""
Validate a generated test case by running it with pytest in the repository root
Args:
test_code: The generated test code
game_path: Path to the game file being tested
repo_root: Repository root directory
config: Game configuration
Returns:
Tuple of (validation_success, error_message)
"""
pip_requirements = config.get("pip_requirements", [])
# running_arguments = config.get("running_arguments", [])
timeout = config.get("timeout", 10)
python_version = config.get("python_version", "3.9")
with tempfile.TemporaryDirectory() as temp_dir:
try:
# Copy entire repository to temp directory
repo_temp_dir = Path(temp_dir) / "repo"
shutil.copytree(repo_root, repo_temp_dir, ignore=shutil.ignore_patterns(
'.git', '__pycache__', '*.pyc', '.DS_Store', '.pytest_cache',
'*.egg-info', 'build', 'dist', '.tox', '.coverage'
))
# Calculate the relative path from repo root to the target file
game_file_path = Path(game_path)
relative_path_from_repo = game_file_path.relative_to(repo_root)
temp_game_file = repo_temp_dir / relative_path_from_repo
# Create test file
test_file = repo_temp_dir / f"test_{game_file_path.stem}.py"
with open(test_file, 'w', encoding='utf-8') as f:
f.write(test_code)
# Decide whether to use conda environment
used_conda_env = False
env_name = ""
python_cmd = [sys.executable]
if pip_requirements or config:
# Create conda environment for this test
env_name = f"test_eval_{uuid.uuid4().hex[:8]}"
used_conda_env = True
env_success, env_error = self.create_conda_environment(env_name, pip_requirements, python_version)
if not env_success:
return False, f"Conda environment creation failed: {env_error}"
python_cmd = ["conda", "run", "-n", env_name, "python"]
# Try to run pytest on the generated test
pytest_cmd = python_cmd + ["-m", "pytest", str(test_file), "-v"]
# if running_arguments:
# pytest_cmd.extend(running_arguments)
# print("pytest_cmd: ", pytest_cmd)
result = subprocess.run(
pytest_cmd,
capture_output=True,
text=True,
timeout=timeout,
cwd=repo_temp_dir
)
# Clean up conda environment
if used_conda_env:
self.cleanup_conda_environment(env_name)
if result.returncode == 0:
return True, ""
else:
error_msg = f"Pytest failed with return code {result.returncode}"
if result.stderr:
error_msg += f": {result.stderr[:500]}"
return False, error_msg
except subprocess.TimeoutExpired:
if used_conda_env:
self.cleanup_conda_environment(env_name)
return False, "Test validation timeout"
except Exception as e:
if used_conda_env:
self.cleanup_conda_environment(env_name)
return False, str(e)
def analyze_source_code(self, file_path: Path, code: str) -> Dict[str, Any]:
"""Analyze source code to extract useful information"""
analysis = {
'functions': [],
'classes': [],
'imports': [],
'main_execution': False,
'game_loops': [],
'event_handlers': [],
'complexity_indicators': [],
'game_type_hints': []
}
try:
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
analysis['functions'].append({
'name': node.name,
'args': [arg.arg for arg in node.args.args],
'line_number': node.lineno,
'docstring': ast.get_docstring(node)
})
if 'game' in node.name.lower() or 'play' in node.name.lower():
analysis['game_type_hints'].append(f"game_function_{node.name}")
if 'loop' in node.name.lower() or 'update' in node.name.lower():
analysis['game_loops'].append(node.name)
if 'event' in node.name.lower() or 'input' in node.name.lower():
analysis['event_handlers'].append(node.name)
elif isinstance(node, ast.ClassDef):
analysis['classes'].append({
'name': node.name,
'line_number': node.lineno,
'methods': [n.name for n in node.body if isinstance(n, ast.FunctionDef)],
'docstring': ast.get_docstring(node)
})
elif isinstance(node, ast.Import):
for alias in node.names:
analysis['imports'].append(alias.name)
if 'pygame' in alias.name:
analysis['game_type_hints'].append('pygame_game')
elif 'tkinter' in alias.name:
analysis['game_type_hints'].append('gui_game')
elif isinstance(node, ast.ImportFrom):
if node.module:
analysis['imports'].append(node.module)
if 'pygame' in node.module:
analysis['game_type_hints'].append('pygame_game')
if '__name__' in code and '__main__' in code:
analysis['main_execution'] = True
analysis['complexity_indicators'] = [
f"functions_{len(analysis['functions'])}",
f"classes_{len(analysis['classes'])}",
f"imports_{len(analysis['imports'])}",
f"lines_{len(code.splitlines())}"
]
except Exception as e:
print(f"Error analyzing {file_path}: {e}")
return analysis
def create_test_generation_prompt(self, file_path: str, code: str, analysis: Dict[str, Any]) -> str:
"""Create prompt for AI test case generation"""
prompt = f"""You are an expert software testing engineer specializing in Python GUI Application development.
Generate comprehensive test cases for the following Python source code.
**File Path:** {file_path}
**Source Code:**
```python
{code}
```
**Code Analysis:**
- Functions: {len(analysis['functions'])} ({', '.join([f['name'] for f in analysis['functions'][:5]])})
- Classes: {len(analysis['classes'])} ({', '.join([c['name'] for c in analysis['classes'][:3]])})
- Imports: {', '.join(analysis['imports'][:10])}
- Type: {', '.join(analysis['game_type_hints'])}
**Requirements:**
Generate 5-8 test cases covering:
1. Unit Tests - Test individual functions
2. Integration Tests - Test component interactions
3. Functional Tests - Test complete features
4. Edge Cases - Test boundary conditions
**Important Testing Guidelines:**
1. DO NOT import from 'main' directly - use importlib or mock instead
2. Create self-contained tests that don't rely on global variables
3. Test logic and algorithms rather than UI rendering
4. Use pytest fixtures and mocking extensively
5. Focus on testable functions and classes, avoid testing main execution blocks
6. Write tests that can run independently without the full game setup
7. Include pytest parameters like -v, --tb=short, --no-header for better test execution
8. Handle import errors gracefully with proper mocking
9. Use relative imports when possible
**Output Format:**
Return a JSON array with this exact structure:
```json
[
{{
"test_name": "test_function_name",
"test_description": "Description of what this test verifies",
"test_type": "unit|integration|functional|edge_case",
"test_code": "import pytest\\n\\ndef test_something():\\n assert True",
"expected_behavior": "What should happen when test runs",
"prerequisites": ["pygame", "mock"],
"input_parameters": {{}},
"expected_output": "Expected result",
"difficulty_level": "basic|intermediate|advanced",
"estimated_runtime": 0.5,
"tags": ["tag1", "tag2"]
}}
]
```
**Important Guidelines for Test Code:**
1. DO NOT import from 'main' directly - use importlib or mock instead
2. Create self-contained tests that don't rely on global variables
2. Test logic and algorithms rather than UI rendering
4. Use pytest fixtures and mocking extensively
5. Focus on testable functions and classes, avoid testing main execution blocks
6. Write tests that can run independently without the full game setup
Focus on testable aspects of the game. Write complete, runnable test code that doesn't have import issues.
"""
return prompt
def generate_test_cases_with_ai(self, file_path: str, code: str, analysis: Dict[str, Any], repo_root: Path, config: Dict[str, Any]) -> List[TestCase]:
"""Generate test cases using OpenAI API and validate them with pytest"""
if not self.client:
print("OpenAI client not configured")
return []
max_retries = 3
retry_count = 0
while retry_count <= max_retries:
try:
prompt = self.create_test_generation_prompt(file_path, code, analysis)
print(f"Using model: {self.api_config['model']}")
response = self.client.chat.completions.create(
model=self.api_config["model"],
messages=[
{"role": "system", "content": "You are an expert testing engineer. Return only valid JSON."},
{"role": "user", "content": prompt}
],
max_tokens=self.api_config["max_tokens"],
temperature=self.api_config["temperature"]
)
response_content = response.choices[0].message.content
if response_content is None:
raise Exception("API returned empty response content")
response_text = response_content.strip()
# Extract JSON from response
if "```json" in response_text:
json_start = response_text.find("```json") + 7
json_end = response_text.find("```", json_start)
response_text = response_text[json_start:json_end].strip()
elif "```" in response_text:
json_start = response_text.find("```") + 3
json_end = response_text.find("```", json_start)
response_text = response_text[json_start:json_end].strip()
test_cases_data = json.loads(response_text)
# Validate each test case with pytest before accepting it
validated_test_cases = []
for i, tc_data in enumerate(test_cases_data):
test_code = tc_data.get("test_code", "")
if not test_code.strip():
continue
# Validate the test case by running it with pytest
validation_success, error_msg = self.validate_test_case_with_pytest(test_code, file_path, repo_root, config)
if validation_success:
test_case = TestCase(
test_id=str(uuid.uuid4()),
test_name=tc_data.get("test_name", f"test_{i}"),
test_description=tc_data.get("test_description", ""),
test_type=tc_data.get("test_type", "unit"),
test_code=test_code,
expected_behavior=tc_data.get("expected_behavior", ""),
prerequisites=tc_data.get("prerequisites", []),
input_parameters=tc_data.get("input_parameters", {}),
expected_output=tc_data.get("expected_output", ""),
difficulty_level=tc_data.get("difficulty_level", "basic"),
estimated_runtime=tc_data.get("estimated_runtime", 1.0),
tags=tc_data.get("tags", [])
)
validated_test_cases.append(test_case)
print(f"✅ Test case '{test_case.test_name}' validated successfully")
else:
print(f"❌ Test case {i+1} validation failed: {error_msg}")
print(f"Generated and validated {len(validated_test_cases)}/{len(test_cases_data)} test cases for {file_path}")
return validated_test_cases
except json.JSONDecodeError as e:
retry_count += 1
if retry_count <= max_retries:
sleep_time = random.uniform(2, 8) # Random sleep between 2-8 seconds
print(f"JSON parsing error for {file_path} (attempt {retry_count}/{max_retries + 1}): {e}. Retrying in {sleep_time:.2f} seconds...")
time.sleep(sleep_time)
else:
print(f"JSON parsing error for {file_path} after {max_retries + 1} attempts: {e}")
return []
except Exception as e:
retry_count += 1
if retry_count <= max_retries:
sleep_time = random.uniform(2, 8) # Random sleep between 2-8 seconds
print(f"Error generating test cases for {file_path} (attempt {retry_count}/{max_retries + 1}): {e}. Retrying in {sleep_time:.2f} seconds.... Orignal prompt: {prompt}")
time.sleep(sleep_time)
else:
print(f"Error generating test cases for {file_path} after {max_retries + 1} attempts: {e}")
return []
# This should never be reached, but added for type safety
return []
def calculate_file_hash(self, content: str) -> str:
"""Calculate SHA-256 hash of file content"""
return hashlib.sha256(content.encode('utf-8')).hexdigest()
def determine_game_type(self, analysis: Dict[str, Any], file_path: str) -> str:
"""Determine game type based on analysis"""
hints = analysis.get('game_type_hints', [])
file_name = Path(file_path).name.lower()
if 'pygame' in ' '.join(hints):
if 'snake' in file_name:
return 'snake_game'
elif 'bird' in file_name or 'flappy' in file_name:
return 'arcade_game'
elif 'sudoku' in file_name or 'puzzle' in file_name:
return 'puzzle_game'
elif 'dragon' in file_name:
return 'adventure_game'
else:
return 'pygame_game'
elif 'tkinter' in ' '.join(hints):
return 'gui_game'
else:
return 'generic_game'
def calculate_complexity_score(self, analysis: Dict[str, Any], code: str) -> int:
"""Calculate complexity score 1-10"""
score = 1
score += min(len(analysis.get('functions', [])) // 3, 3)
score += min(len(analysis.get('classes', [])), 2)
score += min(len(analysis.get('imports', [])) // 2, 2)
score += min(len(code.splitlines()) // 50, 2)
return min(score, 10)
def find_python_files(self) -> List[Path]:
"""Find all Python files in base directory"""
python_files = []
try:
for root, dirs, files in os.walk(self.base_directory):
dirs[:] = [d for d in dirs if d not in self.excluded_dirs]
for file in files:
if file.endswith('.py') and file not in self.excluded_files:
file_path = Path(root) / file
if file_path.stat().st_size > 100:
python_files.append(file_path)
except Exception as e:
print(f"Error finding Python files: {e}")
return python_files
def generate_test_suites(self,
max_files: Optional[int] = None,
save_results: bool = True,
results_file: str = "game_test_cases.json") -> List[GameTestSuite]:
"""Generate test suites for Python game files"""
python_files = self.find_python_files()
if max_files:
python_files = python_files[:max_files]
print(f"Generating test cases for {len(python_files)} Python files...")
test_suites = []
for file_path in tqdm(python_files, desc="Generating test cases"):
try:
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
if len(code.strip()) < 50:
continue
analysis = self.analyze_source_code(file_path, code)
repo_root = self.find_repo_root(file_path)
relative_path = str(file_path.relative_to(self.base_directory))
config = self.game_configs.get(relative_path, {})
test_cases = self.generate_test_cases_with_ai(str(file_path), code, analysis, repo_root, config)
if test_cases:
relative_path = str(file_path.relative_to(self.base_directory))
repository = relative_path.split('/')[0] if '/' in relative_path else "unknown"
game_name = file_path.stem
test_suite = GameTestSuite(
game_path=relative_path,
repository=repository,
game_name=game_name,
source_file_hash=self.calculate_file_hash(code),
generation_timestamp=datetime.now().isoformat(),
source_code_lines=len(code.splitlines()),
source_code_size=len(code),
api_model_used=self.api_config["model"],
test_cases=test_cases,
game_description=f"Test cases for {game_name} game",
main_functions=[f['name'] for f in analysis.get('functions', [])],
dependencies=analysis.get('imports', []),
game_type=self.determine_game_type(analysis, str(file_path)),
complexity_score=self.calculate_complexity_score(analysis, code)
)
test_suites.append(test_suite)
print(f"✅ Generated {len(test_cases)} test cases for {relative_path}")
time.sleep(0.5) # Rate limiting
except Exception as e:
print(f"Error processing {file_path}: {e}")
continue
if save_results and test_suites:
self.save_test_suites(test_suites, results_file)
self.print_generation_statistics(test_suites)
return test_suites
def save_test_suites(self, test_suites: List[GameTestSuite], filename: str):
"""Save test suites to JSON file"""
try:
data = {
"generation_metadata": {
"total_test_suites": len(test_suites),
"generation_timestamp": datetime.now().isoformat(),
"api_model_used": self.api_config["model"],
"base_directory": str(self.base_directory)
},
"test_suites": [asdict(suite) for suite in test_suites]
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"💾 Saved {len(test_suites)} test suites to {filename}")
except Exception as e:
print(f"Error saving test suites: {e}")
def print_generation_statistics(self, test_suites: List[GameTestSuite]):
"""Print statistics about test generation"""
if not test_suites:
print("No test suites generated.")
return
total_test_cases = sum(len(suite.test_cases) for suite in test_suites)
test_types = {}
difficulty_levels = {}
game_types = {}
for suite in test_suites:
game_types[suite.game_type] = game_types.get(suite.game_type, 0) + 1
for test_case in suite.test_cases:
test_types[test_case.test_type] = test_types.get(test_case.test_type, 0) + 1
difficulty_levels[test_case.difficulty_level] = difficulty_levels.get(test_case.difficulty_level, 0) + 1
print("\n" + "="*60)
print("🎮 TEST CASE GENERATION SUMMARY")
print("="*60)
print(f"Total game files processed: {len(test_suites)}")
print(f"Total test cases generated: {total_test_cases}")
print(f"Average test cases per game: {total_test_cases/len(test_suites):.1f}")
print(f"\n📊 TEST TYPE DISTRIBUTION:")
for test_type, count in sorted(test_types.items()):
percentage = (count / total_test_cases) * 100
print(f" {test_type}: {count} ({percentage:.1f}%)")
print(f"\n📈 DIFFICULTY LEVEL DISTRIBUTION:")
for level, count in sorted(difficulty_levels.items()):
percentage = (count / total_test_cases) * 100
print(f" {level}: {count} ({percentage:.1f}%)")
print(f"\n🎯 GAME TYPE DISTRIBUTION:")
for game_type, count in sorted(game_types.items()):
percentage = (count / len(test_suites)) * 100
print(f" {game_type}: {count} ({percentage:.1f}%)")
complexity_scores = [suite.complexity_score for suite in test_suites]
avg_complexity = sum(complexity_scores) / len(complexity_scores)
print(f"\n🧮 COMPLEXITY ANALYSIS:")
print(f" Average complexity score: {avg_complexity:.1f}/10")
print(f" Most complex game: {max(complexity_scores)}/10")
print(f" Simplest game: {min(complexity_scores)}/10")
print("="*60)
def main():
"""Main function"""
parser = argparse.ArgumentParser(description="Generate test cases for game source codes using AI")
parser.add_argument("--base-dir", default="repos_GAME_python_demo",
help="Base directory containing game repositories")
parser.add_argument("--config-file", default="game_config.json",
help="JSON configuration file for games")
parser.add_argument("--api-config", default="openai_config.json",
help="OpenAI API configuration file")
parser.add_argument("--max-files", type=int,
help="Maximum number of files to process")
parser.add_argument("--results-file", default="game_test_cases.json",
help="Output file for test cases")
parser.add_argument("--no-save", action="store_true",
help="Don't save results to file")
parser.add_argument("--model", help="OpenAI model to use")
args = parser.parse_args()
generator = TestCaseGenerator(
base_directory=args.base_dir,
config_file=args.config_file,
api_config_file=args.api_config,
model=args.model
)
try:
test_suites = generator.generate_test_suites(
max_files=args.max_files,
save_results=not args.no_save,
results_file=args.results_file
)
print(f"\n✅ Test case generation complete! Generated test cases for {len(test_suites)} games.")
finally:
# Ensure all conda environments are cleaned up
print("Cleaning up conda environments...")
generator.cleanup_all_conda_environments()
print("Cleanup completed.")
if __name__ == "__main__":
main()