This repository was archived by the owner on Mar 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathtest_generate_analyzer.py
More file actions
508 lines (467 loc) · 14.6 KB
/
test_generate_analyzer.py
File metadata and controls
508 lines (467 loc) · 14.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
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import ast
import pytest
import textwrap as tw
from scripts.microgenerator.generate import parse_code, CodeAnalyzer
# --- Tests CodeAnalyzer handling of Imports ---
class TestCodeAnalyzerImports:
@pytest.mark.parametrize(
"code_snippet, expected_imports",
[
pytest.param(
"import os\nimport sys",
["import os", "import sys"],
id="simple_imports",
),
pytest.param(
"import numpy as np",
["import numpy as np"],
id="aliased_import",
),
pytest.param(
"from collections import defaultdict, OrderedDict",
["from collections import defaultdict, OrderedDict"],
id="from_import_multiple",
),
pytest.param(
"from typing import List as L",
["from typing import List as L"],
id="from_import_aliased",
),
pytest.param(
"from math import *",
["from math import *"],
id="from_import_wildcard",
),
pytest.param(
"import os.path",
["import os.path"],
id="dotted_import",
),
pytest.param(
"from google.cloud import bigquery",
["from google.cloud import bigquery"],
id="from_dotted_module",
),
pytest.param(
"",
[],
id="no_imports",
),
pytest.param(
"class MyClass:\n import json # Should not be picked up",
[],
id="import_inside_class",
),
pytest.param(
"def my_func():\n from time import sleep # Should not be picked up",
[],
id="import_inside_function",
),
],
)
def test_import_extraction(self, code_snippet, expected_imports):
analyzer = CodeAnalyzer()
tree = ast.parse(code_snippet)
analyzer.visit(tree)
# Normalize for comparison
extracted = sorted(list(analyzer.imports))
expected = sorted(expected_imports)
assert extracted == expected
# --- Tests CodeAnalyzer handling of Attributes ---
class TestCodeAnalyzerAttributes:
@pytest.mark.parametrize(
"code_snippet, expected_structure",
[
pytest.param(
"""
class MyClass:
CLASS_VAR = 123
""",
[
{
"class_name": "MyClass",
"methods": [],
"attributes": [{"name": "CLASS_VAR", "type": None}],
}
],
id="class_var_assign",
),
pytest.param(
"""
class MyClass:
class_var: int = 456
""",
[
{
"class_name": "MyClass",
"methods": [],
"attributes": [{"name": "class_var", "type": "int"}],
}
],
id="class_var_annassign",
),
pytest.param(
"""
class MyClass:
class_var: int
""",
[
{
"class_name": "MyClass",
"methods": [],
"attributes": [{"name": "class_var", "type": "int"}],
}
],
id="class_var_annassign_no_value",
),
pytest.param(
"""
class MyClass:
def __init__(self):
self.instance_var = 789
""",
[
{
"class_name": "MyClass",
"methods": [
{
"method_name": "__init__",
"args": [{"name": "self", "type": None}],
"return_type": None,
}
],
"attributes": [{"name": "instance_var", "type": None}],
}
],
id="instance_var_assign",
),
pytest.param(
"""
class MyClass:
def __init__(self):
self.instance_var: str = 'hello'
""",
[
{
"class_name": "MyClass",
"methods": [
{
"method_name": "__init__",
"args": [{"name": "self", "type": None}],
"return_type": None,
}
],
"attributes": [{"name": "instance_var", "type": "str"}],
}
],
id="instance_var_annassign",
),
pytest.param(
"""
class MyClass:
def __init__(self):
self.instance_var: str
""",
[
{
"class_name": "MyClass",
"methods": [
{
"method_name": "__init__",
"args": [{"name": "self", "type": None}],
"return_type": None,
}
],
"attributes": [{"name": "instance_var", "type": "str"}],
}
],
id="instance_var_annassign_no_value",
),
pytest.param(
"""
class MyClass:
VAR_A = 1
var_b: int = 2
def __init__(self):
self.var_c = 3
self.var_d: float = 4.0
""",
[
{
"class_name": "MyClass",
"methods": [
{
"method_name": "__init__",
"args": [{"name": "self", "type": None}],
"return_type": None,
}
],
"attributes": [
{"name": "VAR_A", "type": None},
{"name": "var_b", "type": "int"},
{"name": "var_c", "type": None},
{"name": "var_d", "type": "float"},
],
}
],
id="mixed_attributes",
),
pytest.param(
"a = 123 # Module level",
[],
id="module_level_assign",
),
pytest.param(
"b: int = 456 # Module level",
[],
id="module_level_annassign",
),
],
)
def test_attribute_extraction(self, code_snippet: str, expected_structure: list):
"""Tests the extraction of class and instance attributes."""
analyzer = CodeAnalyzer()
tree = ast.parse(code_snippet)
analyzer.visit(tree)
extracted = analyzer.structure
# Normalize attributes for order-independent comparison
for item in extracted:
if "attributes" in item:
item["attributes"].sort(key=lambda x: x["name"])
for item in expected_structure:
if "attributes" in item:
item["attributes"].sort(key=lambda x: x["name"])
assert extracted == expected_structure
# --- Mock Types ---
class MyClass:
pass
class AnotherClass:
pass
class YetAnotherClass:
pass
def test_codeanalyzer_finds_class():
code = tw.dedent(
"""
class MyClass:
pass
"""
)
analyzer = CodeAnalyzer()
tree = ast.parse(code)
analyzer.visit(tree)
assert len(analyzer.structure) == 1
assert analyzer.structure[0]["class_name"] == "MyClass"
def test_codeanalyzer_finds_multiple_classes():
code = tw.dedent(
"""
class ClassA:
pass
class ClassB:
pass
"""
)
analyzer = CodeAnalyzer()
tree = ast.parse(code)
analyzer.visit(tree)
assert len(analyzer.structure) == 2
class_names = sorted([c["class_name"] for c in analyzer.structure])
assert class_names == ["ClassA", "ClassB"]
def test_codeanalyzer_finds_method():
code = tw.dedent(
"""
class MyClass:
def my_method(self):
pass
"""
)
analyzer = CodeAnalyzer()
tree = ast.parse(code)
analyzer.visit(tree)
assert len(analyzer.structure) == 1
assert len(analyzer.structure[0]["methods"]) == 1
assert analyzer.structure[0]["methods"][0]["method_name"] == "my_method"
def test_codeanalyzer_finds_multiple_methods():
code = tw.dedent(
"""
class MyClass:
def method_a(self):
pass
def method_b(self):
pass
"""
)
analyzer = CodeAnalyzer()
tree = ast.parse(code)
analyzer.visit(tree)
assert len(analyzer.structure) == 1
method_names = sorted([m["method_name"] for m in analyzer.structure[0]["methods"]])
assert method_names == ["method_a", "method_b"]
def test_codeanalyzer_no_classes():
code = tw.dedent(
"""
def top_level_function():
pass
"""
)
analyzer = CodeAnalyzer()
tree = ast.parse(code)
analyzer.visit(tree)
assert len(analyzer.structure) == 0
def test_codeanalyzer_class_with_no_methods():
code = tw.dedent(
"""
class MyClass:
attribute = 123
"""
)
analyzer = CodeAnalyzer()
tree = ast.parse(code)
analyzer.visit(tree)
assert len(analyzer.structure) == 1
assert analyzer.structure[0]["class_name"] == "MyClass"
assert len(analyzer.structure[0]["methods"]) == 0
# --- Test Data for Parameterization ---
TYPE_TEST_CASES = [
pytest.param(
tw.dedent(
"""
class TestClass:
def func(self, a: int, b: str) -> bool: return True
"""
),
[("a", "int"), ("b", "str")],
"bool",
id="simple_types",
),
pytest.param(
tw.dedent(
"""
from typing import Optional
class TestClass:
def func(self, a: Optional[int]) -> str | None: return 'hello'
"""
),
[("a", "Optional[int]")],
"str | None",
id="optional_union_none",
),
pytest.param(
tw.dedent(
"""
from typing import Union
class TestClass:
def func(self, a: int | float, b: Union[str, bytes]) -> None: pass
"""
),
[("a", "int | float"), ("b", "Union[str, bytes]")],
"None",
id="union_types",
),
pytest.param(
tw.dedent(
"""
from typing import List, Dict, Tuple
class TestClass:
def func(self, a: List[int], b: Dict[str, float]) -> Tuple[int, str]: return (1, 'a')
"""
),
[("a", "List[int]"), ("b", "Dict[str, float]")],
"Tuple[int, str]",
id="generic_types",
),
pytest.param(
tw.dedent(
"""
import datetime
from scripts.microgenerator.tests.unit.test_generate_analyzer import MyClass
class TestClass:
def func(self, a: datetime.date, b: MyClass) -> MyClass: return b
"""
),
[("a", "datetime.date"), ("b", "MyClass")],
"MyClass",
id="imported_types",
),
pytest.param(
tw.dedent(
"""
from scripts.microgenerator.tests.unit.test_generate_analyzer import AnotherClass, YetAnotherClass
class TestClass:
def func(self, a: 'AnotherClass') -> 'YetAnotherClass': return AnotherClass()
"""
),
[("a", "'AnotherClass'")],
"'YetAnotherClass'",
id="forward_refs",
),
pytest.param(
tw.dedent(
"""
class TestClass:
def func(self, a, b): return a + b
"""
),
[("a", None), ("b", None)], # No annotations means type is None
None,
id="no_annotations",
),
pytest.param(
tw.dedent(
"""
from typing import List, Optional, Dict, Union, Any
class TestClass:
def func(self, a: List[Optional[Dict[str, Union[int, str]]]]) -> Dict[str, Any]: return {}
"""
),
[("a", "List[Optional[Dict[str, Union[int, str]]]]")],
"Dict[str, Any]",
id="complex_nested",
),
pytest.param(
tw.dedent(
"""
from typing import Literal
class TestClass:
def func(self, a: Literal['one', 'two']) -> Literal[True]: return True
"""
),
[("a", "Literal['one', 'two']")],
"Literal[True]",
id="literal_type",
),
]
class TestCodeAnalyzerArgsReturns:
@pytest.mark.parametrize(
"code_snippet, expected_args, expected_return", TYPE_TEST_CASES
)
def test_type_extraction(self, code_snippet, expected_args, expected_return):
structure, imports, types = parse_code(code_snippet)
assert len(structure) == 1, "Should parse one class"
class_info = structure[0]
assert class_info["class_name"] == "TestClass"
assert len(class_info["methods"]) == 1, "Should find one method"
method_info = class_info["methods"][0]
assert method_info["method_name"] == "func"
# Extract args, skipping 'self'
extracted_args = []
for arg in method_info.get("args", []):
if arg["name"] == "self":
continue
extracted_args.append((arg["name"], arg["type"]))
assert extracted_args == expected_args
assert method_info.get("return_type") == expected_return