import tempfile from pathlib import Path from patternforge.analyzer import CodeAnalyzer from patternforge.config import Config class TestCodeAnalyzer: def setup_method(self) -> None: self.config = Config() def test_analyze_python_file(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: py_file = Path(tmpdir) / "test.py" py_file.write_text( """ class MyClass: def my_method(self): pass def my_function(): pass """ ) analyzer = CodeAnalyzer("python", self.config) result = analyzer.analyze(tmpdir) assert result["language"] == "python" assert result["files_analyzed"] == 1 assert result["summary"]["classes"] >= 1 def test_analyze_javascript_file(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: js_file = Path(tmpdir) / "test.js" js_file.write_text( """ function myFunction() { return true; } class MyClass { constructor() {} } """ ) analyzer = CodeAnalyzer("javascript", self.config) result = analyzer.analyze(tmpdir) assert result["language"] == "javascript" assert result["files_analyzed"] == 1 def test_naming_convention_detection(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: py_file = Path(tmpdir) / "test.py" py_file.write_text( """ class MyClass: pass def my_function(): pass my_variable = 42 MY_CONSTANT = 100 """ ) analyzer = CodeAnalyzer("python", self.config) result = analyzer.analyze(tmpdir) naming = result.get("naming_conventions", {}) assert "PascalCase" in naming or "snake_case" in naming def test_save_patterns(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: py_file = Path(tmpdir) / "test.py" py_file.write_text("def test():\n pass\n") output_file = Path(tmpdir) / "patterns.yaml" analyzer = CodeAnalyzer("python", self.config) result = analyzer.analyze(tmpdir) analyzer.save_patterns(str(output_file), result) assert output_file.exists() import yaml loaded = yaml.safe_load(output_file.read_text()) assert loaded["language"] == "python" def test_empty_directory(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: analyzer = CodeAnalyzer("python", self.config) result = analyzer.analyze(tmpdir) assert result.get("error") == "No matching files found" def test_recursive_analysis(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: subdir = Path(tmpdir) / "subdir" subdir.mkdir() py_file1 = Path(tmpdir) / "test1.py" py_file2 = subdir / "test2.py" py_file1.write_text("class A: pass\n") py_file2.write_text("class B: pass\n") analyzer = CodeAnalyzer("python", self.config) result = analyzer.analyze(tmpdir, recursive=True) assert result["files_analyzed"] == 2 result_no_recursive = analyzer.analyze(tmpdir, recursive=False) assert result_no_recursive["files_analyzed"] == 1