File size: 12,450 Bytes
40fd3fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Quality Assurance Testing Suite

Comprehensive QA tests for burme-coder-max project.
Covers: Code Quality, Functionality, Performance, Security.
"""

import pytest
import ast
import os
import re
import sys
from pathlib import Path
from typing import List, Dict, Tuple

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))


class TestCodeQuality:
    """Code quality validation tests."""

    PROJECT_ROOT = Path(__file__).parent.parent

    def test_python_syntax(self):
        """Verify all Python files have valid syntax."""
        errors = []
        for py_file in self.PROJECT_ROOT.rglob("*.py"):
            if ".venv" in str(py_file) or "venv" in str(py_file):
                continue
            try:
                content = py_file.read_text(encoding="utf-8")
                ast.parse(content)
            except SyntaxError as e:
                errors.append(f"{py_file}: {e}")

        assert not errors, f"Syntax errors found:\n" + "\n".join(errors)

    def test_docstrings_present(self):
        """Check module-level docstrings exist."""
        missing_docs = []
        for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
            if py_file.name == "__init__.py":
                continue
            content = py_file.read_text(encoding="utf-8")
            if '"""' not in content and "'''" not in content:
                missing_docs.append(py_file.name)

        assert not missing_docs, f"Missing docstrings in: {missing_docs}"

    def test_imports_are_valid(self):
        """Verify all imports can be resolved."""
        for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
            content = py_file.read_text(encoding="utf-8")
            tree = ast.parse(content)
            for node in ast.walk(tree):
                if isinstance(node, ast.Import):
                    for alias in node.names:
                        # Skip relative imports and external packages
                        if not alias.name.startswith(".") and not alias.name.startswith("_"):
                            pass  # External packages assumed valid
                elif isinstance(node, ast.ImportFrom):
                    module = node.module or ""
                    if module.startswith("_"):
                        pytest.fail(f"Import from private module: {module} in {py_file}")

    def test_no_debug_code(self):
        """Check for debug/ad-hoc code."""
        debug_patterns = [
            r"print\s*\(\s*debug",
            r"print\s*\(\s*TODO",
            r"print\s*\(\s*FIXME",
            r"print\s*\(\s*console\.log",
            r"import\s+pdb",
            r"import\s+ipdb",
        ]
        violations = []
        for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
            content = py_file.read_text(encoding="utf-8")
            for pattern in debug_patterns:
                if re.search(pattern, content, re.IGNORECASE):
                    violations.append(f"{py_file.name}: {pattern}")

        assert not violations, f"Debug code found:\n{violations}"


class TestFunctionality:
    """Functional tests for core modules."""

    def test_agent_initialization(self):
        """Test CoderAgent can be initialized."""
        from core.agent import CoderAgent
        agent = CoderAgent()
        assert agent is not None
        assert agent.model == "gpt-4"
        assert agent.session_id is not None

    def test_agent_generate_response(self):
        """Test response generation returns expected structure."""
        from core.agent import CoderAgent
        agent = CoderAgent()
        response = agent.generate_response("test instruction")

        assert "session_id" in response
        assert "instruction" in response
        assert "response" in response
        assert "timestamp" in response
        assert "model" in response

    def test_executor_initialization(self):
        """Test CodeExecutor initialization."""
        from core.executor import CodeExecutor, ExecutionResult
        executor = CodeExecutor(timeout=10)
        assert executor.timeout == 10
        assert executor.execution_count == 0

    def test_validator_initialization(self):
        """Test ResponseValidator initialization."""
        from core.validator import ResponseValidator, ValidationResult
        validator = ResponseValidator()
        result = validator.validate("def test(): pass", "test function")

        assert isinstance(result, ValidationResult)
        assert hasattr(result, "quality")
        assert hasattr(result, "score")
        assert hasattr(result, "issues")

    def test_animation_configs(self):
        """Test all animation classes are importable."""
        from animations import Spinner, ProgressBar, ParticleBurst, TypingEffect
        assert Spinner is not None
        assert ProgressBar is not None
        assert ParticleBurst is not None
        assert TypingEffect is not None

    def test_knowledge_base_search(self):
        """Test LocalKB search functionality."""
        from knowledge import LocalKB
        kb = LocalKB()
        results = kb.search("python")
        assert isinstance(results, list)


class TestSecurity:
    """Security validation tests."""

    PROJECT_ROOT = Path(__file__).parent.parent

    def test_no_hardcoded_secrets(self):
        """Check for hardcoded passwords/secrets in code."""
        secret_patterns = [
            r"password\s*=\s*['\"][^'\"]{8,}['\"]",
            r"api_key\s*=\s*['\"][^'\"]{20,}['\"]",
            r"secret\s*=\s*['\"][^'\"]{20,}['\"]",
            r"token\s*=\s*['\"][A-Za-z0-9_\-]{30,}['\"]",
        ]
        violations = []
        for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
            content = py_file.read_text(encoding="utf-8")
            for pattern in secret_patterns:
                if re.search(pattern, content, re.IGNORECASE):
                    violations.append(f"{py_file.name}")

        assert not violations, f"Hardcoded secrets found in: {violations}"

    def test_sql_injection_protection(self):
        """Verify SQL queries use parameterized inputs."""
        dangerous_sql = ["SELECT * FROM users WHERE name = '" + "' + user_input + '"]
        violations = []
        for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
            content = py_file.read_text(encoding="utf-8")
            if "sql" in content.lower() or "query" in content.lower():
                for dangerous in dangerous_sql:
                    if dangerous in content:
                        violations.append(py_file.name)

        assert not violations, f"SQL injection vulnerable code: {violations}"

    def test_shell_injection_protection(self):
        """Verify shell commands are safe."""
        from core.executor import CodeExecutor
        executor = CodeExecutor()

        # Should detect potentially malicious code
        malicious = "__import__('os').system('rm -rf /')"
        result = executor._contains_malicious_code(malicious)
        assert result == True

    def test_input_validation(self):
        """Test input validation in key modules."""
        from core.validator import ResponseValidator

        # Empty response should still validate
        validator = ResponseValidator()
        result = validator.validate("", "test")
        assert result.score >= 0  # Score should be defined


class TestPerformance:
    """Performance-related tests."""

    def test_import_time(self):
        """Measure import time for core modules."""
        import time

        start = time.time()
        from core.agent import CoderAgent
        from core.executor import CodeExecutor
        from core.validator import ResponseValidator
        import_duration = time.time() - start

        # Should import in under 2 seconds
        assert import_duration < 2.0, f"Import took {import_duration}s"

    def test_agent_response_time(self):
        """Test response generation time."""
        import time
        from core.agent import CoderAgent

        agent = CoderAgent()
        start = time.time()
        response = agent.generate_response("test")
        duration = time.time() - start

        # Should complete in reasonable time
        assert duration < 5.0, f"Response took {duration}s"


class TestIntegration:
    """Integration tests across modules."""

    def test_full_agent_workflow(self):
        """Test complete agent workflow."""
        from core.agent import CoderAgent
        from core.validator import ResponseValidator

        agent = CoderAgent()
        validator = ResponseValidator()

        instruction = "Write a Python hello world function"
        response = agent.generate_response(instruction)
        validation = validator.validate(response["response"], instruction)

        assert validation.score > 0
        assert len(response["response"]) > 0

    def test_animation_with_agent(self):
        """Test animations working with agent."""
        import time
        from animations import Spinner
        from core.agent import CoderAgent

        agent = CoderAgent()
        with Spinner("Testing..."):
            response = agent.generate_response("test")
            time.sleep(0.1)

        assert len(response["response"]) > 0

    def test_knowledge_with_agent(self):
        """Test knowledge base integration."""
        from core.agent import CoderAgent
        from knowledge import LocalKB

        agent = CoderAgent()
        kb = LocalKB()

        # Create agent with knowledge dir
        agent_with_kb = CoderAgent(
            knowledge_dir=str(Path(__file__).parent.parent / "data" / "knowledge")
        )
        response = agent_with_kb.generate_response("python decorator hta ya")

        assert len(response["response"]) > 0


class TestDocumentation:
    """Documentation quality tests."""

    PROJECT_ROOT = Path(__file__).parent.parent

    def test_readme_exists(self):
        """Verify README.md exists."""
        readme = self.PROJECT_ROOT / "README.md"
        assert readme.exists(), "README.md not found"

    def test_readme_has_install_section(self):
        """Check README has installation instructions."""
        readme = (self.PROJECT_ROOT / "README.md").read_text(encoding="utf-8")
        assert "install" in readme.lower(), "Install section missing"

    def test_readme_has_usage_section(self):
        """Check README has usage examples."""
        readme = (self.PROJECT_ROOT / "README.md").read_text(encoding="utf-8")
        assert "usage" in readme.lower() or "example" in readme.lower()

    def test_docs_directory_exists(self):
        """Verify docs directory exists."""
        docs_dir = self.PROJECT_ROOT / "docs"
        assert docs_dir.exists(), "docs/ directory not found"

    def test_all_md_files_have_content(self):
        """Check all markdown files have substantial content."""
        small_files = []
        for md_file in self.PROJECT_ROOT.rglob("*.md"):
            content = md_file.read_text(encoding="utf-8")
            if len(content) < 100:
                small_files.append(md_file.name)

        assert not small_files, f"Very short markdown files: {small_files}"


class QAReport:
    """Generate QA report."""

    CLASSES = [
        TestCodeQuality,
        TestFunctionality,
        TestSecurity,
        TestPerformance,
        TestIntegration,
        TestDocumentation,
    ]

    @classmethod
    def run_all(cls) -> Dict:
        """Run all test classes and generate report."""
        from collections import defaultdict

        results = defaultdict(list)
        for test_class in cls.CLASSES:
            class_name = test_class.__name__
            for method_name in dir(test_class):
                if method_name.startswith("test_"):
                    try:
                        instance = test_class()
                        method = getattr(instance, method_name)
                        method()
                        results[class_name].append({
                            "name": method_name,
                            "status": "PASS"
                        })
                    except Exception as e:
                        results[class_name].append({
                            "name": method_name,
                            "status": "FAIL",
                            "error": str(e)
                        })

        return dict(results)


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])