Generates test scaffolding for PyFlowGraph components.
| 48 | category: str # unit, integration, gui, headless |
| 49 | |
| 50 | class TestGenerator: |
| 51 | """Generates test scaffolding for PyFlowGraph components.""" |
| 52 | |
| 53 | def __init__(self, project_root: Path = None): |
| 54 | self.project_root = project_root or Path(__file__).parent |
| 55 | self.src_dir = self.project_root / "src" |
| 56 | self.test_dir = self.project_root / "tests" |
| 57 | |
| 58 | # Load existing test patterns |
| 59 | self.existing_patterns = self._analyze_existing_tests() |
| 60 | |
| 61 | # PyFlowGraph-specific templates |
| 62 | self.templates = self._load_templates() |
| 63 | |
| 64 | def _analyze_existing_tests(self) -> Dict[str, List[str]]: |
| 65 | """Analyze existing tests to learn patterns and conventions.""" |
| 66 | patterns = { |
| 67 | 'imports': set(), |
| 68 | 'fixtures': set(), |
| 69 | 'setup_patterns': [], |
| 70 | 'assertion_patterns': [], |
| 71 | 'teardown_patterns': [] |
| 72 | } |
| 73 | |
| 74 | for test_file in self.test_dir.rglob("test_*.py"): |
| 75 | try: |
| 76 | with open(test_file, 'r', encoding='utf-8') as f: |
| 77 | content = f.read() |
| 78 | |
| 79 | tree = ast.parse(content) |
| 80 | |
| 81 | # Extract import patterns |
| 82 | for node in ast.walk(tree): |
| 83 | if isinstance(node, ast.Import): |
| 84 | for alias in node.names: |
| 85 | patterns['imports'].add(alias.name) |
| 86 | elif isinstance(node, ast.ImportFrom): |
| 87 | if node.module: |
| 88 | patterns['imports'].add(node.module) |
| 89 | |
| 90 | # Extract fixture and setup patterns |
| 91 | for node in ast.walk(tree): |
| 92 | if isinstance(node, ast.FunctionDef): |
| 93 | if node.name in ['setUp', 'setUpClass', 'tearDown', 'tearDownClass']: |
| 94 | patterns['fixtures'].add(node.name) |
| 95 | elif node.name.startswith('test_'): |
| 96 | # Analyze test structure |
| 97 | source = ast.get_source_segment(content, node) |
| 98 | if source: |
| 99 | patterns['assertion_patterns'].extend( |
| 100 | self._extract_assertion_patterns(source) |
| 101 | ) |
| 102 | |
| 103 | except (SyntaxError, UnicodeDecodeError) as e: |
| 104 | print(f"Warning: Could not analyze {test_file}: {e}") |
| 105 | |
| 106 | # Convert sets to lists for JSON serialization |
| 107 | patterns['imports'] = list(patterns['imports']) |