Skip to content
This repository was archived by the owner on Jul 28, 2025. It is now read-only.

tests: add zmap tests#11

Merged
dogancanbakir merged 3 commits into
HappyHackingSpace:mainfrom
ahsentekd:main
Jul 1, 2025
Merged

tests: add zmap tests#11
dogancanbakir merged 3 commits into
HappyHackingSpace:mainfrom
ahsentekd:main

Conversation

@ahsentekd

@ahsentekd ahsentekd commented Jun 19, 2025

Copy link
Copy Markdown
Contributor

add some unit tests

Summary by CodeRabbit

  • Tests
    • Added tests for API endpoints, including root and documentation endpoints.
    • Introduced tests for configuration validation and error handling.
    • Added tests to verify correct initialization and attribute assignment for request schemas.
  • Chores
    • Updated CI workflow to include a test execution step.
    • Added a Makefile target to run tests via Poetry.

@coderabbitai

coderabbitai Bot commented Jun 19, 2025

Copy link
Copy Markdown

Walkthrough

This update introduces three new test modules targeting the API, configuration, and schema layers of the project. It also modifies an import statement in the API module to use absolute imports. The new tests leverage mocking and validation to verify correct endpoint responses, configuration handling, and schema initialization. Additionally, the CI workflow is enhanced to run tests, and a Makefile target is added to facilitate running pytest.

Changes

File(s) Summary
tests/test_api.py Adds pytest fixtures and tests for FastAPI endpoints, including root and docs endpoints, with mocking.
tests/test_config.py Adds test for ZMapScanConfig creation, attribute validation, and error handling.
tests/test_schemas.py Adds tests for ScanRequest schema: minimal and full initialization validation.
zmapsdk/api.py Changes relative import of ZMap to absolute import; removes unused import.
.github/workflows/ci.yml Adds a "Run tests" step executing make pytest after linting.
Makefile Adds pytest target to run tests via poetry run pytest.

Sequence Diagram(s)

sequenceDiagram
    participant TestClient
    participant FastAPI_App
    participant MockZMap

    TestClient->>FastAPI_App: GET "/"
    FastAPI_App->>MockZMap: get_version()
    MockZMap-->>FastAPI_App: "1.2.3"
    FastAPI_App-->>TestClient: JSON response with version info

    TestClient->>FastAPI_App: GET "/openapi.json"
    FastAPI_App-->>TestClient: OpenAPI schema

    TestClient->>FastAPI_App: GET "/docs"
    FastAPI_App-->>TestClient: Swagger UI HTML

    TestClient->>FastAPI_App: GET "/redoc"
    FastAPI_App-->>TestClient: Redoc HTML
Loading

Possibly related PRs

Suggested reviewers

  • dogancanbakir

Poem

In the warren, tests now bloom,
For API, config, and schema room.
With mocks and checks, the code feels bright,
Each endpoint tested, all set right.
A bunny hops with gleeful cheer—
"Our code is safe, no bugs to fear!"
🐇✨


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 3

🧹 Nitpick comments (2)
tests/test_config.py (1)

6-17: Consider expanding test coverage.

The current test only covers basic attribute access and dictionary conversion. Consider adding tests for:

  • Invalid bandwidth values
  • Edge cases for rate and max_targets
  • Validation of other configuration parameters
tests/test_schemas.py (1)

1-27: LGTM: Well-structured schema tests.

The tests provide good coverage of the ScanRequest schema with both minimal and comprehensive configurations. The assertions properly validate default values and explicit field assignments.

Consider adding edge case tests for better coverage:

  • Invalid subnet formats
  • Invalid port ranges
  • Invalid file paths
  • Field validation boundaries
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a06c26 and a38bcd0.

📒 Files selected for processing (4)
  • tests/test_api.py (1 hunks)
  • tests/test_config.py (1 hunks)
  • tests/test_schemas.py (1 hunks)
  • zmapsdk/api.py (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
zmapsdk/api.py

[error] 1-20: isort: Imports are incorrectly sorted and/or formatted. Please run 'isort --write' to fix import order.

tests/test_config.py

[error] 1-10: isort: Imports are incorrectly sorted and/or formatted. Please run 'isort --write' to fix import order.

🔇 Additional comments (4)
zmapsdk/api.py (1)

18-18: LGTM: Import change improves consistency.

The change from relative to absolute import aligns well with the package structure and maintains consistency with other imports in the file.

However, please address the pipeline failure regarding import sorting:

#!/bin/bash
# Description: Check import order issues in the file
# Expected: Show current import order and suggest fixes

echo "Current import structure:"
head -20 zmapsdk/api.py

echo -e "\n\nRunning isort to check issues:"
isort --check-only --diff zmapsdk/api.py || echo "Import sorting needed"
tests/test_config.py (1)

1-4: Fix import sorting issues.

The pipeline indicates import formatting problems. Please run isort --write to fix the import order.

tests/test_api.py (2)

42-53: LGTM: Comprehensive endpoint testing.

The test properly mocks the ZMap instance, validates the response structure, and ensures the mock method is called correctly.


56-68: LGTM: Good documentation endpoint coverage.

The tests verify that all documentation endpoints are accessible and return expected content, which is essential for API usability.

Comment thread tests/test_config.py Outdated
Comment on lines +19 to +21
with pytest.raises(ZMapConfigError) as exc_info:
conf = ZMapScanConfig(source_port=-9999)
assert f"Invalid source port range: {conf.source_port}. Must be between 0 and 65535." in str(exc_info.value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix test logic error: assertion should be outside the context manager.

The assertion on line 21 is incorrectly placed inside the pytest.raises context. It should be moved outside to properly validate the exception message.

Apply this fix:

    with pytest.raises(ZMapConfigError) as exc_info:
        conf = ZMapScanConfig(source_port=-9999)
-        assert f"Invalid source port range: {conf.source_port}. Must be between 0 and 65535." in str(exc_info.value)
+    assert f"Invalid source port range: -9999. Must be between 0 and 65535." in str(exc_info.value)

Note: Also fixed the reference to use the actual invalid value (-9999) directly since conf.source_port may not be accessible if the exception is raised during initialization.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with pytest.raises(ZMapConfigError) as exc_info:
conf = ZMapScanConfig(source_port=-9999)
assert f"Invalid source port range: {conf.source_port}. Must be between 0 and 65535." in str(exc_info.value)
with pytest.raises(ZMapConfigError) as exc_info:
conf = ZMapScanConfig(source_port=-9999)
assert f"Invalid source port range: -9999. Must be between 0 and 65535." in str(exc_info.value)
🤖 Prompt for AI Agents
In tests/test_config.py around lines 19 to 21, the assertion checking the
exception message is incorrectly inside the pytest.raises context manager. Move
the assertion outside the with block to properly verify the exception message
after the exception is caught. Also, replace conf.source_port with the literal
invalid value -9999 in the assertion message to avoid referencing conf when
initialization fails.

Comment thread tests/test_api.py
Comment on lines +38 to +41
def test_root_endpoint_success(
client: TestClient,
mock_zmap: Generator[MagicMock, Any, None]
) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect type annotation.

The mock_zmap parameter should be typed as MagicMock, not Generator[MagicMock, Any, None].

def test_root_endpoint_success(
        client: TestClient,
-        mock_zmap: Generator[MagicMock, Any, None]
+        mock_zmap: MagicMock
) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_root_endpoint_success(
client: TestClient,
mock_zmap: Generator[MagicMock, Any, None]
) -> None:
def test_root_endpoint_success(
client: TestClient,
mock_zmap: MagicMock
) -> None:
🤖 Prompt for AI Agents
In tests/test_api.py around lines 38 to 41, the type annotation for the
mock_zmap parameter is incorrect; it is currently annotated as
Generator[MagicMock, Any, None]. Change the type annotation of mock_zmap to
MagicMock to correctly reflect its type.

Comment thread tests/test_api.py
Comment on lines +16 to +36
@pytest.fixture(autouse=True)
def mock_zmap() -> Generator[MagicMock, Any, None]:
"""Automatically mock the ZMap instance before each test."""
with patch('zmapsdk.api.ZMap') as mock_zmap:
mock_instance = MagicMock()
mock_zmap.return_value = mock_instance
app.state.zmap = mock_instance
yield mock_instance
if hasattr(app.state, 'zmap'):
del app.state.zmap

@pytest.fixture(autouse=True)
def setup_teardown() -> Generator[None, Any, None]:
"""Fixture to handle setup and teardown for each test."""
mock_zmap = MagicMock()
app.state.zmap = mock_zmap
yield
# Teardown - clean up
if hasattr(app.state, 'zmap'):
del app.state.zmap

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix duplicate and conflicting fixtures.

You have two autouse fixtures (mock_zmap and setup_teardown) that both manipulate app.state.zmap, which can cause conflicts and unpredictable behavior.

Consolidate into a single fixture:

@pytest.fixture(autouse=True)
-def mock_zmap() -> Generator[MagicMock, Any, None]:
-    """Automatically mock the ZMap instance before each test."""
-    with patch('zmapsdk.api.ZMap') as mock_zmap:
-        mock_instance = MagicMock()
-        mock_zmap.return_value = mock_instance
-        app.state.zmap = mock_instance
-        yield mock_instance
-        if hasattr(app.state, 'zmap'):
-            del app.state.zmap
-
-@pytest.fixture(autouse=True)
-def setup_teardown() -> Generator[None, Any, None]:
-    """Fixture to handle setup and teardown for each test."""
+def mock_zmap_instance() -> Generator[MagicMock, Any, None]:
+    """Automatically mock the ZMap instance before each test."""
     mock_zmap = MagicMock()
     app.state.zmap = mock_zmap
-    yield
-    # Teardown - clean up
+    yield mock_zmap
     if hasattr(app.state, 'zmap'):
         del app.state.zmap

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In tests/test_api.py around lines 16 to 36, there are two autouse fixtures both
setting and deleting app.state.zmap, causing conflicts. Consolidate these into a
single autouse fixture that mocks ZMap, assigns the mock to app.state.zmap
before yielding, and deletes app.state.zmap after the test completes to ensure
consistent setup and teardown without duplication.

@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: 0

🧹 Nitpick comments (1)
.github/workflows/ci.yml (1)

39-41: Add a trailing newline to satisfy YAML lint

yamllint is already flagging the missing final EOL. While this doesn’t break GitHub Actions, it will keep the workflow file permanently “dirty” in lint checks.

-        make pytest
+        make pytest
+
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 855eafd and 9a04adb.

📒 Files selected for processing (2)
  • .github/workflows/ci.yml (1 hunks)
  • Makefile (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Makefile
🧰 Additional context used
🪛 YAMLlint (1.37.1)
.github/workflows/ci.yml

[error] 41-41: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (1)
.github/workflows/ci.yml (1)

35-38: Lint step is correctly wired into CI

Adding a dedicated make lint step keeps style violations from masking test results. Looks good.

@dogancanbakir
dogancanbakir merged commit 5ab2603 into HappyHackingSpace:main Jul 1, 2025
2 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants