Skip to content

Implement API test suite with 100% coverage#1442

Open
Ya-Sabyr wants to merge 2 commits intoOWASP:masterfrom
Ya-Sabyr:api-test-coverage
Open

Implement API test suite with 100% coverage#1442
Ya-Sabyr wants to merge 2 commits intoOWASP:masterfrom
Ya-Sabyr:api-test-coverage

Conversation

@Ya-Sabyr
Copy link
Copy Markdown

@Ya-Sabyr Ya-Sabyr commented Mar 23, 2026

Proposed change

This PR improves API test coverage by adding a dedicated API test fixture layer and a comprehensive test suite for nettacker/api/engine.py.

The changes include:

  • adding tests/api/conftest.py to isolate Flask app state, API config, and temporary results paths during tests
  • adding tests/api/test_engine.py to cover:
    • error handlers
    • security headers and access logging
    • API key and IP whitelist enforcement
    • static and index routes
    • scan/session/compare endpoints
    • results and logs export endpoints
    • search behavior
    • API startup helpers
  • covering the remaining defensive and branch-only paths so nettacker/api/engine.py now reaches 100% coverage

This is a test-only change and does not modify production behavior.

Validation performed:

  • poetry run pytest --cov=nettacker/api/engine --cov-report term-missing tests/api/test_engine.py -q
  • make test

Results:

  • nettacker/api/engine.py: 0% -> 100%
  • overall repository coverage: 48% -> 56%
  • full test suite: 338 passed, 6 skipped, 2 xfailed

Type of change

  • New core framework functionality
  • Bugfix (non-breaking change which fixes an issue)
  • Code refactoring without any functionality changes
  • New or existing module/payload change
  • Documentation/localization improvement
  • Test coverage improvement
  • Dependency upgrade
  • Other improvement (best practice, cleanup, optimization, etc)

Checklist

  • I've followed the contributing guidelines
  • I have digitally signed all my commits in this PR
  • I've run make pre-commit and confirm it didn't generate any warnings/changes
  • I've run make test, I confirm all tests passed locally
  • I've added/updated any relevant documentation in the docs/ folder
  • I've linked this PR with an open issue
  • I've tested and verified that my code works as intended and resolves the issue as described
  • I have attached screenshots demonstrating my code works as intended
  • I've checked all other open PRs to avoid submitting duplicate work
  • I confirm that the code and comments in this PR are not direct unreviewed outputs of AI
  • I confirm that I am the Sole Responsible Author for every line of code, comment, and design decision

Copilot AI review requested due to automatic review settings March 23, 2026 13:21
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 23, 2026

Walkthrough

Two new test files have been added to the API test suite. A conftest.py file provides pytest fixtures that manage test configuration and setup/teardown, including an autouse fixture that snapshots and restores engine configuration state. A comprehensive test_engine.py file contains tests for the API's Flask error handlers, security headers, IP whitelisting, request logging, static assets, authentication, session management, scan operations, results/logs endpoints, attachments, and subprocess startup behavior.

Changes

Cohort / File(s) Summary
Test Fixtures Setup
tests/api/conftest.py
Introduces pytest fixtures for API tests: api_test_state (autouse) snapshots and restores Flask app config and Nettacker configuration before/after each test, api_client returns the Flask test client, and api_key provides a constant test key value.
API Engine Test Suite
tests/api/test_engine.py
Comprehensive test coverage for the Flask API including error response handling, security headers injection, IP whitelist enforcement, request logging, static asset serving, template rendering, filename sanitization, API key authentication, session management, scan creation and comparison workflows, results/logs pagination and retrieval, attachment generation with formatting, logs rendering, search functionality, and subprocess/server initialization with SSL context and child process management.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • arkid15r
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title directly summarizes the main change: implementing an API test suite to achieve 100% code coverage for the engine module.
Description check ✅ Passed The PR description is directly related to the changeset, clearly explaining the addition of test fixtures and a comprehensive test suite for nettacker/api/engine.py with specific coverage improvements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds a dedicated API testing fixture layer and a comprehensive test suite targeting nettacker/api/engine.py, aiming to fully exercise its routes, helpers, and error/edge-case behavior without changing production code.

Changes:

  • Added tests/api/conftest.py to isolate Flask app config/state and redirect results output into a temp directory per test.
  • Added tests/api/test_engine.py to cover API error handlers, security/access logging middleware, auth/IP filtering, routes, export endpoints, search behavior, and API startup helpers.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
tests/api/conftest.py Introduces an autouse fixture to reset API app config and results directory state between tests, plus api_client/api_key helpers.
tests/api/test_engine.py Adds a broad set of unit/integration-style Flask tests for nettacker.api.engine covering routes, middleware, and subprocess/server helpers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/api/test_engine.py (1)

591-600: Use the shared api_key fixture instead of a hardcoded query value.

This test already takes api_key, so hardcoding test-key here creates a second source of truth and makes fixture changes easier to miss.

Suggested fix
-    with engine.app.test_request_context("/logs/search?key=test-key&page=1"), patch.object(
+    with engine.app.test_request_context(
+        f"/logs/search?key={api_key}&page=1"
+    ), patch.object(
         engine, "get_value", side_effect=fake_get_value
     ), patch.object(engine, "search_logs", return_value=[{"query": ""}]) as mock_search:
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/api/test_engine.py` around lines 591 - 600, The test
test_go_for_search_logs_falls_back_when_query_lookup_raises hardcodes the key
query parameter ("test-key") instead of using the provided api_key fixture;
update the engine.app.test_request_context call (and any other occurrences in
this test) to use the api_key fixture value (e.g., interpolate api_key into the
request path or build the query params from api_key) so the test relies on the
shared fixture rather than a second hardcoded source of truth; keep the
fake_get_value patching of engine.get_value unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/api/conftest.py`:
- Around line 14-16: The teardown snapshots use shallow copies so nested mutable
state can leak between tests; replace the shallow copies with deep copies for
the saved config state by using a deep copy of engine.app.config and
engine.nettacker_application_config (and any other saved dicts such as the
variables captured as original_app_config and original_application_config)
before mutating globals, and ensure primitives like original_results_dir remain
copied as-is; locate the assignments that create original_app_config and
original_application_config and change them to use a deep copy operation (e.g.,
via copy.deepcopy) so nested structures like api_client_whitelisted_ips are
fully duplicated.

---

Nitpick comments:
In `@tests/api/test_engine.py`:
- Around line 591-600: The test
test_go_for_search_logs_falls_back_when_query_lookup_raises hardcodes the key
query parameter ("test-key") instead of using the provided api_key fixture;
update the engine.app.test_request_context call (and any other occurrences in
this test) to use the api_key fixture value (e.g., interpolate api_key into the
request path or build the query params from api_key) so the test relies on the
shared fixture rather than a second hardcoded source of truth; keep the
fake_get_value patching of engine.get_value unchanged.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ff98b1a9-951e-4a73-b97a-1f48c86e56c8

📥 Commits

Reviewing files that changed from the base of the PR and between 74d89e2 and 2725944.

📒 Files selected for processing (2)
  • tests/api/conftest.py
  • tests/api/test_engine.py

Comment thread tests/api/conftest.py
@Ya-Sabyr Ya-Sabyr changed the title init Implement API test suite with 100% coverage Mar 23, 2026
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.

2 participants