Buckets:

download
raw
63.6 kB
"""Comprehensive unit tests for tools/zap_integration.py. All HTTP calls, subprocess invocations, and file operations are mocked. """ import asyncio import importlib import json import sys import time from pathlib import Path from unittest.mock import AsyncMock, MagicMock, Mock, patch import aiohttp import pytest pytestmark = pytest.mark.filterwarnings("ignore:coroutine.*was never awaited:RuntimeWarning") from tools import zap_integration as zi from tools.zap_integration import ( ZAPActiveScanResult, ZAPAlert, ZAPAlertRisk, ZAPAPIClient, ZAPAuthConfig, ZAPAuthMethod, ZAPAutomationFramework, ZAPContext, ZAPContextManager, ZAPDockerManager, ZAPScanner, ZAPScanPolicy, ZAPScanResult, ZAPSessionAuth, ZAPSessionManager, ZAPSpiderResult, register_zap_tools, zap_api_scan, zap_quick_scan, zap_scan, zap_scan_url, zap_scan_with_auth, zap_spider_only, ) # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- SAMPLE_ALERT_DICT = { "alertId": "1", "name": "Suspicious Comments", "risk": "Informational", "confidence": "Medium", "description": "The response contains a suspicious comment.", "solution": "Remove comments.", "reference": "https://owasp.org/", "cweid": "200", "wascid": "13", "sourceid": "3", "url": "http://example.com/", "method": "GET", "attack": "", "evidence": "", "otherinfo": "", "param": "", "pluginId": "10010", } SAMPLE_ALERTS_RESPONSE = {"alerts": [SAMPLE_ALERT_DICT]} def _mock_cm(status=200, text="{}"): """Build an async context manager that returns a mocked aiohttp response.""" response = AsyncMock() response.status = status response.text = AsyncMock(return_value=text) cm = AsyncMock() cm.__aenter__ = AsyncMock(return_value=response) cm.__aexit__ = AsyncMock(return_value=None) return cm def _mock_session(cm=None, get_side_effect=None, post_side_effect=None): """Build a mocked aiohttp.ClientSession. session.get/post must return the async context manager directly (not a coroutine) because ``async with session.get(...)`` does not await the call expression. """ session = AsyncMock() session.closed = False session.get = MagicMock(return_value=cm) session.post = MagicMock(return_value=cm) if get_side_effect is not None: session.get.side_effect = get_side_effect if post_side_effect is not None: session.post.side_effect = post_side_effect return session def _alert(**kwargs): defaults = dict( alert_id="1", name="XSS", risk="High", confidence="High", description="desc", solution="fix", reference="", ) defaults.update(kwargs) return ZAPAlert(**defaults) def _params(call): """Extract the params dict from a positional _api_request call.""" if call[0] and len(call[0]) >= 2: return call[0][1] return call.kwargs.get("params") # --------------------------------------------------------------------------- # Enums & simple dataclasses # --------------------------------------------------------------------------- class TestEnums: """Exercise all enumeration classes.""" @pytest.mark.parametrize( "member,expected", [ (ZAPScanPolicy.DEFAULT, "Default Policy"), (ZAPScanPolicy.SQL_INJECTION, "SQL Injection"), (ZAPScanPolicy.XSS, "Cross Site Scripting (Reflected)"), (ZAPScanPolicy.DIRECTORY_BROWSING, "Directory Browsing"), (ZAPScanPolicy.CSRF, "Cross Site Request Forgery"), (ZAPScanPolicy.COMMAND_INJECTION, "Command Injection"), (ZAPScanPolicy.LDAP_INJECTION, "LDAP Injection"), (ZAPScanPolicy.XPATH_INJECTION, "XPath Injection"), (ZAPScanPolicy.XML_EXTERNAL_ENTITY, "XML External Entity Attack"), (ZAPScanPolicy.SERVER_SIDE_INCLUDE, "Server Side Include"), (ZAPScanPolicy.PATH_TRAVERSAL, "Path Traversal"), (ZAPScanPolicy.CUSTOM, "Custom Policy"), ], ) def test_scan_policy_values(self, member, expected): assert member.value == expected @pytest.mark.parametrize( "member,expected", [ (ZAPAlertRisk.INFORMATIONAL, 0), (ZAPAlertRisk.LOW, 1), (ZAPAlertRisk.MEDIUM, 2), (ZAPAlertRisk.HIGH, 3), ], ) def test_alert_risk_values(self, member, expected): assert member.value == expected @pytest.mark.parametrize( "member,expected", [ (ZAPAuthMethod.FORM_BASED, "formBasedAuthentication"), (ZAPAuthMethod.JSON_BASED, "jsonBasedAuthentication"), (ZAPAuthMethod.SCRIPT_BASED, "scriptBasedAuthentication"), (ZAPAuthMethod.HTTP, "httpAuthentication"), (ZAPAuthMethod.MANUAL, "manualAuthentication"), ], ) def test_auth_method_values(self, member, expected): assert member.value == expected @pytest.mark.parametrize( "member,expected", [ (ZAPSessionAuth.COOKIE, "cookieBasedSessionManagement"), (ZAPSessionAuth.HTTP, "httpAuthSessionManagement"), (ZAPSessionAuth.SCRIPT, "scriptBasedSessionManagement"), ], ) def test_session_auth_values(self, member, expected): assert member.value == expected class TestDataclasses: """Exercise dataclass constructors and helpers.""" def test_zap_alert_defaults(self): alert = ZAPAlert(alert_id="1", name="A", risk="Low", confidence="Medium", description="d", solution="s", reference="r") assert alert.cwe_id == "" assert alert.to_dict()["name"] == "A" def test_zap_alert_to_dict(self): alert = _alert() d = alert.to_dict() assert d["alert_id"] == "1" assert d["risk"] == "High" def test_zap_scan_result_filters(self): alerts = [ _alert(risk="High"), _alert(risk="Medium"), _alert(risk="Low"), _alert(risk="Informational"), ] result = ZAPScanResult(success=True, target="http://t", scan_type="full", alerts=alerts) assert len(result.get_high_risk()) == 1 assert len(result.get_medium_risk()) == 1 assert len(result.get_low_risk()) == 1 assert len(result.get_info_risk()) == 1 assert len(result.get_alerts_by_risk("high")) == 1 def test_zap_auth_config_form_payload(self): cfg = ZAPAuthConfig( method=ZAPAuthMethod.FORM_BASED, login_url="http://test/login", username="u", password="p", username_field="user", password_field="pass", extra_params={"remember": "true"}, ) payload = cfg.to_login_payload() data = json.loads(payload) assert data["loginUrl"] == "http://test/login" assert "user={%username%}" in data["loginRequestData"] assert "remember=true" in data["loginRequestData"] def test_zap_auth_config_json_payload(self): cfg = ZAPAuthConfig( method=ZAPAuthMethod.JSON_BASED, login_url="http://test/login", username="u", password="p", extra_params={"realm": "admin"}, ) payload = cfg.to_login_payload() outer = json.loads(payload) inner = json.loads(outer["loginRequestData"]) assert inner["realm"] == "admin" def test_zap_auth_config_http_payload(self): cfg = ZAPAuthConfig( method=ZAPAuthMethod.HTTP, login_url="http://test:8080/login", ) payload = cfg.to_login_payload() data = json.loads(payload) assert data["hostname"] == "test" assert data["port"] == 8080 def test_zap_auth_config_unknown_returns_empty(self): cfg = ZAPAuthConfig(method=ZAPAuthMethod.MANUAL) assert cfg.to_login_payload() == "" def test_zap_context_defaults(self): ctx = ZAPContext(name="ctx") assert ctx.include_regexes == [] assert ctx.exclude_regexes == [] assert ctx.session_management == ZAPSessionAuth.COOKIE def test_zap_spider_result(self): r = ZAPSpiderResult(scan_id="5", urls_found=["http://a"], progress=100, completed=True) assert r.urls_in_scope == 0 def test_zap_active_scan_result(self): r = ZAPActiveScanResult(scan_id="7", progress=50, alerts_found=3, scan_policy="XSS") assert r.completed is False # --------------------------------------------------------------------------- # ZAPAPIClient # --------------------------------------------------------------------------- class TestZAPAPIClient: """Test the low-level REST client with mocked aiohttp.""" @pytest.mark.asyncio async def test_init_and_close(self): client = ZAPAPIClient(api_url="http://zap:8080/", api_key="k") assert client.api_url == "http://zap:8080" assert client.api_key == "k" session = await client._get_session() assert session is client._session await client.close() assert session.closed @pytest.mark.asyncio async def test_request_get_json(self): client = ZAPAPIClient() cm = _mock_cm(200, '{"version":"2.12"}') client._session = _mock_session(cm) result = await client.request("core/view/version/") assert result == {"version": "2.12"} client._session.get.assert_called_once() @pytest.mark.asyncio async def test_request_post_plain_text(self): client = ZAPAPIClient(api_key="k") cm = _mock_cm(200, "OK") client._session = _mock_session(cm) result = await client.request("core/action/newSession/", {"name": "s"}, "POST") assert result == {"result": "OK"} client._session.post.assert_called_once() # api key injected call_args = client._session.post.call_args assert "apikey" in call_args.kwargs["data"] @pytest.mark.asyncio async def test_request_non_json_response(self): client = ZAPAPIClient() cm = _mock_cm(200, "not-json") client._session = _mock_session(cm) result = await client.request("foo/") assert result == {"result": "not-json"} @pytest.mark.asyncio async def test_request_error_status(self): client = ZAPAPIClient() cm = _mock_cm(500, "boom") client._session = _mock_session(cm) with pytest.raises(RuntimeError, match="ZAP API error 500"): await client.request("foo/") @pytest.mark.asyncio async def test_request_client_error(self): client = ZAPAPIClient() client._session = _mock_session() client._session.get.side_effect = aiohttp.ClientError("refused") with pytest.raises(RuntimeError, match="Failed to connect"): await client.request("foo/") @pytest.mark.asyncio async def test_core_version(self): client = ZAPAPIClient() cm = _mock_cm(200, '{"version":"2.12"}') client._session = _mock_session(cm) assert await client.core_version() == "2.12" @pytest.mark.asyncio async def test_core_status(self): client = ZAPAPIClient() cm = _mock_cm(200, '{"version":"2.12"}') client._session = _mock_session(cm) result = await client.core_status() assert result["version"] == "2.12" @pytest.mark.asyncio async def test_is_running_true(self): client = ZAPAPIClient() cm = _mock_cm(200, '{"version":"2.12"}') client._session = _mock_session(cm) assert await client.is_running() is True @pytest.mark.asyncio async def test_is_running_false(self): client = ZAPAPIClient() client._session = _mock_session() client._session.get.side_effect = aiohttp.ClientError("boom") assert await client.is_running() is False # --------------------------------------------------------------------------- # ZAPContextManager # --------------------------------------------------------------------------- class TestZAPContextManager: """Test context lifecycle and authentication configuration.""" @pytest.fixture def client(self): return ZAPAPIClient() @pytest.mark.asyncio async def test_create_context_success(self, client): cm_mock = _mock_cm(200, '{"contextId":"3"}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) ctx = ZAPContext( name="ctx1", include_regexes=["http://t/.*"], exclude_regexes=["http://t/logout"], technologies=["Db"] ) cid = await mgr.create_context(ctx) assert cid == "3" assert ctx.context_id == "3" posts = [c for c in client._session.post.call_args_list] # newContext + include + exclude + sessionManagement + tech assert len(posts) == 5 @pytest.mark.asyncio async def test_create_context_failure(self, client): cm_mock = _mock_cm(200, '{"contextId":""}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) with pytest.raises(RuntimeError, match="Failed to create context"): await mgr.create_context(ZAPContext(name="bad")) @pytest.mark.asyncio async def test_configure_auth_form(self, client): cm_mock = _mock_cm(200, '{"contextId":"3"}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) cfg = ZAPAuthConfig( method=ZAPAuthMethod.FORM_BASED, login_url="http://t/login", username="u", password="p", logged_in_indicator="Welcome", logged_out_indicator="Login", ) ctx = ZAPContext(name="ctx", auth_config=cfg) await mgr.create_context(ctx) # Auth method + logged in + logged out posts = client._session.post.call_args_list assert any("setAuthenticationMethod" in str(c) for c in posts) assert any("setLoggedInIndicator" in str(c) for c in posts) @pytest.mark.asyncio async def test_configure_auth_json(self, client): cm_mock = _mock_cm(200, '{"contextId":"3"}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) cfg = ZAPAuthConfig( method=ZAPAuthMethod.JSON_BASED, login_url="http://t/login", username="u", password="p", ) ctx = ZAPContext(name="ctx", auth_config=cfg) await mgr.create_context(ctx) posts = client._session.post.call_args_list assert any("setAuthenticationMethod" in str(c) for c in posts) @pytest.mark.asyncio async def test_configure_auth_http(self, client): cm_mock = _mock_cm(200, '{"contextId":"3"}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) cfg = ZAPAuthConfig(method=ZAPAuthMethod.HTTP, login_url="http://t:8080/login") ctx = ZAPContext(name="ctx", auth_config=cfg) await mgr.create_context(ctx) posts = client._session.post.call_args_list assert any("setAuthenticationMethod" in str(c) for c in posts) @pytest.mark.asyncio async def test_configure_auth_manual_session_cookie(self, client): cm_mock = _mock_cm(200, '{"contextId":"3"}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) cfg = ZAPAuthConfig( method=ZAPAuthMethod.MANUAL, login_url="http://t/", session_cookie_name="sessionid", session_cookie_value="abc", ) ctx = ZAPContext(name="ctx", auth_config=cfg) await mgr.create_context(ctx) posts = [str(c) for c in client._session.post.call_args_list] assert any("addSessionToken" in p for p in posts) assert any("setSessionTokenValue" in p for p in posts) @pytest.mark.asyncio async def test_remove_context(self, client): cm_mock = _mock_cm(200, "OK") client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) await mgr.remove_context("ctx") client._session.post.assert_called_once() @pytest.mark.asyncio async def test_list_contexts(self, client): cm_mock = _mock_cm(200, '{"contextList":["ctx1","ctx2"]}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) result = await mgr.list_contexts() assert result == ["ctx1", "ctx2"] @pytest.mark.asyncio async def test_get_context(self, client): cm_mock = _mock_cm(200, '{"name":"ctx1"}') client._session = _mock_session(cm_mock) mgr = ZAPContextManager(client) result = await mgr.get_context("ctx1") assert result["name"] == "ctx1" # --------------------------------------------------------------------------- # ZAPSessionManager # --------------------------------------------------------------------------- class TestZAPSessionManager: @pytest.fixture def client(self): return ZAPAPIClient() @pytest.mark.asyncio async def test_new_session(self, client): client._session = _mock_session(_mock_cm(200, '{"Result":"OK"}')) mgr = ZAPSessionManager(client) assert await mgr.new_session("sess") is True @pytest.mark.asyncio async def test_save_session(self, client): client._session = _mock_session(_mock_cm(200, "OK")) mgr = ZAPSessionManager(client) assert await mgr.save_session("sess") is True @pytest.mark.asyncio async def test_load_session(self, client): client._session = _mock_session(_mock_cm(200, "OK")) mgr = ZAPSessionManager(client) assert await mgr.load_session("sess") is True @pytest.mark.asyncio async def test_snapshot_session(self, client): client._session = _mock_session(_mock_cm(200, "OK")) mgr = ZAPSessionManager(client) assert await mgr.snapshot_session() is True @pytest.mark.asyncio async def test_clear_session(self, client): client._session = _mock_session(_mock_cm(200, "OK")) mgr = ZAPSessionManager(client) assert await mgr.clear_session() is True # --------------------------------------------------------------------------- # ZAPScanner initialization & daemon control # --------------------------------------------------------------------------- class TestZAPScannerInit: def test_defaults(self): scanner = ZAPScanner(target="http://t") assert scanner.target == "http://t" assert scanner.api_url == "http://localhost:8080" assert scanner.options["spider"] is True assert scanner.options["ajax_spider"] is False assert scanner.options["active_scan"] is True assert scanner.options["recursion_depth"] == 5 assert scanner.options["scan_timeout"] == 600 def test_custom_options(self): scanner = ZAPScanner( target="http://t", api_url="http://zap:9090/", api_key="k", zap_path="/zap", use_docker=True, options={"spider": False, "scan_policy": ZAPScanPolicy.XSS.value}, ) assert scanner.api_url == "http://zap:9090" assert scanner.api_key == "k" assert scanner.zap_path == "/zap" assert scanner.use_docker is True assert scanner.options["spider"] is False assert scanner.options["scan_policy"] == ZAPScanPolicy.XSS.value def test_lazy_api_client(self): scanner = ZAPScanner(target="http://t") assert scanner._api_client is None assert isinstance(scanner.api_client, ZAPAPIClient) assert scanner._api_client is scanner.api_client def test_lazy_context_manager(self): scanner = ZAPScanner(target="http://t") assert isinstance(scanner.context_manager, ZAPContextManager) def test_lazy_session_manager(self): scanner = ZAPScanner(target="http://t") assert isinstance(scanner.session_manager, ZAPSessionManager) class TestZAPScannerDaemon: """Test local/docker daemon startup / shutdown helpers.""" @pytest.mark.asyncio async def test_check_zap_installed_local(self): scanner = ZAPScanner(target="http://t", zap_path="zap") with patch("shutil.which", return_value="/usr/bin/zap") as which: assert scanner._check_zap_installed() is True which.assert_called_with("zap") @pytest.mark.asyncio async def test_check_zap_installed_docker(self): scanner = ZAPScanner(target="http://t", use_docker=True) with patch("shutil.which", return_value="/usr/bin/docker") as which: assert scanner._check_zap_installed() is True which.assert_called_with("docker") @pytest.mark.asyncio async def test_start_daemon_missing_zap(self): scanner = ZAPScanner(target="http://t") with patch("shutil.which", return_value=None): with pytest.raises(RuntimeError, match="ZAP not found"): await scanner.start_daemon() @pytest.mark.asyncio async def test_start_local_daemon(self): scanner = ZAPScanner(target="http://t", api_key="k") proc = MagicMock() with ( patch("shutil.which", return_value="/zap"), patch("subprocess.Popen", return_value=proc) as popen, patch("asyncio.sleep", new_callable=AsyncMock), ): assert await scanner.start_daemon(port=8090, headless=True) is True popen.assert_called_once() cmd = popen.call_args[0][0] assert "-daemon" in cmd assert "8090" in cmd assert "api.key=k" in cmd @pytest.mark.asyncio async def test_start_local_daemon_not_headless(self): scanner = ZAPScanner(target="http://t") with ( patch("shutil.which", return_value="/zap"), patch("subprocess.Popen", return_value=MagicMock()), patch("asyncio.sleep", new_callable=AsyncMock), ): assert await scanner.start_daemon(port=8080, headless=False) is True @pytest.mark.asyncio async def test_start_local_daemon_exception(self): scanner = ZAPScanner(target="http://t") with ( patch("shutil.which", return_value="/zap"), patch("subprocess.Popen", side_effect=OSError("boom")), patch("asyncio.sleep", new_callable=AsyncMock), ): assert await scanner.start_daemon() is False @pytest.mark.asyncio async def test_start_docker_daemon(self): scanner = ZAPScanner(target="http://t", use_docker=True) run = MagicMock() run.returncode = 0 run.stdout.strip.return_value = "container123" with ( patch("shutil.which", return_value="/docker"), patch("subprocess.run", return_value=run) as sr, patch("asyncio.sleep", new_callable=AsyncMock), ): assert await scanner.start_daemon(port=8080) is True assert scanner._docker_container == "container123" sr.assert_called_once() cmd = sr.call_args[0][0] assert cmd[0] == "docker" assert "ghcr.io/zaproxy/zaproxy:stable" in cmd @pytest.mark.asyncio async def test_start_docker_daemon_failure(self): scanner = ZAPScanner(target="http://t", use_docker=True) run = MagicMock() run.returncode = 1 run.stderr = "no docker" with ( patch("shutil.which", return_value="/docker"), patch("subprocess.run", return_value=run), patch("asyncio.sleep", new_callable=AsyncMock), ): assert await scanner.start_daemon() is False @pytest.mark.asyncio async def test_stop_daemon(self): scanner = ZAPScanner(target="http://t") scanner._docker_container = "c1" scanner._session = AsyncMock() scanner._session.closed = False scanner._api_client = ZAPAPIClient() scanner._api_client._session = AsyncMock() scanner._api_client._session.closed = False with patch("subprocess.run") as sr: await scanner.stop_daemon() assert scanner._docker_container is None assert sr.call_count == 2 # stop + rm @pytest.mark.asyncio async def test_get_session(self): scanner = ZAPScanner(target="http://t") session = await scanner._get_session() assert session is not None second = await scanner._get_session() assert second is session # --------------------------------------------------------------------------- # ZAPScanner scan methods # --------------------------------------------------------------------------- class TestZAPScannerScanMethods: """Test spider, ajax spider, active, openapi, graphql scans.""" @pytest.mark.asyncio async def test_spider_scan_completes(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [ {"scan": "1"}, {"status": "50"}, {"results": ["http://t/1"]}, {"status": "100"}, {"results": ["http://t/1", "http://t/2"]}, ] progress = [] with patch("asyncio.sleep", new_callable=AsyncMock): result = await scanner.spider_scan(progress_callback=progress.append) assert result.completed is True assert result.progress == 100 assert len(result.urls_found) == 2 assert 50 in progress and 100 in progress @pytest.mark.asyncio async def test_spider_scan_times_out(self): scanner = ZAPScanner(target="http://t") scanner.options["scan_timeout"] = 1 with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [ {"scan": "1"}, {"status": "10"}, {"results": ["http://t/1"]}, ] with patch("asyncio.sleep", new_callable=AsyncMock): # [start, while-check-before-loop, while-check-after-sleep] with patch("time.time", side_effect=[1000.0, 1000.0, 1002.0]): result = await scanner.spider_scan() assert result.completed is False @pytest.mark.asyncio async def test_spider_scan_start_failure(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={}): with pytest.raises(RuntimeError, match="Failed to start spider"): await scanner.spider_scan() @pytest.mark.asyncio async def test_spider_scan_uses_options(self): scanner = ZAPScanner( target="http://t", options={ "context_name": "ctx", "user_agent": "Bot/1", "subtree_only": True, "max_children": 10, "recursion_depth": 3, }, ) with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [ {"scan": "1"}, {"status": "100"}, {"results": []}, ] with patch("asyncio.sleep", new_callable=AsyncMock): await scanner.spider_scan() call = api.call_args_list[0] params = _params(call) assert params["contextName"] == "ctx" assert params["userAgent"] == "Bot/1" assert params["subtreeOnly"] == "true" assert params["maxChildren"] == 10 @pytest.mark.asyncio async def test_ajax_spider_scan_completes(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [ {}, # start {"status": "running"}, {"status": "stopped"}, ] progress = [] with patch("asyncio.sleep", new_callable=AsyncMock): result = await scanner.ajax_spider_scan(progress_callback=progress.append) assert result is True assert 100 in progress @pytest.mark.asyncio async def test_ajax_spider_scan_times_out(self): scanner = ZAPScanner(target="http://t") scanner.options["ajax_timeout"] = 1 with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [ {}, {"status": "running"}, ] with patch("asyncio.sleep", new_callable=AsyncMock): with patch("time.time", side_effect=[1000.0, 1000.0, 1002.0]): result = await scanner.ajax_spider_scan() assert result is False @pytest.mark.asyncio async def test_active_scan_completes(self): scanner = ZAPScanner(target="http://t") alert = ZAPAlert(alert_id="1", name="A", risk="High", confidence="High", description="d", solution="s", reference="") with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[alert]), ): api.side_effect = [ {"scan": "2"}, {"status": "100"}, ] progress = [] with patch("asyncio.sleep", new_callable=AsyncMock): result = await scanner.active_scan(progress_callback=progress.append) assert result.completed is True assert result.progress == 100 assert result.alerts_found == 1 assert 100 in progress @pytest.mark.asyncio async def test_active_scan_with_context(self): scanner = ZAPScanner(target="http://t", options={"context_name": "ctx"}) with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[]), ): api.side_effect = [ {"contextList": ["ctx"]}, {"scan": "3"}, {"status": "100"}, ] with patch("asyncio.sleep", new_callable=AsyncMock): await scanner.active_scan() # contextList lookup + scan start + status assert api.call_count == 3 @pytest.mark.asyncio async def test_active_scan_start_failure(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={}): with pytest.raises(RuntimeError, match="Failed to start active scan"): await scanner.active_scan() @pytest.mark.asyncio async def test_active_scan_times_out(self): scanner = ZAPScanner(target="http://t") scanner.options["active_scan_timeout"] = 1 with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [ {"scan": "4"}, {"status": "10"}, ] with patch("asyncio.sleep", new_callable=AsyncMock): with patch("time.time", side_effect=[1000.0, 1000.0, 1002.0]): result = await scanner.active_scan() assert result.completed is False @pytest.mark.asyncio async def test_openapi_scan(self): scanner = ZAPScanner(target="http://t") with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "spider_scan", new_callable=AsyncMock) as spider, ): spider.return_value = ZAPSpiderResult(scan_id="s", urls_found=["http://t/a"], completed=True) api.return_value = {"result": "OK"} result = await scanner.openapi_scan("http://t/openapi.json") api.assert_called_once() spider.assert_called_once() assert result.completed is True @pytest.mark.asyncio async def test_graphql_scan(self): scanner = ZAPScanner(target="http://t") with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "spider_scan", new_callable=AsyncMock) as spider, ): spider.return_value = ZAPSpiderResult(scan_id="g", urls_found=[], completed=True) api.return_value = {"result": "OK"} result = await scanner.graphql_scan("http://t/graphql", schema_url="http://t/schema") api.assert_called_once() spider.assert_called_once() assert result.completed is True # --------------------------------------------------------------------------- # Alerts # --------------------------------------------------------------------------- class TestZAPScannerAlerts: @pytest.mark.asyncio async def test_get_alerts(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value=SAMPLE_ALERTS_RESPONSE) as api: alerts = await scanner.get_alerts() assert len(alerts) == 1 assert alerts[0].name == "Suspicious Comments" api.assert_called_once_with("core/view/alerts/", {}) @pytest.mark.asyncio async def test_get_alerts_with_base_url(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value=SAMPLE_ALERTS_RESPONSE) as api: alerts = await scanner.get_alerts(base_url="http://t/") assert len(alerts) == 1 call = api.call_args params = _params(call) assert params["baseurl"] == "http://t/" @pytest.mark.asyncio async def test_get_alerts_with_risk_filter(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value=SAMPLE_ALERTS_RESPONSE) as api: alerts = await scanner.get_alerts(risk="High") assert len(alerts) == 1 call = api.call_args params = _params(call) assert params["riskId"] == str(ZAPAlertRisk.HIGH.value) @pytest.mark.asyncio async def test_get_alerts_empty(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={"alerts": []}): alerts = await scanner.get_alerts() assert alerts == [] @pytest.mark.asyncio async def test_get_alert_by_id(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[_alert(alert_id="42")]): found = await scanner.get_alerts_by_id("42") assert found is not None assert found.alert_id == "42" missing = await scanner.get_alerts_by_id("99") assert missing is None @pytest.mark.asyncio async def test_delete_alert(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={"Result": "OK"}) as api: assert await scanner.delete_alert("1") is True api.assert_called_once_with("core/action/deleteAlert/", {"id": "1"}, "POST") @pytest.mark.asyncio async def test_delete_all_alerts(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value="OK") as api: assert await scanner.delete_all_alerts() is True api.assert_called_once_with("core/action/deleteAllAlerts/", method="POST") # --------------------------------------------------------------------------- # Full scan orchestration # --------------------------------------------------------------------------- class TestZAPScannerFullScan: @pytest.mark.asyncio async def test_scan_full_success(self): scanner = ZAPScanner(target="http://t") alert = _alert(risk="Medium") calls = [ # spider start {"scan": "1"}, # spider status 100 {"status": "100"}, # spider results {"results": ["http://t/1"]}, # active start {"scan": "2"}, # active status 100 {"status": "100"}, # get_alerts inside active_scan SAMPLE_ALERTS_RESPONSE, # get_alerts at end SAMPLE_ALERTS_RESPONSE, # core/view/urls {"urls": ["http://t/1", "http://t/2"]}, ] progress = [] scanner.options["progress_callback"] = progress.append with ( patch.object(scanner, "_api_request", new_callable=AsyncMock, side_effect=calls), patch("asyncio.sleep", new_callable=AsyncMock), ): result = await scanner.scan() assert result.success is True assert result.target == "http://t" assert result.scan_type == "full" assert result.auth_success is False assert result.urls_crawled == 2 assert any("spider" in p for p in progress) assert any("active_scan" in p for p in progress) @pytest.mark.asyncio async def test_scan_with_auth_config(self): scanner = ZAPScanner(target="http://t", options={"context_name": None}) auth = ZAPAuthConfig( method=ZAPAuthMethod.FORM_BASED, login_url="http://t/login", username="u", password="p", ) with ( patch.object(ZAPContextManager, "create_context", new_callable=AsyncMock, return_value="5") as create_ctx, patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch("asyncio.sleep", new_callable=AsyncMock), ): api.side_effect = [ # spider {"scan": "1"}, {"status": "100"}, {"results": []}, # active scan looks up context {"contextList": ["auth_context_1780784513"]}, {"scan": "2"}, {"status": "100"}, {"alerts": []}, {"alerts": []}, {"urls": []}, ] result = await scanner.scan(auth_config=auth) assert result.success is True assert result.auth_success is True create_ctx.assert_awaited_once() @pytest.mark.asyncio async def test_scan_options_variations(self): scanner = ZAPScanner( target="http://t", options={"spider": False, "active_scan": False, "ajax_spider": True}, ) with ( patch.object(scanner, "ajax_spider_scan", new_callable=AsyncMock, return_value=True) as ajax, patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={"alerts": [], "urls": []}), ): result = await scanner.scan() assert result.success is True ajax.assert_awaited_once() @pytest.mark.asyncio async def test_scan_error_handling(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, side_effect=RuntimeError("boom")): result = await scanner.scan() assert result.success is False assert "boom" in result.error assert result.end_time is not None # --------------------------------------------------------------------------- # Output parsing & normalization # --------------------------------------------------------------------------- class TestZAPScannerParsing: def test_parse_output(self): scanner = ZAPScanner(target="http://t") alert = _alert( name="XSS", risk="High", description="desc", solution="fix", reference="https://owasp.org/xss https://cwe.mitre.org/79", url="http://t/u", method="GET", param="q", attack="<script>", evidence="<script>", cwe_id="79", wasc_id="8", plugin_id="40012", ) findings = scanner.parse_output([alert]) assert len(findings) == 1 f = findings[0] assert f["tool"] == "zap" assert f["severity"] == "high" assert f["cwe_id"] == "79" assert f["evidence"]["url"] == "http://t/u" assert "https://owasp.org/xss" in f["references"] def test_parse_output_no_http_reference(self): scanner = ZAPScanner(target="http://t") alert = _alert(reference="see docs", name="A", risk="Low") findings = scanner.parse_output([alert]) assert findings[0]["references"] == ["see docs"] def test_normalize_findings(self): scanner = ZAPScanner(target="http://t") findings = [ { "tool": "zap", "name": "SQLi", "severity": "high", "confidence": "high", "description": "d", "evidence": {"url": "http://t"}, "solution": "s", "references": ["ref"], "cwe_id": "89", "wasc_id": "19", "plugin_id": "40014", } ] normalized = scanner.normalize_findings(findings) assert normalized[0]["tool"] == "owasp_zap" assert normalized[0]["target"] == "http://t" assert normalized[0]["severity"] == "high" assert normalized[0]["title"] == "SQLi" def test_normalize_findings_unknown_severity(self): scanner = ZAPScanner(target="http://t") out = scanner.normalize_findings([{"severity": "weird"}]) assert out[0]["severity"] == "info" def test_risk_to_severity(self): scanner = ZAPScanner(target="http://t") assert scanner._risk_to_severity("High") == "high" assert scanner._risk_to_severity("Medium") == "medium" assert scanner._risk_to_severity("Low") == "low" assert scanner._risk_to_severity("Informational") == "info" assert scanner._risk_to_severity("Unknown") == "info" def test_parse_references(self): scanner = ZAPScanner(target="http://t") assert scanner._parse_references("") == [] assert scanner._parse_references("https://a") == ["https://a"] refs = scanner._parse_references("https://a https://b") assert "https://a" in refs refs2 = scanner._parse_references("https://a\nhttps://b") assert len(refs2) == 2 # --------------------------------------------------------------------------- # Report generation # --------------------------------------------------------------------------- class TestZAPScannerReporting: @pytest.mark.asyncio async def test_generate_report_json(self): scanner = ZAPScanner(target="http://t") with patch.object( scanner, "_api_request", new_callable=AsyncMock, return_value={"generate": "/path/report.json"} ) as api: result = await scanner.generate_report("json") assert result == "/path/report.json" params = _params(api.call_args) assert params["template"] == "traditional-json" @pytest.mark.asyncio async def test_generate_report_html_with_theme(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={"generate": "/report.html"}) as api: result = await scanner.generate_report("html", output_path="/tmp/r", theme="dark") params = _params(api.call_args) assert params["template"] == "traditional-html" assert params["theme"] == "dark" assert params["reportFileName"] == "/tmp/r" @pytest.mark.asyncio async def test_generate_report_sarif_returns_json_string(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[_alert(plugin_id="123", cwe_id="79")]): result = await scanner.generate_report("sarif") data = json.loads(result) assert data["version"] == "2.1.0" assert len(data["runs"][0]["results"]) == 1 @pytest.mark.asyncio async def test_generate_report_sarif_writes_file(self, tmp_path): scanner = ZAPScanner(target="http://t") out = tmp_path / "out.sarif" with patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[_alert(plugin_id="123")]): result = await scanner.generate_report("sarif", output_path=str(out)) assert result == str(out) assert out.exists() data = json.loads(out.read_text()) assert data["runs"][0]["results"][0]["ruleId"] == "ZAP-123" @pytest.mark.asyncio async def test_get_report_json(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[_alert(risk="High")]): report = await scanner.get_report("json") assert report["target"] == "http://t" assert report["summary"]["total"] == 1 assert report["summary"]["high"] == 1 @pytest.mark.asyncio async def test_get_report_sarif(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[_alert(risk="Medium", plugin_id="1")]): report = await scanner.get_report("sarif") assert report["version"] == "2.1.0" def test_zap_to_sarif_level(self): scanner = ZAPScanner(target="http://t") assert scanner._zap_to_sarif_level("High") == "error" assert scanner._zap_to_sarif_level("Medium") == "warning" assert scanner._zap_to_sarif_level("Low") == "note" assert scanner._zap_to_sarif_level("Informational") == "note" assert scanner._zap_to_sarif_level("Unknown") == "none" # --------------------------------------------------------------------------- # get_version # --------------------------------------------------------------------------- class TestZAPScannerVersion: def test_get_version_success(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, return_value={"version": "2.12"}): assert scanner.get_version() == "2.12" def test_get_version_failure(self): scanner = ZAPScanner(target="http://t") with patch.object(scanner, "_api_request", new_callable=AsyncMock, side_effect=RuntimeError("boom")): assert scanner.get_version() == "unknown" # --------------------------------------------------------------------------- # ZAPDockerManager # --------------------------------------------------------------------------- class TestZAPDockerManager: @pytest.mark.asyncio async def test_start_container(self): mgr = ZAPDockerManager() run = MagicMock() run.returncode = 0 run.stdout.strip.return_value = "cid123" with patch("subprocess.run", return_value=run) as sr, patch("asyncio.sleep", new_callable=AsyncMock): cid = await mgr.start_container("zap1", port=8080, api_key="k", network="net", volumes=["/host:/zap"]) assert cid == "cid123" assert mgr.containers["zap1"] == "cid123" cmd = sr.call_args[0][0] assert "docker" in cmd assert "--network" in cmd and "net" in cmd assert "-v" in cmd assert "api.key=k" in cmd @pytest.mark.asyncio async def test_start_container_failure(self): mgr = ZAPDockerManager() run = MagicMock() run.returncode = 1 run.stderr = "err" with patch("subprocess.run", return_value=run): with pytest.raises(RuntimeError, match="Failed to start container"): await mgr.start_container("zap1") @pytest.mark.asyncio async def test_stop_container(self): mgr = ZAPDockerManager() mgr.containers["zap1"] = "cid123" run = MagicMock() run.returncode = 0 with patch("subprocess.run", return_value=run) as sr: result = await mgr.stop_container("zap1") assert result is True assert "zap1" not in mgr.containers assert sr.call_count == 2 # stop + rm @pytest.mark.asyncio async def test_stop_container_failure(self): mgr = ZAPDockerManager() run = MagicMock() run.returncode = 1 with patch("subprocess.run", return_value=run): result = await mgr.stop_container("zap1") assert result is False @pytest.mark.asyncio async def test_stop_all(self): mgr = ZAPDockerManager() mgr.containers["a"] = "1" mgr.containers["b"] = "2" run = MagicMock() run.returncode = 0 with patch("subprocess.run", return_value=run): await mgr.stop_all() assert mgr.containers == {} def test_is_running_true(self): mgr = ZAPDockerManager() run = MagicMock() run.returncode = 0 run.stdout.strip.return_value = "abc" with patch("subprocess.run", return_value=run): assert mgr.is_running("zap1") is True def test_is_running_false(self): mgr = ZAPDockerManager() run = MagicMock() run.returncode = 0 run.stdout.strip.return_value = "" with patch("subprocess.run", return_value=run): assert mgr.is_running("zap1") is False # --------------------------------------------------------------------------- # ZAPAutomationFramework # --------------------------------------------------------------------------- class TestZAPAutomationFramework: @pytest.fixture def client(self): return ZAPAPIClient() @pytest.mark.asyncio async def test_run_automation_plan(self, client): fw = ZAPAutomationFramework(client) client._session = _mock_session() # runPlan is POST; planProgress is GET client._session.post.side_effect = [_mock_cm(200, '{"Result":"OK"}')] client._session.get.side_effect = [_mock_cm(200, '{"finished":true}')] progress = [] plan = {"env": {"contexts": []}, "jobs": []} with patch("asyncio.sleep", new_callable=AsyncMock), patch("os.unlink") as unlink: result = await fw.run_automation_plan(plan, progress_callback=progress.append) assert result == {"Result": "OK"} assert any(p.get("finished") for p in progress) unlink.assert_called_once() @pytest.mark.asyncio async def test_run_automation_plan_no_callback(self, client): fw = ZAPAutomationFramework(client) client._session = _mock_session() client._session.post.side_effect = [_mock_cm(200, '{"Result":"OK"}')] client._session.get.side_effect = [_mock_cm(200, '{"finished":true}')] with patch("asyncio.sleep", new_callable=AsyncMock), patch("os.unlink"): result = await fw.run_automation_plan({"env": {"contexts": []}, "jobs": []}) assert result == {"Result": "OK"} def test_create_plan_template_default(self): client = ZAPAPIClient() fw = ZAPAutomationFramework(client) plan = fw.create_plan_template("http://t") assert plan["env"]["contexts"][0]["name"] == "Default Context" types = [j["type"] for j in plan["jobs"]] assert "spider" in types assert "activeScan" in types assert "report" in types def test_create_plan_template_no_spider(self): client = ZAPAPIClient() fw = ZAPAutomationFramework(client) plan = fw.create_plan_template("http://t", spider=False, report_formats=["html", "json"]) types = [j["type"] for j in plan["jobs"]] assert "spider" not in types assert types.count("report") == 2 # --------------------------------------------------------------------------- # LangChain / tool wrappers # --------------------------------------------------------------------------- class TestLangChainTools: def test_zap_scan_url_success(self): mock_result = MagicMock() mock_result.success = True mock_result.target = "http://t" mock_result.scan_time = 1.5 mock_result.urls_crawled = 10 mock_result.alerts = [_alert(risk="High"), _alert(risk="Medium")] with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_scan_url("http://t") assert "OWASP ZAP Scan completed" in result assert "High Risk Findings" in result def test_zap_scan_url_failure(self): mock_result = MagicMock() mock_result.success = False mock_result.error = "boom" with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_scan_url("http://t") assert "failed" in result assert "boom" in result def test_zap_quick_scan(self): mock_result = MagicMock() mock_result.success = True mock_result.alerts = [_alert(risk="High"), _alert(risk="Low")] with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_quick_scan("http://t") assert "High: 1" in result assert "Total Alerts: 2" in result def test_zap_spider_only(self): mock_result = MagicMock() mock_result.success = True mock_result.urls_crawled = 42 with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_spider_only("http://t") assert "42 URLs" in result def test_zap_scan_with_auth(self): mock_result = MagicMock() mock_result.success = True mock_result.scan_time = 5.0 mock_result.auth_success = True mock_result.alerts = [_alert(risk="High")] mock_result.get_high_risk.return_value = [_alert(risk="High")] mock_result.get_medium_risk.return_value = [] mock_result.get_low_risk.return_value = [] with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_scan_with_auth("http://t", "http://t/login", "u", "p") assert "Auth Success: True" in result def test_zap_api_scan(self): spider = MagicMock() spider.urls_found = ["http://t/a"] spider.completed = True with patch("tools.zap_integration.asyncio.run", return_value=spider): result = zap_api_scan("http://t", "http://t/openapi.json") assert "API Scan completed" in result def test_zap_scan_alias(self): assert zap_scan is zap_scan_url def test_register_zap_tools_when_not_available(self): with patch.object(zi, "TOOL_REGISTRY_AVAILABLE", False), patch.object(zi, "LANGCHAIN_AVAILABLE", False): # should silently return assert register_zap_tools() is None def test_register_zap_tools_success(self): mock_registry = MagicMock() with ( patch.object(zi, "TOOL_REGISTRY_AVAILABLE", True), patch.object(zi, "LANGCHAIN_AVAILABLE", True), patch.object(zi, "registry", mock_registry, create=True), ): register_zap_tools() assert mock_registry.register.call_count == 5 def test_register_zap_tools_exception_handling(self): mock_registry = MagicMock() mock_registry.register.side_effect = RuntimeError("nope") with ( patch.object(zi, "TOOL_REGISTRY_AVAILABLE", True), patch.object(zi, "LANGCHAIN_AVAILABLE", True), patch.object(zi, "registry", mock_registry, create=True), ): # should not raise register_zap_tools() def test_module_auto_register_except_branch(self): with patch.object(zi, "register_zap_tools", side_effect=RuntimeError("auto fail")): importlib.reload(zi) # restore normal module state for remaining tests importlib.reload(zi) def test_langchain_available_flag(self): # The flag reflects whether langchain_core.tools was importable at module load time. # Other tests may inject langchain_core into sys.modules, so assert only that the # attribute exists and is a bool. assert isinstance(zi.LANGCHAIN_AVAILABLE, bool) def test_tool_decorator_fallback_identity(self): # The fallback @tool decorator returns the function unchanged. @zi.tool def sample(): """doc""" return 1 assert sample() == 1 assert sample.__doc__ == "doc" def test_tool_decorator_with_kwargs(self): @zi.tool(response_format="content") def sample2(): return 2 assert sample2() == 2 # --------------------------------------------------------------------------- # Extra coverage for previously-missed branches # --------------------------------------------------------------------------- class TestMissingBranches: """Small targeted tests to push coverage higher.""" @pytest.mark.asyncio async def test_ajax_spider_scan_uses_options(self): scanner = ZAPScanner( target="http://t", options={ "context_name": "ctx", "user_agent": "Bot/1", "subtree_only": True, }, ) with patch.object(scanner, "_api_request", new_callable=AsyncMock) as api: api.side_effect = [{}, {"status": "stopped"}] with patch("asyncio.sleep", new_callable=AsyncMock): await scanner.ajax_spider_scan() params = _params(api.call_args_list[0]) assert params["contextName"] == "ctx" assert params["userAgent"] == "Bot/1" assert params["subtreeOnly"] == "true" @pytest.mark.asyncio async def test_active_scan_user_id_and_options_context(self): scanner = ZAPScanner(target="http://t", options={"context_name": "ctx"}) with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=[]), ): api.side_effect = [ {"contextList": []}, {"scan": "9"}, {"status": "100"}, ] with patch("asyncio.sleep", new_callable=AsyncMock): await scanner.active_scan(user_id="42") scan_call = api.call_args_list[1] params = _params(scan_call) assert params["userId"] == "42" @pytest.mark.asyncio async def test_openapi_scan_options(self): scanner = ZAPScanner(target="http://t", options={"context_name": "ctx"}) with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "spider_scan", new_callable=AsyncMock), ): api.return_value = {"result": "OK"} await scanner.openapi_scan("http://t/openapi.json") params = _params(api.call_args) assert params["targetUrl"] == "http://t" assert params["contextName"] == "ctx" @pytest.mark.asyncio async def test_graphql_scan_schema_and_options(self): scanner = ZAPScanner(target="http://t", options={"context_name": "ctx"}) with ( patch.object(scanner, "_api_request", new_callable=AsyncMock) as api, patch.object(scanner, "spider_scan", new_callable=AsyncMock), ): api.return_value = {"result": "OK"} await scanner.graphql_scan("http://t/gql", schema_url="http://t/sdl") params = _params(api.call_args) assert params["schemaUrl"] == "http://t/sdl" assert params["contextName"] == "ctx" @pytest.mark.asyncio async def test_generate_sarif_duplicate_rule(self): scanner = ZAPScanner(target="http://t") alerts = [ _alert(plugin_id="1", cwe_id="79", risk="High"), _alert(plugin_id="1", cwe_id="79", risk="High"), ] with patch.object(scanner, "get_alerts", new_callable=AsyncMock, return_value=alerts): result = await scanner.generate_report("sarif") data = json.loads(result) assert len(data["runs"][0]["tool"]["driver"]["rules"]) == 1 assert len(data["runs"][0]["results"]) == 2 @pytest.mark.asyncio async def test_docker_stop_container_success_not_tracked(self): mgr = ZAPDockerManager() run = MagicMock() run.returncode = 0 with patch("subprocess.run", return_value=run): result = await mgr.stop_container("unknown") assert result is True assert "unknown" not in mgr.containers @pytest.mark.asyncio async def test_automation_plan_progress_sleep(self): client = ZAPAPIClient() fw = ZAPAutomationFramework(client) client._session = _mock_session() client._session.post.side_effect = [_mock_cm(200, '{"Result":"OK"}')] client._session.get.side_effect = [ _mock_cm(200, '{"finished":false}'), _mock_cm(200, '{"finished":true}'), ] with patch("asyncio.sleep", new_callable=AsyncMock) as sleep, patch("os.unlink"): await fw.run_automation_plan({"env": {"contexts": []}, "jobs": []}, progress_callback=lambda s: None) sleep.assert_awaited_once() def test_create_plan_template_no_active_scan(self): fw = ZAPAutomationFramework(ZAPAPIClient()) plan = fw.create_plan_template("http://t", active_scan=False) types = [j["type"] for j in plan["jobs"]] assert "activeScan" not in types def test_zap_quick_scan_failure(self): mock_result = MagicMock() mock_result.success = False mock_result.error = "connection failed" with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_quick_scan("http://t") assert "failed" in result assert "connection failed" in result def test_zap_spider_only_failure(self): mock_result = MagicMock() mock_result.success = False mock_result.error = "boom" with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_spider_only("http://t") assert "failed" in result assert "boom" in result def test_zap_scan_with_auth_failure(self): mock_result = MagicMock() mock_result.success = False mock_result.error = "auth failed" with patch("tools.zap_integration.asyncio.run", return_value=mock_result): result = zap_scan_with_auth("http://t", "http://t/login", "u", "p") assert "failed" in result assert "auth failed" in result
"""Comprehensive unit tests for tools/zap_integration.py.
All HTTP calls, subprocess invocations, and file operations are mocked.
"""
import asyncio
import importlib
import json
import sys
import time
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import aiohttp
import pytest
pytestmark = pytest.mark.filterwarnings("ignore:coroutine.*was never awaited:RuntimeWarning")
from tools import zap_integration as zi
from tools.zap_integration import (
ZAPActiveScanResult,
ZAPAlert,
ZAPAlertRisk,
ZAPAPIClient,
ZAPAuthConfig,
ZAPAuthMethod,
ZAPAutomationFramework,
ZAPContext,
ZAPContextManager,
ZAPDockerManager,
ZAPScanner,
ZAPScanPolicy,
ZAPScanResult,
ZAPSessionAuth,
ZAPSessionManager,
ZAPSpiderResult,
register_zap_tools,
zap_api_scan,
zap_quick_scan,
zap_scan,
zap_scan_url,
zap_scan_with_auth,
zap_spider_only,
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
SAMPLE_ALERT_DICT = {
"alertId": "1",
"name": "Suspicious Comments",
"risk": "Informational",
"confidence": "Medium",
"description": "The response contains a suspicious comment.",
"solution": "Remove comments.",
"reference": "https://owasp.org/",
"cweid": "200",
"wascid": "13",
"sourceid": "3",
"url": "http://example.com/",
"method": "GET",
"attack": "",
"evidence": "",
"otherinfo": "",
"param": "",
"pluginId": "10010",
}
SAMPLE_ALERTS_RESPONSE = {"alerts": [SAMPLE_ALERT_DICT]}
def _mock_cm(status=200, text="{}"):
"""Build an async context manager that returns a mocked aiohttp response."""
response = AsyncMock()
response.status = status
response.text = AsyncMock(return_value=text)
cm = AsyncMock()
cm.__aenter__ = AsyncMock(return_value=response)
cm.__aexit__ = AsyncMock(return_value=None)
return cm
def _mock_session(cm=None, get_side_effect=None, post_side_effect=None):
"""Build a mocked aiohttp.ClientSession.
session.get/post must return the async context manager directly
(not a coroutine) because ``async with session.get(...)`` does not
await the call expression.
"""
session = AsyncMock()
session.closed = False
session.get = MagicMock(return_value=cm)
session.post = MagicMock(return_value=cm)
if get_side_effect is not None:
session.get.side_effect = get_side_effect
if post_side_effect is not None:
session.post.side_effect = post_side_effect
return session

Xet Storage Details

Size:
63.6 kB
·
Xet hash:
d0945441f65a15d34b7fd4dd12bbc51245c271b04a4413ab3440fc99d29d5e10

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.