| """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: |
| |
| if not alias.name.startswith(".") and not alias.name.startswith("_"): |
| pass |
| 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() |
|
|
| |
| 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 |
|
|
| |
| validator = ResponseValidator() |
| result = validator.validate("", "test") |
| assert result.score >= 0 |
|
|
|
|
| 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 |
|
|
| |
| 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 |
|
|
| |
| 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() |
|
|
| |
| 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"]) |
|
|