Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_database_advanced.py
| """ | |
| Database Advanced Tests for Zen-AI-Pentest | |
| Tests for relationships, initialization, edge cases, complex queries, | |
| multi-user scenarios, performance, and additional coverage. | |
| """ | |
| import os | |
| import sys | |
| from datetime import datetime, timezone | |
| from unittest.mock import MagicMock, PropertyMock, patch | |
| import pytest | |
| from sqlalchemy import create_engine | |
| from sqlalchemy.orm import sessionmaker | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../..")) | |
| from database import crud | |
| from database.models import ( | |
| Asset, | |
| AuditLog, | |
| Base, | |
| Finding, | |
| Notification, | |
| Report, | |
| ReportFormat, | |
| ReportStatus, | |
| Scan, | |
| ScanStatus, | |
| Severity, | |
| ToolConfig, | |
| User, | |
| VulnerabilityDB, | |
| ) | |
| from database.models import bulk_create_findings as models_bulk_create_findings | |
| from database.models import create_audit_log as models_create_audit_log | |
| from database.models import ( | |
| create_default_admin, | |
| ) | |
| from database.models import create_finding as models_create_finding | |
| from database.models import create_report as models_create_report | |
| from database.models import create_scan as models_create_scan | |
| from database.models import ( | |
| get_db, | |
| ) | |
| from database.models import get_findings as models_get_findings | |
| from database.models import get_findings_by_severity as models_get_findings_by_severity | |
| from database.models import get_reports as models_get_reports | |
| from database.models import get_scan as models_get_scan | |
| from database.models import get_scans as models_get_scans | |
| from database.models import get_scans_by_user as models_get_scans_by_user | |
| from database.models import ( | |
| init_db, | |
| ) | |
| from database.models import update_scan_status as models_update_scan_status | |
| def db_engine(): | |
| engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False}, echo=False) | |
| Base.metadata.create_all(bind=engine) | |
| yield engine | |
| Base.metadata.drop_all(bind=engine) | |
| def db_session(db_engine): | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=db_engine) | |
| session = SessionLocal() | |
| yield session | |
| session.close() | |
| def sample_user(db_session): | |
| user = User( | |
| username="testuser", email="test@example.com", hashed_password="hashed_password_123", role="operator", is_active=1 | |
| ) | |
| db_session.add(user) | |
| db_session.commit() | |
| db_session.refresh(user) | |
| return user | |
| def sample_admin(db_session): | |
| user = User( | |
| username="adminuser", email="admin@example.com", hashed_password="hashed_admin_pass", role="admin", is_active=1 | |
| ) | |
| db_session.add(user) | |
| db_session.commit() | |
| db_session.refresh(user) | |
| return user | |
| def sample_scan(db_session, sample_user): | |
| scan = Scan( | |
| name="Test Scan", | |
| target="example.com", | |
| scan_type="nmap", | |
| status=ScanStatus.PENDING, | |
| config={"ports": "80,443"}, | |
| user_id=sample_user.id, | |
| ) | |
| db_session.add(scan) | |
| db_session.commit() | |
| db_session.refresh(scan) | |
| return scan | |
| def sample_finding(db_session, sample_scan): | |
| finding = Finding( | |
| scan_id=sample_scan.id, | |
| title="SQL Injection", | |
| description="SQL injection vulnerability found in login form", | |
| severity=Severity.HIGH, | |
| cvss_score=7.5, | |
| cve_id="CVE-2023-1234", | |
| evidence="payload: ' OR 1=1 --", | |
| remediation="Use parameterized queries", | |
| tool="sqlmap", | |
| target="example.com/login", | |
| port=443, | |
| service="https", | |
| verified=1, | |
| ) | |
| db_session.add(finding) | |
| db_session.commit() | |
| db_session.refresh(finding) | |
| return finding | |
| def sample_report(db_session, sample_scan, sample_user): | |
| report = Report( | |
| scan_id=sample_scan.id, | |
| user_id=sample_user.id, | |
| name="test-report", | |
| format=ReportFormat.PDF, | |
| template="default", | |
| status=ReportStatus.PENDING, | |
| file_path="/reports/test.pdf", | |
| file_size=1024, | |
| ) | |
| db_session.add(report) | |
| db_session.commit() | |
| db_session.refresh(report) | |
| return report | |
| class TestRelationships: | |
| """Tests for model relationships.""" | |
| def test_user_scans_count(self, db_session, sample_user): | |
| initial_count = db_session.query(Scan).filter(Scan.user_id == sample_user.id).count() | |
| for i in range(5): | |
| scan = Scan(name=f"Scan {i}", target=f"target{i}.com", scan_type="nmap", user_id=sample_user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| count = db_session.query(Scan).filter(Scan.user_id == sample_user.id).count() | |
| assert count == initial_count + 5 | |
| def test_user_reports_count(self, db_session, sample_user, sample_scan): | |
| initial_count = db_session.query(Report).filter(Report.user_id == sample_user.id).count() | |
| for i in range(3): | |
| report = Report(scan_id=sample_scan.id, user_id=sample_user.id, name=f"report-{i}", format=ReportFormat.PDF) | |
| db_session.add(report) | |
| db_session.commit() | |
| count = db_session.query(Report).filter(Report.user_id == sample_user.id).count() | |
| assert count == initial_count + 3 | |
| def test_scan_findings_count(self, db_session, sample_scan): | |
| initial_count = db_session.query(Finding).filter(Finding.scan_id == sample_scan.id).count() | |
| for i in range(10): | |
| finding = Finding(scan_id=sample_scan.id, title=f"Finding {i}", description="Test") | |
| db_session.add(finding) | |
| db_session.commit() | |
| count = db_session.query(Finding).filter(Finding.scan_id == sample_scan.id).count() | |
| assert count == initial_count + 10 | |
| def test_scan_reports_count(self, db_session, sample_scan, sample_user): | |
| initial_count = db_session.query(Report).filter(Report.scan_id == sample_scan.id).count() | |
| for i in range(4): | |
| report = Report(scan_id=sample_scan.id, user_id=sample_user.id, name=f"scan-report-{i}", format=ReportFormat.JSON) | |
| db_session.add(report) | |
| db_session.commit() | |
| count = db_session.query(Report).filter(Report.scan_id == sample_scan.id).count() | |
| assert count == initial_count + 4 | |
| def test_cascade_delete_scan_removes_findings(self, db_session, sample_user): | |
| scan = Scan(name="Cascade Test", target="cascade.test.com", scan_type="nmap", user_id=sample_user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| db_session.refresh(scan) | |
| scan_id = scan.id | |
| for i in range(5): | |
| finding = Finding(scan_id=scan_id, title=f"Cascade Finding {i}", description="Test") | |
| db_session.add(finding) | |
| db_session.commit() | |
| findings_count_before = db_session.query(Finding).filter(Finding.scan_id == scan_id).count() | |
| assert findings_count_before == 5 | |
| scan = db_session.query(Scan).filter(Scan.id == scan_id).first() | |
| db_session.delete(scan) | |
| db_session.commit() | |
| findings_count_after = db_session.query(Finding).filter(Finding.scan_id == scan_id).count() | |
| assert findings_count_after == 0 | |
| def test_delete_user_does_not_cascade_scans(self, db_session, sample_user, sample_scan): | |
| scan_id = sample_scan.id | |
| db_session.delete(sample_user) | |
| db_session.commit() | |
| scan = db_session.query(Scan).filter(Scan.id == scan_id).first() | |
| assert scan is not None | |
| class TestDatabaseInitialization: | |
| """Tests for database initialization functions.""" | |
| def test_init_db_creates_tables(self, db_engine): | |
| from sqlalchemy import inspect | |
| inspector = inspect(db_engine) | |
| tables = inspector.get_table_names() | |
| expected_tables = [ | |
| "users", | |
| "scans", | |
| "findings", | |
| "reports", | |
| "vulnerabilities", | |
| "assets", | |
| "audit_logs", | |
| "notifications", | |
| "tool_configs", | |
| ] | |
| for table in expected_tables: | |
| assert table in tables | |
| def test_get_db_generator(self, db_engine): | |
| import inspect | |
| from database.models import get_db as models_get_db | |
| assert inspect.isgeneratorfunction(models_get_db) | |
| def test_create_default_admin(self, db_session): | |
| with patch("database.models.SessionLocal") as mock_session_local: | |
| mock_session = MagicMock() | |
| mock_session_local.return_value = mock_session | |
| mock_session.__enter__ = MagicMock(return_value=mock_session) | |
| mock_session.__exit__ = MagicMock(return_value=None) | |
| mock_session.query.return_value.filter.return_value.first.return_value = None | |
| create_default_admin() | |
| assert mock_session.add.called | |
| assert mock_session.commit.called | |
| class TestEdgeCases: | |
| """Tests for edge cases and error handling.""" | |
| def test_empty_string_values(self, db_session, sample_user): | |
| scan = Scan(name="", target="", scan_type="", user_id=sample_user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| assert scan.name == "_" | |
| assert scan.target == "" | |
| def test_null_values(self, db_session, sample_scan): | |
| finding = Finding(scan_id=sample_scan.id, title="Null Test", description=None, evidence=None, remediation=None) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert finding.description is None | |
| assert finding.evidence is None | |
| def test_very_long_strings(self, db_session, sample_scan): | |
| long_title = "A" * 500 | |
| long_description = "B" * 10000 | |
| finding = Finding(scan_id=sample_scan.id, title=long_title, description=long_description) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert finding.title == long_title | |
| def test_unicode_characters(self, db_session, sample_user): | |
| scan = Scan( | |
| name="Unicode Test 🔒 🛡️", | |
| target="日本語.example.com", | |
| scan_type="nmap", | |
| config={"unicode": "测试"}, | |
| user_id=sample_user.id, | |
| ) | |
| db_session.add(scan) | |
| db_session.commit() | |
| assert "🔒" in scan.name | |
| assert "日本語" in scan.target | |
| def test_special_characters_in_strings(self, db_session, sample_scan): | |
| finding = Finding( | |
| scan_id=sample_scan.id, | |
| title="<script>alert('XSS')</script>", | |
| description="Test & Test <br> More", | |
| evidence="' OR 1=1 --", | |
| ) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert "<script>" in finding.title | |
| def test_negative_numbers(self, db_session, sample_scan): | |
| finding = Finding(scan_id=sample_scan.id, title="Negative Test", cvss_score=-1.0, port=-1) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert finding.cvss_score == -1.0 | |
| assert finding.port == -1 | |
| def test_zero_values(self, db_session, sample_scan): | |
| finding = Finding(scan_id=sample_scan.id, title="Zero Test", cvss_score=0.0, port=0, verified=0) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert finding.cvss_score == 0.0 | |
| assert finding.port == 0 | |
| assert finding.verified == 0 | |
| def test_large_numbers(self, db_session, sample_scan): | |
| finding = Finding(scan_id=sample_scan.id, title="Large Number Test", port=65535) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert finding.port == 65535 | |
| def test_float_precision(self, db_session, sample_scan): | |
| finding = Finding(scan_id=sample_scan.id, title="Float Test", cvss_score=7.123456789) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert abs(finding.cvss_score - 7.123456789) < 0.0001 | |
| def test_nested_json_config(self, db_session, sample_user): | |
| scan = Scan( | |
| name="Nested Config Test", | |
| target="example.com", | |
| scan_type="nmap", | |
| config={"level1": {"level2": {"level3": {"deep": "value"}}}, "list": [1, 2, 3, {"nested_in_list": True}]}, | |
| user_id=sample_user.id, | |
| ) | |
| db_session.add(scan) | |
| db_session.commit() | |
| assert scan.config["level1"]["level2"]["level3"]["deep"] == "value" | |
| class TestComplexQueries: | |
| """Tests for complex database queries.""" | |
| def test_findings_by_severity_count(self, db_session, sample_scan): | |
| severities = [ | |
| Severity.CRITICAL, | |
| Severity.HIGH, | |
| Severity.HIGH, | |
| Severity.MEDIUM, | |
| Severity.MEDIUM, | |
| Severity.MEDIUM, | |
| Severity.LOW, | |
| Severity.INFO, | |
| ] | |
| for i, severity in enumerate(severities): | |
| finding = Finding(scan_id=sample_scan.id, title=f"Finding {i}", description="Test", severity=severity) | |
| db_session.add(finding) | |
| db_session.commit() | |
| assert db_session.query(Finding).filter(Finding.severity == Severity.CRITICAL).count() == 1 | |
| assert db_session.query(Finding).filter(Finding.severity == Severity.HIGH).count() == 2 | |
| def test_scans_by_date_range(self, db_session, sample_user): | |
| from datetime import timedelta | |
| for i in range(5): | |
| scan = Scan(name=f"Date Scan {i}", target=f"date{i}.com", scan_type="nmap", user_id=sample_user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| scans = db_session.query(Scan).order_by(Scan.created_at.desc()).all() | |
| assert len(scans) >= 5 | |
| def test_user_scan_findings_join(self, db_session, sample_user): | |
| scan = Scan(name="Join Test Scan", target="join.test.com", scan_type="nmap", user_id=sample_user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| for i in range(3): | |
| finding = Finding(scan_id=scan.id, title=f"Join Finding {i}", description="Test") | |
| db_session.add(finding) | |
| db_session.commit() | |
| results = db_session.query(Finding).join(Scan).filter(Scan.user_id == sample_user.id).all() | |
| assert len(results) >= 3 | |
| def test_group_by_severity(self, db_session, sample_scan): | |
| from sqlalchemy import func | |
| for severity in [Severity.HIGH, Severity.HIGH, Severity.MEDIUM]: | |
| finding = Finding(scan_id=sample_scan.id, title=f"Group {severity} Finding", description="Test", severity=severity) | |
| db_session.add(finding) | |
| db_session.commit() | |
| results = db_session.query(Finding.severity, func.count(Finding.id)).group_by(Finding.severity).all() | |
| severity_counts = {r[0]: r[1] for r in results} | |
| assert Severity.HIGH in severity_counts | |
| assert Severity.MEDIUM in severity_counts | |
| class TestMultiUserScenarios: | |
| """Tests for multi-user scenarios.""" | |
| def test_multiple_users_same_target(self, db_session): | |
| target = "shared-target.com" | |
| for i in range(3): | |
| user = User(username=f"user{i}", email=f"user{i}@test.com", hashed_password="pass") | |
| db_session.add(user) | |
| db_session.commit() | |
| scan = Scan(name=f"User {i} Scan", target=target, scan_type="nmap", user_id=user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| scans = db_session.query(Scan).filter(Scan.target == target).all() | |
| assert len(scans) == 3 | |
| def test_user_isolation(self, db_session): | |
| user1 = User(username="iso1", email="iso1@test.com", hashed_password="pass") | |
| user2 = User(username="iso2", email="iso2@test.com", hashed_password="pass") | |
| db_session.add_all([user1, user2]) | |
| db_session.commit() | |
| scan1 = Scan(name="User1 Scan", target="target1.com", scan_type="nmap", user_id=user1.id) | |
| db_session.add(scan1) | |
| db_session.commit() | |
| user2_scans = db_session.query(Scan).filter(Scan.user_id == user2.id).all() | |
| assert len(user2_scans) == 0 | |
| def test_admin_can_see_all(self, db_session, sample_admin, sample_user): | |
| for i in range(3): | |
| scan = Scan(name=f"User Scan {i}", target=f"target{i}.com", scan_type="nmap", user_id=sample_user.id) | |
| db_session.add(scan) | |
| db_session.commit() | |
| all_scans = db_session.query(Scan).all() | |
| assert len(all_scans) == 3 | |
| class TestPerformanceAndBulk: | |
| """Tests for performance and bulk operations.""" | |
| def test_bulk_insert_findings(self, db_session, sample_scan): | |
| findings_data = [ | |
| { | |
| "scan_id": sample_scan.id, | |
| "title": f"Bulk Finding {i}", | |
| "description": f"Description {i}", | |
| "severity": Severity.HIGH.value, | |
| } | |
| for i in range(100) | |
| ] | |
| models_bulk_create_findings(db_session, findings_data) | |
| count = db_session.query(Finding).filter(Finding.scan_id == sample_scan.id).count() | |
| assert count == 100 | |
| def test_large_scan_result_summary(self, db_session, sample_user): | |
| large_result = {"findings": [{"id": i, "data": "x" * 100} for i in range(1000)]} | |
| scan = models_create_scan( | |
| db_session, name="Large Result Scan", target="large.test.com", scan_type="nmap", config={}, user_id=sample_user.id | |
| ) | |
| scan.result_summary = str(large_result) | |
| db_session.commit() | |
| assert len(scan.result_summary) > 1000 | |
| def test_many_findings_query_performance(self, db_session, sample_scan): | |
| for i in range(1000): | |
| finding = Finding( | |
| scan_id=sample_scan.id, | |
| title=f"Finding {i}", | |
| description="Test", | |
| severity=Severity.MEDIUM if i % 2 == 0 else Severity.HIGH, | |
| ) | |
| db_session.add(finding) | |
| db_session.commit() | |
| import time | |
| start = time.time() | |
| high_findings = db_session.query(Finding).filter(Finding.severity == Severity.HIGH).all() | |
| elapsed = time.time() - start | |
| assert len(high_findings) == 500 | |
| assert elapsed < 5 | |
| class TestCoverage: | |
| """Tests to verify coverage of all code paths.""" | |
| def test_all_models_imported(self): | |
| from database.models import Finding, Report, Scan, User | |
| assert all([User, Scan, Finding, Report, VulnerabilityDB, Asset, AuditLog, Notification, ToolConfig]) | |
| def test_all_enums_imported(self): | |
| from database.models import ReportFormat, ReportStatus, ScanStatus, Severity | |
| assert all([ScanStatus, Severity, ReportFormat, ReportStatus]) | |
| def test_all_crud_functions_exist(self): | |
| assert callable(models_create_scan) | |
| assert callable(models_get_scan) | |
| assert callable(models_get_scans) | |
| assert callable(models_update_scan_status) | |
| assert callable(models_create_finding) | |
| assert callable(models_create_report) | |
| assert callable(models_create_audit_log) | |
| assert callable(crud.create_scan) | |
| assert callable(crud.get_scan) | |
| assert callable(crud.get_scans) | |
| assert callable(crud.update_scan_status) | |
| assert callable(crud.create_finding) | |
| assert callable(crud.get_findings) | |
| assert callable(crud.create_report) | |
| assert callable(crud.get_reports) | |
| class TestAdditionalCoverage: | |
| """Additional tests to improve coverage.""" | |
| def test_get_db_context_manager(self, db_engine): | |
| db_gen = get_db() | |
| db = next(db_gen) | |
| assert db is not None | |
| try: | |
| next(db_gen) | |
| except StopIteration: | |
| pass | |
| def test_models_get_scans_with_status_filter(self, db_session, sample_user): | |
| scan1 = models_create_scan( | |
| db_session, | |
| name="Pending Filter Scan", | |
| target="pending.test.com", | |
| scan_type="nmap", | |
| config={}, | |
| user_id=sample_user.id, | |
| ) | |
| scan1.status = ScanStatus.PENDING | |
| db_session.commit() | |
| scan2 = models_create_scan( | |
| db_session, | |
| name="Completed Filter Scan", | |
| target="completed.test.com", | |
| scan_type="nmap", | |
| config={}, | |
| user_id=sample_user.id, | |
| ) | |
| scan2.status = ScanStatus.COMPLETED | |
| db_session.commit() | |
| pending_scans = models_get_scans(db_session, status="pending") | |
| assert len([s for s in pending_scans if s.name == "Pending Filter Scan"]) == 1 | |
| def test_models_get_scans_with_skip_limit(self, db_session, sample_user): | |
| for i in range(10): | |
| models_create_scan( | |
| db_session, | |
| name=f"SkipLimit Scan {i}", | |
| target=f"skip{i}.test.com", | |
| scan_type="nmap", | |
| config={}, | |
| user_id=sample_user.id, | |
| ) | |
| scans_page1 = models_get_scans(db_session, skip=0, limit=5) | |
| assert len(scans_page1) >= 5 | |
| scans_page2 = models_get_scans(db_session, skip=5, limit=5) | |
| assert len(scans_page2) >= 5 | |
| def test_models_update_scan_status_running_sets_started_at(self, db_session, sample_user): | |
| scan = models_create_scan( | |
| db_session, name="Started At Test", target="started.test.com", scan_type="nmap", config={}, user_id=sample_user.id | |
| ) | |
| assert scan.started_at is None | |
| updated = models_update_scan_status(db_session, scan.id, "running") | |
| assert updated.started_at is not None | |
| def test_models_update_scan_status_failed_sets_completed_at(self, db_session, sample_user): | |
| scan = models_create_scan( | |
| db_session, name="Failed At Test", target="failed.test.com", scan_type="nmap", config={}, user_id=sample_user.id | |
| ) | |
| assert scan.completed_at is None | |
| updated = models_update_scan_status(db_session, scan.id, "failed") | |
| assert updated.completed_at is not None | |
| def test_crud_update_scan_status_limits_result_length(self, db_session, sample_scan): | |
| long_result = {"data": "x" * 2000} | |
| updated = crud.update_scan_status(db_session, sample_scan.id, "completed", long_result) | |
| assert updated.result_summary is not None | |
| assert len(updated.result_summary) <= 1005 | |
| def test_get_findings_with_severity_filter(self, db_session, sample_scan): | |
| for severity in [Severity.HIGH, Severity.MEDIUM, Severity.LOW]: | |
| finding = Finding( | |
| scan_id=sample_scan.id, title=f"{severity.value} Severity Finding", description="Test", severity=severity | |
| ) | |
| db_session.add(finding) | |
| db_session.commit() | |
| high_findings = models_get_findings(db_session, sample_scan.id, severity="high") | |
| assert len(high_findings) == 1 | |
| assert high_findings[0].severity == Severity.HIGH | |
| def test_models_create_finding_minimum_fields(self, db_session, sample_scan): | |
| finding = models_create_finding( | |
| db_session, scan_id=sample_scan.id, title="Minimal Finding", description="Minimal description" | |
| ) | |
| assert finding.title == "Minimal Finding" | |
| assert finding.severity == "medium" | |
| assert finding.cvss_score is None | |
| assert finding.target is None | |
| def test_bulk_create_findings_empty_list(self, db_session): | |
| models_bulk_create_findings(db_session, []) | |
| count = db_session.query(Finding).count() | |
| assert count >= 0 | |
| def test_models_get_findings_by_severity_empty(self, db_session): | |
| findings = models_get_findings_by_severity(db_session, "critical") | |
| assert findings == [] | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v"]) | |
Xet Storage Details
- Size:
- 23.6 kB
- Xet hash:
- 5d094441d4421fbf72abcbcd357d8bf46bc107d094c0950e863fc4dc1bdcf446
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.