Skip to content

test: expand pytest coverage from 58.6% to 67% - #11

Merged
SALhik merged 12 commits into
mainfrom
coverage/pytest-expansion-2026-06-01
Jun 8, 2026
Merged

SALhik merged 12 commits into
mainfrom
coverage/pytest-expansion-2026-06-01

Conversation

@SALhik

@SALhik SALhik commented Jun 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

Systematic pytest coverage expansion across 12 tasks in 5 phases, adding 1,298 new tests across 17 new test files (+1 conftest fix). Overall coverage rises from 58.6% → 67% (4,400 lines recovered).

  • Phase 0: Created tests/testing/ directory
  • Phase 1: ConfigValidator characterization tests (71 tests, 79% module coverage)
  • Phase 2: Stealth + detection resistance orchestrator integration tests (88 tests, 68-70% coverage)
  • Phase 3: Agent, detection resistance, effectiveness, monitoring, knowledge, and network deep tests (1,053 tests across 10 files)
  • Phase 4: Automation testing framework + security validation suite (154 tests, 83-91% coverage)
  • Phase 5: Fixed alert_correlation_engine conftest fixture (Mock(spec=...) missing instance attribute recent_events, leaked daemon threads)

Key stats

Metric Before After
Total tests 3,746 5,044
Overall coverage 58.6% 67%
Missing statements 22,448 18,048
Lines recovered — ~4,400

Modules covered

Module Tests Coverage
config_validation.py 71 79%
stealth_orchestrator_integration.py 41 68%
detection_resistance_orchestrator_integration.py 47 70%
network_operations_agent.py 98 76%
stealth_operations_agent.py 81 74%
ai_ml_resistance.py + edr_evasion.py 241 deep
success_rate_analytics.py 133 95%
security_event_analyzer.py + response_controller.py 183 deep
intelligence_feed_integrator.py 127 71%
segmentation_traversal.py + protocol_evasion.py 190 92%
automation_testing_framework.py 73 83%
security_validation_suite.py 81 91%

Bug fix (Task 12)

The alert_correlation_engine fixture in tests/conftest.py used Mock(spec=DetectionMonitor), but recent_events is an instance attribute (set in __init__), not a class attribute — so the mock didn't expose it. Any test calling start_correlation() leaked a daemon thread spamming AttributeError every 5 seconds. Fixed by explicitly setting monitor.recent_events = deque(maxlen=10000) and adding yield + stop_correlation() teardown.

Test plan

  • ./venv/bin/pytest tests/ -x -q --timeout=120 — 5,044 passed, 9 skipped, 0 failures
  • ./venv/bin/ruff check . — clean
  • ./venv/bin/mypy . — 72 errors all in test files (mock type annotations), 0 in production code
  • No production code modified (except conftest fixture fix)
  • All tests use tmp_path / :memory: DBs, no thread leaks

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Tests
    • Expanded end-to-end and deep unit test coverage across agents, monitoring/response, network traversal/evasion, detection-resistance, effectiveness analytics, intelligence feeds, security validation, and automation to improve reliability.
  • Bug Fixes
    • Improved threat feed parsing to handle varied indicator formats robustly.
    • Toned evasion-intensity responses so alerts only increase intensity for medium/high severities.

SALhik and others added 8 commits June 1, 2026 16:57
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
71 tests covering ConfigValidationError, ConfigValidator methods,
validate_config_file, and edge paths. 79% coverage on config_validation.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ests

Task 2: 41 tests, 68% coverage on stealth_orchestrator_integration.py
Task 3: 47 tests, 70% coverage on detection_resistance_orchestrator_integration.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Task 4: 98 tests, 76% coverage on network_operations_agent.py
Task 5: 81 tests, 74% coverage on stealth_operations_agent.py
Both avoid .start() to prevent thread leaks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ests

Task 6: 241 tests for ai_ml_resistance.py + edr_evasion.py
Task 7: 133 tests, 95% coverage on success_rate_analytics.py
Task 8: 183 tests for security_event_analyzer.py + response_controller.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…tests

Task 9: 127 tests, 71% coverage on intelligence_feed_integrator.py
Task 10: 190 tests, 92% coverage on segmentation_traversal.py + protocol_evasion.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Task 11: 154 tests total
- automation_testing_framework.py: 83% coverage (73 tests)
- security_validation_suite.py: 91% coverage (81 tests)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…p() teardown

Task 12: Fix Mock(spec=DetectionMonitor) missing instance attribute
recent_events. Add yield + stop_correlation() teardown to prevent
leaked daemon threads. Regression test confirms the fix.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@SALhik, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 52 minutes and 48 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7aee1966-b569-4c94-9da5-6c7e47ea7809

📥 Commits

Reviewing files that changed from the base of the PR and between 2d9c416 and adf4b79.

📒 Files selected for processing (3)
  • .coveragerc
  • pyproject.toml
  • tests/conftest.py
📝 Walkthrough

Walkthrough

Adds ~11,000 lines of tests across many subsystems (agents, detection resistance, monitoring, network, effectiveness, testing frameworks, and orchestrator integrations). Updates alert_correlation_engine fixture and two small production behaviors in intelligence_feed_integrator and protocol_evasion.

Changes

Test Suite Expansion

Layer / File(s) Summary
Test fixture updates
tests/conftest.py
alert_correlation_engine fixture now yields an AlertCorrelationEngine built with a mocked DetectionMonitor exposing a deque recent_events buffer and calls stop_correlation() on teardown.
Agent test coverage
tests/agents/test_network_operations_agent.py, tests/agents/test_stealth_operations_agent.py
Comprehensive tests for NetworkOperationsAgent and StealthOperationsAgent covering enums/dataclasses, init state, public operation creation, internal execution threads, helper/simulation methods, monitoring/metrics, topology-change detection, lifecycle (stop() when not started), and operation-history trimming.
Detection resistance subsystems
tests/detection_resistance/*
Deep characterization tests for AI/ML resistance and EDR evasion components (analyzers, generators, manipulators, evaders) validating enabled/disabled modes, strategy generation, scoring, and orchestration.
Monitoring infrastructure
tests/monitoring/*
Regression and unit tests for alert correlation (thread leaks, fixture), ResponseController (rules, plan creation/execution/lifecycle), and SecurityEventLogAnalyzer (parsers, patterns, anomaly detection, batch reports).
Network operations
tests/network/*
Protocol evasion and segmentation traversal deep tests: payload encoding, XOR encryption helpers, header obfuscation, evasion/timing strategies, traffic mimicry, covert channels, discovery/firewall evasion/lateral movement engines, and orchestrator-level flows.
Effectiveness & intelligence
tests/effectiveness/*, tests/knowledge/*
SuccessRateAnalytics tests for attack/result tracking, factor analysis, false-positive detection, benchmarking, reporting; IntelligenceFeedIntegrator tests for feed processing, IOC extraction, async handling, and rate limiting.
Testing frameworks
tests/testing/*
Automation testing framework tests for test-case generation strategies, coverage analysis, bug detection, scheduling, and orchestrator pipeline execution.
Configuration & integrations
tests/utils/* and production changes pentestgpt/knowledge/intelligence_feed_integrator.py, pentestgpt/network/protocol_evasion.py
Config validation tests (error formatting, key/path/URL checks, file parsing). Small production changes: normalize indicators types in threat feed processing; only increase evasion intensity on medium/high detection alerts in ProtocolEvasionManager.handle_network_event.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • SALhik/AutoPentester#10: Overlaps NetworkOperationsAgent lifecycle/stop and scan-processor behavior covered by the new network agent tests.
  • SALhik/AutoPentester#2: Related to StealthOperationsAgent behaviors (evidence path handling, operation IDs, evasion execution) targeted by the new stealth tests.

Poem

🐰 I stitched new tests through day and night,
Assertions snug and confidence light.
Agents, nets, resistors—each one checked,
Fixtures tamed, small fixes decked.
Hopping off now—CI green in sight!

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch coverage/pytest-expansion-2026-06-01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
tests/agents/test_stealth_operations_agent.py (1)

33-1069: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add @pytest.mark.unit markers to all test classes.

The coding guidelines require pytest markers based on test directory. Since this file is in tests/agents/, all test classes must be decorated with @pytest.mark.unit.

📝 Proposed fix to add pytest markers
+@pytest.mark.unit
 class TestEnums:
     def test_stealth_operation_type_values(self):

...

+@pytest.mark.unit
 class TestDataclasses:
     def test_opsec_plan(self):

...

+@pytest.mark.unit
 class TestStealthOperationsAgentInit:
     def test_init(self):

...

+@pytest.mark.unit
 class TestCreateOpsecPlan:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestExecuteStealthOperation:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestOperationThreadMethods:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestEvidenceManagement:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestStealthStatusAndMetrics:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestUpdateRiskProfile:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestInternalMethods:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestScheduledCleanups:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestStopMethod:
     def test_stop_without_start(self):

...

+@pytest.mark.unit
 class TestOperationThread:
     def setup_method(self):

As per coding guidelines: "Apply pytest markers automatically based on test directory: @pytest.mark.unit for tests/agents/".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/agents/test_stealth_operations_agent.py` around lines 33 - 1069, The
test classes in this file (e.g., TestEnums, TestDataclasses,
TestStealthOperationsAgentInit, TestCreateOpsecPlan,
TestExecuteStealthOperation, TestOperationThreadMethods, TestEvidenceManagement,
TestStealthStatusAndMetrics, TestUpdateRiskProfile, TestInternalMethods,
TestScheduledCleanups, TestStopMethod, TestOperationThread) are missing the
required pytest marker; add `@pytest.mark.unit` above each class definition and
ensure pytest is imported (add "import pytest" if not present) so all classes in
this tests/agents/ file are decorated with the unit marker per guidelines.
tests/agents/test_network_operations_agent.py (1)

57-993: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add @pytest.mark.unit markers to all test classes.

The coding guidelines require pytest markers based on test directory. Since this file is in tests/agents/, all test classes must be decorated with @pytest.mark.unit.

📝 Proposed fix to add pytest markers
+@pytest.mark.unit
 class TestDataclasses:
     def test_network_target_required_fields(self):

...

+@pytest.mark.unit
 class TestNetworkOperationsAgentInit:
     def test_init(self):

...

+@pytest.mark.unit
 class TestNetworkOperationsAgentPublicMethods:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestExecutionMethods:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestInternalHelperMethods:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestMonitoringMethods:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestNetworkChangeDetection:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestSecurityMonitoring:
     def setup_method(self):

...

+@pytest.mark.unit
 class TestStopMethod:
     def test_stop_without_start(self):

...

+@pytest.mark.unit
 class TestHistoryTrimming:
     def test_operation_history_trimmed_at_200(self):

You'll also need to import pytest at the top:

 from datetime import datetime, timedelta
 from unittest.mock import MagicMock, patch
+
+import pytest
 
 from pentestgpt.agents.network_operations_agent import (

As per coding guidelines: "Apply pytest markers automatically based on test directory: @pytest.mark.unit for tests/agents/".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/agents/test_network_operations_agent.py` around lines 57 - 993, Import
pytest at the top of the file and add the `@pytest.mark.unit` decorator to every
test class in this file (e.g., TestDataclasses, TestNetworkOperationsAgentInit,
TestNetworkOperationsAgentPublicMethods, TestExecutionMethods,
TestInternalHelperMethods, TestMonitoringMethods, TestNetworkChangeDetection,
TestSecurityMonitoring, TestStopMethod, TestHistoryTrimming) so each class is
marked as a unit test per the repository guideline; ensure the decorator is
placed immediately above each class definition.
tests/monitoring/test_response_controller.py (1)

90-927: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add return type annotations to all test methods.

As per coding guidelines, all new Python code must use strict MyPy type annotations. All test methods throughout this file should be annotated with -> None. This applies to all test classes: TestResponseEnums, TestResponseRule, TestResponseActionExecution, TestResponsePlan, TestResponseController, TestResponsePlanCreation, TestResponseExecution, TestResponsePlanLifecycle, and TestResponseStatus.

Example for the first few methods:

-    def test_response_level_members(self):
+    def test_response_level_members(self) -> None:
         assert ResponseLevel.MONITOR.value == "monitor"
         
-    def test_creation(self):
+    def test_creation(self) -> None:
         rule = ResponseRule(

Based on coding guidelines: "All new Python code must use strict MyPy type annotations with full type coverage" for **/*.py files.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/monitoring/test_response_controller.py` around lines 90 - 927, The test
methods in the file lack return type annotations; add "-> None" to every test
method and any setup/teardown methods in the test classes (e.g.,
TestResponseEnums.test_response_level_members, TestResponseRule.test_creation,
TestResponseActionExecution.test_creation, TestResponsePlan.test_creation,
TestResponseController.setup_method and its test_* methods,
TestResponsePlanCreation.* methods, TestResponseExecution.setup_method and its
tests, TestResponsePlanLifecycle.setup_method and its tests,
TestResponseStatus.setup_method and its tests) so each method signature ends
with "-> None". Ensure you update all occurrences consistently across the listed
classes without changing behavior.
tests/monitoring/test_security_event_analyzer.py (1)

53-919: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add return type annotations to all test methods.

As per coding guidelines, all new Python code must use strict MyPy type annotations. All test methods throughout this file should be annotated with -> None. This applies to all test classes: TestLogEnums, TestLogEntry, TestLogPattern, TestAnomalyDetection, TestSecurityEventLogAnalyzer, TestLogParsers, TestProcessLogEntry, TestAnomalyDetectors, TestBaselineUpdates, and TestBatchAnalysis.

Additionally, the _base_entry helper method at line 586 should return -> LogEntry.

Example for the first few methods:

-    def test_log_format_members(self):
+    def test_log_format_members(self) -> None:
         assert LogFormat.SYSLOG.value == "syslog"
         
-    def _base_entry(self):
+    def _base_entry(self) -> LogEntry:
         return LogEntry(

Based on coding guidelines: "All new Python code must use strict MyPy type annotations with full type coverage" for **/*.py files.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/monitoring/test_security_event_analyzer.py` around lines 53 - 919, Add
explicit return type annotations to all test methods and lifecycle/helpers in
the test classes: annotate every test_* method with -> None in TestLogEnums,
TestLogEntry, TestLogPattern, TestAnomalyDetection,
TestSecurityEventLogAnalyzer, TestLogParsers, TestProcessLogEntry,
TestAnomalyDetectors, TestBaselineUpdates, and TestBatchAnalysis; also annotate
setup_method methods with -> None and change the helper method _base_entry to
return -> LogEntry. Ensure the function signatures for methods like
TestLogParsers._base_entry, all setup_method, and every def test_* in those
classes include the specified return types to satisfy MyPy.
🧹 Nitpick comments (4)
tests/agents/test_network_operations_agent.py (1)

46-46: ⚡ Quick win

Replace deprecated datetime.utcnow() with datetime.now(timezone.utc).

datetime.utcnow() is deprecated in Python 3.12+ and will be removed in a future version. Use datetime.now(timezone.utc) instead for timezone-aware datetime objects.

♻️ Proposed fix
     defaults = {
         "operation_id": "op-1",
         "operation_type": NetworkOperationType.RECONNAISSANCE,
         "target": _make_target(),
         "status": NetworkStatus.PENDING,
-        "start_time": datetime.utcnow(),
+        "start_time": datetime.now(timezone.utc),
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/agents/test_network_operations_agent.py` at line 46, Replace the
deprecated call datetime.utcnow() used for the "start_time" field with a
timezone-aware datetime.now(timezone.utc); update the test to use
datetime.now(timezone.utc) instead of datetime.utcnow(), and ensure the module
imports timezone (e.g., from datetime import datetime, timezone) so the new call
resolves correctly.
tests/monitoring/test_alert_correlation_fix.py (1)

13-21: ⚖️ Poor tradeoff

Consider more robust thread leak detection.

The test uses arbitrary sleep durations (0.2s and 0.3s) and allows up to 1 extra thread (<= initial_threads + 1), which may not reliably detect thread leaks in all environments. Consider using thread join with timeout or a more deterministic synchronization mechanism.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/monitoring/test_alert_correlation_fix.py` around lines 13 - 21, The
test uses fixed sleeps and a loose thread-count assertion; replace that with
deterministic synchronization by waiting for the engine's worker to stop or join
instead of sleeping: call alert_correlation_engine.stop_correlation(), then join
or wait on the engine's internal thread(s) (or expose a stop_event/finished
Event from alert_correlation_engine) with a short timeout, and only after the
join succeeds assert threading.active_count() <= initial_threads (or equals
initial_threads); avoid arbitrary time.sleep() and the "+ 1" allowance so the
test reliably detects leaks. Use the existing methods
alert_correlation_engine.start_correlation() and
alert_correlation_engine.stop_correlation() and reference the engine's worker
thread(s) to perform the join/poll.
tests/network/test_segmentation_traversal_deep.py (1)

74-864: 💤 Low value

Add return type annotations to test methods.

All test methods throughout the file are missing return type annotations (-> None). While this is common in pytest code, the coding guidelines require full type coverage for all new Python code.

Consider adding -> None annotations to setup_method and all test_* methods, and async def test methods should be annotated as async def test_name(...) -> None:.

Example:

def setup_method(self) -> None:
    self.config = _make_config()

def test_network_segment_type_values(self) -> None:
    assert NetworkSegmentType.DMZ.value == "dmz"

As per coding guidelines: "All new Python code must use strict MyPy type annotations with full type coverage."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/network/test_segmentation_traversal_deep.py` around lines 74 - 864, The
tests lack explicit return type annotations; add "-> None" to every test and
setup method in this file (e.g. setup_method, all def test_* methods like
test_network_segment_type_values, test_discover_network_range_empty, etc.) and
to every async test (e.g. async def test_handle_network_event_scan_request) to
satisfy the MyPy/type coverage rule; update each function signature to include
"-> None" without changing bodies or behavior.
tests/network/test_protocol_evasion_deep.py (1)

55-877: 💤 Low value

Add return type annotations to test methods.

All test methods throughout the file are missing return type annotations (-> None). While this is common in pytest code, the coding guidelines require full type coverage for all new Python code.

Consider adding -> None annotations to setup_method and all test_* methods, and async def test methods should be annotated as async def test_name(...) -> None:.

Example:

def setup_method(self) -> None:
    self.mgr = _make_manager()

def test_traffic_mimicry_type_values(self) -> None:
    assert TrafficMimicryType.LEGITIMATE_BROWSING.value == "legitimate_browsing"

As per coding guidelines: "All new Python code must use strict MyPy type annotations with full type coverage."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/network/test_protocol_evasion_deep.py` around lines 55 - 877, Add
explicit return type annotations (-> None) to every test and setup method in
this file: annotate all def test_* methods and setup_method methods as "-> None"
and annotate async tests as "async def ...(...) -> None". Locate and update
methods such as TestEnums.test_traffic_mimicry_type_values,
TestDataclasses.test_protocol_packet_defaults, TestPayloadEncoding.setup_method,
TestXorEncryption.setup_method, TestHeaderObfuscation.setup_method,
TestEvasionStrategy.setup_method, TestTimingStrategy.setup_method,
TestTrafficMimicry.setup_method, TestEvadeProtocol.setup_method,
TestParseTarget.setup_method, TestStealthCommunication.setup_method,
TestEvasionStatistics.setup_method,
TestRegisterIntegration.test_register_integration,
TestIncreaseEvasionIntensity.test_increase_adds_techniques,
TestHandleNetworkEvent.setup_method and its async tests (e.g., async def
test_evasion_request_event), and TestPacketHelpers.setup_method and its test_*
functions; ensure each signature includes "-> None" with no other behavioral
changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/agents/test_network_operations_agent.py`:
- Around line 23-49: Add explicit return type annotations to the helper
functions: annotate _make_agent() to return NetworkOperationsAgent,
_make_target(...) to return NetworkTarget, and _make_operation(...) to return
NetworkOperation; ensure any parameter types (like **overrides) are typed as
Mapping[str, Any] or appropriate TypedDict if available and import Any and
Mapping from typing so these functions satisfy strict MyPy coverage and match
the NetworkOperationsAgent, NetworkTarget, and NetworkOperation constructors.

In `@tests/agents/test_stealth_operations_agent.py`:
- Around line 21-25: The helper function _make_agent is missing a MyPy return
type annotation; update its signature to include the concrete return type
(StealthOperationsAgent) so the function becomes typed (e.g., def _make_agent()
-> StealthOperationsAgent:), and ensure any necessary imports or forward
references for StealthOperationsAgent are added to the test file so the
annotation resolves correctly; keep existing body (router mocks and return)
unchanged.

In `@tests/conftest.py`:
- Around line 335-350: The fixture function alert_correlation_engine lacks a
MyPy return type annotation; update its signature to declare the return type as
Generator[AlertCorrelationEngine, None, None], import Generator from typing (or
collections.abc) at the top of the file, and ensure AlertCorrelationEngine is in
scope (import or annotate via forward reference) so the fixture signature reads
as alert_correlation_engine(...) -> Generator[AlertCorrelationEngine, None,
None].

In `@tests/effectiveness/test_success_rate_analytics.py`:
- Around line 28-33: Add a precise return type annotation to the helper function
_make_router so it satisfies MyPy: declare the function returns MagicMock (or
unittest.mock.MagicMock) whose route_task is typed to return Tuple[str,
Dict[Any, Any], float]; update the def _make_router() signature accordingly and
import any needed typing symbols (Tuple, Dict, Any) to ensure full type coverage
for the returned MagicMock with a route_task return type.

In `@tests/knowledge/test_intelligence_feed_integrator.py`:
- Around line 193-201: The test shows
ThreatIntelligenceProcessor.process_threat_feed silently returns None when
"indicators" is a list; update process_threat_feed to explicitly handle both str
and list inputs (or raise a clear TypeError): inside
ThreatIntelligenceProcessor.process_threat_feed detect the type of the
indicators field, if it's a list join/normalize it into the expected string
format (or iterate to create indicator objects) before concatenation, and if
it's an unexpected type raise TypeError with a descriptive message mentioning
"indicators" and expected types; also update any docstring/comments for
process_threat_feed to state accepted input types so callers know the contract.

In `@tests/monitoring/test_alert_correlation_fix.py`:
- Around line 8-24: Add explicit return type annotations ("-> None") to each
test function definition: test_recent_events_attribute_exists,
test_start_stop_does_not_leak, and test_correlation_not_active_by_default so
their signatures become annotated per MyPy rules; update the def lines only
(e.g., def test_recent_events_attribute_exists(self) -> None:) and keep the
bodies unchanged.

In `@tests/monitoring/test_response_controller.py`:
- Around line 29-87: Add explicit return type annotations to the four helpers:
annotate _make_controller to return ResponseController, _make_event to return
MonitoredEvent, _make_action to return ResponseActionExecution, and
_make_response_plan to return ResponsePlan; update their signatures to include
these types and import any missing types (ResponseController, MonitoredEvent,
ResponseActionExecution, ResponsePlan) or use fully-qualified names, and ensure
any typing imports (e.g., from typing import Dict, Any) are added if needed so
the functions satisfy strict MyPy coverage.

In `@tests/monitoring/test_security_event_analyzer.py`:
- Around line 26-50: Add explicit return type annotations to the module helpers:
annotate _make_analyzer to return SecurityEventLogAnalyzer and _make_log_entry
to return LogEntry; update their signatures to include these return types and
import any missing types (SecurityEventLogAnalyzer, LogEntry) at top of the test
module so MyPy sees them, ensuring the stubbed/mocked values still conform to
those types.

In `@tests/network/test_protocol_evasion_deep.py`:
- Around line 33-47: The helper functions _make_config, _make_router, and
_make_manager lack MyPy type annotations; add explicit return type annotations
and parameter types (e.g., _make_config(**overrides: Any) -> NetworkConfig,
_make_router() -> MagicMock, _make_manager(**config_overrides: Any) ->
ProtocolEvasionManager) and import Any from typing so the file has full type
coverage for these helpers.
- Around line 807-813: The test and comment show that for alert_level == "low"
handle_network_event does not call _increase_evasion_intensity(), yet it returns
status "evasion_intensity_increased" which is misleading; update
handle_network_event (the function named handle_network_event in
protocol_evasion.py) to return a clear status when no intensity change occurs
(e.g., "no_evasion_intensity_change" or "evasion_intensity_unchanged") for the
low branch, and adjust the test test_detection_alert_low (or its
assertion/comment) accordingly so the status string accurately reflects whether
_increase_evasion_intensity() was invoked.

In `@tests/network/test_segmentation_traversal_deep.py`:
- Around line 37-66: Add MyPy type annotations and necessary typing imports:
import Any, Dict, List, Optional from typing. Annotate _make_config(**overrides)
-> NetworkConfig with parameter overrides: Dict[str, Any]; annotate
_make_router() -> MagicMock (or more generally -> Any if MagicMock type isn't
imported); annotate _make_host with types ip: str, open_ports: Any =
_SENTINEL_PORTS, services: Any = _SENTINEL_SERVICES, trust_level: float = 0.5,
segment_type: NetworkSegmentType = NetworkSegmentType.INTERNAL and return type
-> NetworkHost; ensure the file imports Any (and other typing names you use) so
MyPy has full coverage for _make_config, _make_router, and _make_host.

In `@tests/utils/test_stealth_orchestrator_integration.py`:
- Around line 59-75: Add an explicit return type to the helper: change the
signature of _build_orchestrator to annotate its return as
StealthEnhancedOrchestrator (i.e. def _build_orchestrator(...) ->
StealthEnhancedOrchestrator:). Ensure the StealthEnhancedOrchestrator name is
available for annotations by importing it from
pentestgpt.utils.stealth_orchestrator_integration at module scope or by using a
string literal/"forward reference" for the type; keep the existing in-function
import (or move it) so the runtime behavior is unchanged.
- Line 19: Add explicit return type annotations "-> None" to every test function
in this file (every def whose name starts with test_), matching the style used
in test_detection_resistance_orchestrator_integration.py; leave helper
functions' existing annotations as-is or make them consistent if missing. Locate
all unannotated test methods (def test_*) and append "-> None" to their
signatures, update any stub or fixture functions if they are intended as tests,
and run the test suite/mypy to ensure full type coverage compliance with strict
MyPy rules.
- Around line 136-144: The _make_orch helper should declare an explicit return
type instead of using the # type: ignore; change its signature to include the
concrete return type returned by _build_orchestrator (e.g., PentestOrchestrator
or the Orchestrator type exported by the module) and remove the "# type:
ignore[name-defined]" comment; if that type isn't in scope in the test file, add
an import or a typing-only import (from
pentestgpt.utils.stealth_orchestrator_integration import PentestOrchestrator or
use TYPE_CHECKING) so mypy can resolve the annotation while leaving the patched
symbols unchanged.

---

Outside diff comments:
In `@tests/agents/test_network_operations_agent.py`:
- Around line 57-993: Import pytest at the top of the file and add the
`@pytest.mark.unit` decorator to every test class in this file (e.g.,
TestDataclasses, TestNetworkOperationsAgentInit,
TestNetworkOperationsAgentPublicMethods, TestExecutionMethods,
TestInternalHelperMethods, TestMonitoringMethods, TestNetworkChangeDetection,
TestSecurityMonitoring, TestStopMethod, TestHistoryTrimming) so each class is
marked as a unit test per the repository guideline; ensure the decorator is
placed immediately above each class definition.

In `@tests/agents/test_stealth_operations_agent.py`:
- Around line 33-1069: The test classes in this file (e.g., TestEnums,
TestDataclasses, TestStealthOperationsAgentInit, TestCreateOpsecPlan,
TestExecuteStealthOperation, TestOperationThreadMethods, TestEvidenceManagement,
TestStealthStatusAndMetrics, TestUpdateRiskProfile, TestInternalMethods,
TestScheduledCleanups, TestStopMethod, TestOperationThread) are missing the
required pytest marker; add `@pytest.mark.unit` above each class definition and
ensure pytest is imported (add "import pytest" if not present) so all classes in
this tests/agents/ file are decorated with the unit marker per guidelines.

In `@tests/monitoring/test_response_controller.py`:
- Around line 90-927: The test methods in the file lack return type annotations;
add "-> None" to every test method and any setup/teardown methods in the test
classes (e.g., TestResponseEnums.test_response_level_members,
TestResponseRule.test_creation, TestResponseActionExecution.test_creation,
TestResponsePlan.test_creation, TestResponseController.setup_method and its
test_* methods, TestResponsePlanCreation.* methods,
TestResponseExecution.setup_method and its tests,
TestResponsePlanLifecycle.setup_method and its tests,
TestResponseStatus.setup_method and its tests) so each method signature ends
with "-> None". Ensure you update all occurrences consistently across the listed
classes without changing behavior.

In `@tests/monitoring/test_security_event_analyzer.py`:
- Around line 53-919: Add explicit return type annotations to all test methods
and lifecycle/helpers in the test classes: annotate every test_* method with ->
None in TestLogEnums, TestLogEntry, TestLogPattern, TestAnomalyDetection,
TestSecurityEventLogAnalyzer, TestLogParsers, TestProcessLogEntry,
TestAnomalyDetectors, TestBaselineUpdates, and TestBatchAnalysis; also annotate
setup_method methods with -> None and change the helper method _base_entry to
return -> LogEntry. Ensure the function signatures for methods like
TestLogParsers._base_entry, all setup_method, and every def test_* in those
classes include the specified return types to satisfy MyPy.

---

Nitpick comments:
In `@tests/agents/test_network_operations_agent.py`:
- Line 46: Replace the deprecated call datetime.utcnow() used for the
"start_time" field with a timezone-aware datetime.now(timezone.utc); update the
test to use datetime.now(timezone.utc) instead of datetime.utcnow(), and ensure
the module imports timezone (e.g., from datetime import datetime, timezone) so
the new call resolves correctly.

In `@tests/monitoring/test_alert_correlation_fix.py`:
- Around line 13-21: The test uses fixed sleeps and a loose thread-count
assertion; replace that with deterministic synchronization by waiting for the
engine's worker to stop or join instead of sleeping: call
alert_correlation_engine.stop_correlation(), then join or wait on the engine's
internal thread(s) (or expose a stop_event/finished Event from
alert_correlation_engine) with a short timeout, and only after the join succeeds
assert threading.active_count() <= initial_threads (or equals initial_threads);
avoid arbitrary time.sleep() and the "+ 1" allowance so the test reliably
detects leaks. Use the existing methods
alert_correlation_engine.start_correlation() and
alert_correlation_engine.stop_correlation() and reference the engine's worker
thread(s) to perform the join/poll.

In `@tests/network/test_protocol_evasion_deep.py`:
- Around line 55-877: Add explicit return type annotations (-> None) to every
test and setup method in this file: annotate all def test_* methods and
setup_method methods as "-> None" and annotate async tests as "async def
...(...) -> None". Locate and update methods such as
TestEnums.test_traffic_mimicry_type_values,
TestDataclasses.test_protocol_packet_defaults, TestPayloadEncoding.setup_method,
TestXorEncryption.setup_method, TestHeaderObfuscation.setup_method,
TestEvasionStrategy.setup_method, TestTimingStrategy.setup_method,
TestTrafficMimicry.setup_method, TestEvadeProtocol.setup_method,
TestParseTarget.setup_method, TestStealthCommunication.setup_method,
TestEvasionStatistics.setup_method,
TestRegisterIntegration.test_register_integration,
TestIncreaseEvasionIntensity.test_increase_adds_techniques,
TestHandleNetworkEvent.setup_method and its async tests (e.g., async def
test_evasion_request_event), and TestPacketHelpers.setup_method and its test_*
functions; ensure each signature includes "-> None" with no other behavioral
changes.

In `@tests/network/test_segmentation_traversal_deep.py`:
- Around line 74-864: The tests lack explicit return type annotations; add "->
None" to every test and setup method in this file (e.g. setup_method, all def
test_* methods like test_network_segment_type_values,
test_discover_network_range_empty, etc.) and to every async test (e.g. async def
test_handle_network_event_scan_request) to satisfy the MyPy/type coverage rule;
update each function signature to include "-> None" without changing bodies or
behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1e9cef29-501d-49a9-96d2-039e3c708938

📥 Commits

Reviewing files that changed from the base of the PR and between 49af785 and 45bbbdf.

📒 Files selected for processing (18)
  • tests/agents/test_network_operations_agent.py
  • tests/agents/test_stealth_operations_agent.py
  • tests/conftest.py
  • tests/detection_resistance/test_ai_ml_resistance_deep.py
  • tests/detection_resistance/test_edr_evasion_deep.py
  • tests/effectiveness/test_success_rate_analytics.py
  • tests/knowledge/test_intelligence_feed_integrator.py
  • tests/monitoring/test_alert_correlation_fix.py
  • tests/monitoring/test_response_controller.py
  • tests/monitoring/test_security_event_analyzer.py
  • tests/network/test_protocol_evasion_deep.py
  • tests/network/test_segmentation_traversal_deep.py
  • tests/testing/__init__.py
  • tests/testing/test_automation_framework.py
  • tests/testing/test_security_validation_suite.py
  • tests/utils/test_config_validation.py
  • tests/utils/test_detection_resistance_orchestrator_integration.py
  • tests/utils/test_stealth_orchestrator_integration.py

Comment thread tests/agents/test_network_operations_agent.py
Comment thread tests/agents/test_stealth_operations_agent.py Outdated
Comment thread tests/conftest.py Outdated
Comment thread tests/effectiveness/test_success_rate_analytics.py Outdated
Comment thread tests/knowledge/test_intelligence_feed_integrator.py Outdated
Comment thread tests/network/test_protocol_evasion_deep.py Outdated
Comment thread tests/network/test_segmentation_traversal_deep.py Outdated
Comment thread tests/utils/test_stealth_orchestrator_integration.py
Comment thread tests/utils/test_stealth_orchestrator_integration.py Outdated
Comment thread tests/utils/test_stealth_orchestrator_integration.py Outdated
…uff/mypy strict

Production fixes (P2):
- intelligence_feed_integrator: normalize list/str indicators before IOC extraction
  instead of silently swallowing TypeError and returning None
- protocol_evasion: return "evasion_intensity_unchanged" for low-level detection
  alerts; only return "evasion_intensity_increased" when intensity actually changes

Type annotation sweep (mypy --strict + ruff clean across 538 files):
- Add -> None to all test methods and setup_method throughout changed test files
- Annotate helper functions with proper return types and **overrides: Any
- Fix bare dict / dict | None to dict[str, Any] | None in signatures
- Add dict[str, Any] to untyped literal assignments (var-annotated errors)
- Fix AlertSeverity import to its canonical module (detection_monitor)
- Replace unused # type: ignore comments; add # type: ignore[method-assign]
  where ruff B010 and mypy method-assign conflict on mock assignments
- Type self.orch: Any in stealth/detection orchestrator test setup_method to
  allow MagicMock attribute access on heavily-patched typed objects
- Add Generator[AlertCorrelationEngine, None, None] return to conftest fixture

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/conftest.py`:
- Line 335: The fixture alert_correlation_engine is missing a type annotation
for its mock_model_router parameter; update the signature of
alert_correlation_engine to add a proper MyPy-compatible type for
mock_model_router (use the concrete fixture type used elsewhere in tests—e.g.,
the MockModelRouter class or protocol) so the function has full type coverage,
or if mock_model_router isn't referenced inside alert_correlation_engine remove
the parameter from the signature to avoid unused untyped params; reference the
alert_correlation_engine fixture and the mock_model_router fixture/type when
making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 633327e9-07ac-48b1-a7fc-eb13c305b293

📥 Commits

Reviewing files that changed from the base of the PR and between 45bbbdf and 2d9c416.

📒 Files selected for processing (18)
  • pentestgpt/knowledge/intelligence_feed_integrator.py
  • pentestgpt/network/protocol_evasion.py
  • tests/agents/test_network_operations_agent.py
  • tests/agents/test_stealth_operations_agent.py
  • tests/conftest.py
  • tests/detection_resistance/test_ai_ml_resistance_deep.py
  • tests/detection_resistance/test_edr_evasion_deep.py
  • tests/effectiveness/test_success_rate_analytics.py
  • tests/knowledge/test_intelligence_feed_integrator.py
  • tests/monitoring/test_alert_correlation_fix.py
  • tests/monitoring/test_response_controller.py
  • tests/monitoring/test_security_event_analyzer.py
  • tests/network/test_protocol_evasion_deep.py
  • tests/network/test_segmentation_traversal_deep.py
  • tests/testing/test_automation_framework.py
  • tests/testing/test_security_validation_suite.py
  • tests/utils/test_detection_resistance_orchestrator_integration.py
  • tests/utils/test_stealth_orchestrator_integration.py
🚧 Files skipped from review as they are similar to previous changes (14)
  • tests/monitoring/test_alert_correlation_fix.py
  • tests/utils/test_detection_resistance_orchestrator_integration.py
  • tests/knowledge/test_intelligence_feed_integrator.py
  • tests/detection_resistance/test_edr_evasion_deep.py
  • tests/agents/test_network_operations_agent.py
  • tests/monitoring/test_security_event_analyzer.py
  • tests/network/test_protocol_evasion_deep.py
  • tests/network/test_segmentation_traversal_deep.py
  • tests/testing/test_security_validation_suite.py
  • tests/testing/test_automation_framework.py
  • tests/monitoring/test_response_controller.py
  • tests/agents/test_stealth_operations_agent.py
  • tests/detection_resistance/test_ai_ml_resistance_deep.py
  • tests/utils/test_stealth_orchestrator_integration.py

Comment thread tests/conftest.py Outdated
SALhik and others added 3 commits June 7, 2026 21:18
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…elation_engine fixture

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@SALhik
SALhik merged commit 4412353 into main Jun 8, 2026
0 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant