|
| 1 | +import ast |
| 2 | +from autogen.scripts.microgenerator.generate import CodeAnalyzer |
| 3 | + |
| 4 | + |
| 5 | +def test_codeanalyzer_finds_class(): |
| 6 | + code = """ |
| 7 | +class MyClass: |
| 8 | + pass |
| 9 | +""" |
| 10 | + analyzer = CodeAnalyzer() |
| 11 | + tree = ast.parse(code) |
| 12 | + analyzer.visit(tree) |
| 13 | + assert len(analyzer.structure) == 1 |
| 14 | + assert analyzer.structure[0]["class_name"] == "MyClass" |
| 15 | + |
| 16 | + |
| 17 | +def test_codeanalyzer_finds_multiple_classes(): |
| 18 | + code = """ |
| 19 | +class ClassA: |
| 20 | + pass |
| 21 | +
|
| 22 | +
|
| 23 | +class ClassB: |
| 24 | + pass |
| 25 | +""" |
| 26 | + analyzer = CodeAnalyzer() |
| 27 | + tree = ast.parse(code) |
| 28 | + analyzer.visit(tree) |
| 29 | + assert len(analyzer.structure) == 2 |
| 30 | + class_names = sorted([c["class_name"] for c in analyzer.structure]) |
| 31 | + assert class_names == ["ClassA", "ClassB"] |
| 32 | + |
| 33 | + |
| 34 | +def test_codeanalyzer_finds_method(): |
| 35 | + code = """ |
| 36 | +class MyClass: |
| 37 | + def my_method(self): |
| 38 | + pass |
| 39 | +""" |
| 40 | + analyzer = CodeAnalyzer() |
| 41 | + tree = ast.parse(code) |
| 42 | + analyzer.visit(tree) |
| 43 | + assert len(analyzer.structure) == 1 |
| 44 | + assert len(analyzer.structure[0]["methods"]) == 1 |
| 45 | + assert analyzer.structure[0]["methods"][0]["method_name"] == "my_method" |
| 46 | + |
| 47 | + |
| 48 | +def test_codeanalyzer_finds_multiple_methods(): |
| 49 | + code = """ |
| 50 | +class MyClass: |
| 51 | + def method_a(self): |
| 52 | + pass |
| 53 | +
|
| 54 | + def method_b(self): |
| 55 | + pass |
| 56 | +""" |
| 57 | + analyzer = CodeAnalyzer() |
| 58 | + tree = ast.parse(code) |
| 59 | + analyzer.visit(tree) |
| 60 | + assert len(analyzer.structure) == 1 |
| 61 | + method_names = sorted([m["method_name"] for m in analyzer.structure[0]["methods"]]) |
| 62 | + assert method_names == ["method_a", "method_b"] |
| 63 | + |
| 64 | + |
| 65 | +def test_codeanalyzer_no_classes(): |
| 66 | + code = """ |
| 67 | +def top_level_function(): |
| 68 | + pass |
| 69 | +""" |
| 70 | + analyzer = CodeAnalyzer() |
| 71 | + tree = ast.parse(code) |
| 72 | + analyzer.visit(tree) |
| 73 | + assert len(analyzer.structure) == 0 |
| 74 | + |
| 75 | + |
| 76 | +def test_codeanalyzer_class_with_no_methods(): |
| 77 | + code = """ |
| 78 | +class MyClass: |
| 79 | + attribute = 123 |
| 80 | +""" |
| 81 | + analyzer = CodeAnalyzer() |
| 82 | + tree = ast.parse(code) |
| 83 | + analyzer.visit(tree) |
| 84 | + assert len(analyzer.structure) == 1 |
| 85 | + assert analyzer.structure[0]["class_name"] == "MyClass" |
| 86 | + assert len(analyzer.structure[0]["methods"]) == 0 |
0 commit comments