Skip to content
This repository was archived by the owner on Jun 16, 2026. It is now read-only.

πŸ§ͺ Add tests for transport conditional branches in main.py - #242

Merged
Adam Poulemanos (bashandbone) merged 2 commits into
mainfrom
test/add-main-run-conditional-branch-tests-12817532639525235297
Mar 17, 2026
Merged

πŸ§ͺ Add tests for transport conditional branches in main.py#242
Adam Poulemanos (bashandbone) merged 2 commits into
mainfrom
test/add-main-run-conditional-branch-tests-12817532639525235297

Conversation

@bashandbone

@bashandbone Adam Poulemanos (bashandbone) commented Mar 17, 2026

Copy link
Copy Markdown
Contributor

🎯 What: The testing gap addressed
The run function in src/codeweaver/main.py handles the main entry point logic to start the CodeWeaver server, but the transport conditional branch (deciding between stdio proxy vs streamable-http web server logic) lacked explicit unit tests. This patch adds those missing tests to ensure the configuration parameters correctly delegate to their respective inner handlers (_run_stdio_server and _run_http_server).

πŸ“Š Coverage: What scenarios are now tested

  1. transport='stdio': Verifies that when the server is started with the stdio transport, it delegates execution to the _run_stdio_server handler, correctly passing down parameters like config_file, project_path, host, port, verbose, and debug.
  2. transport='streamable-http': Verifies that when the server is started with the HTTP transport, it delegates execution to the _run_http_server handler, again checking that all relevant configuration options are passed correctly.

✨ Result: The improvement in test coverage
The codebase now benefits from increased test reliability in its primary initialization flow. By asserting that the transport argument dictates the correct initialization branch, it serves as a safety net against regressions if new parameters are introduced to these internal handlers. It prevents silent failures that could otherwise occur if transport options are accidentally misrouted.


PR created automatically by Jules for task 12817532639525235297 started by Adam Poulemanos (@bashandbone)

Summary by Sourcery

Add coverage for the main entrypoint's transport-based delegation logic.

Tests:

  • Add async unit test verifying that run() with transport='stdio' delegates to the stdio server handler with the expected arguments.
  • Add async unit test verifying that run() with transport='streamable-http' delegates to the HTTP server handler with the expected arguments.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings March 17, 2026 03:56
@google-labs-jules

Copy link
Copy Markdown
Contributor

πŸ‘‹ Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a πŸ‘€ emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai

sourcery-ai Bot commented Mar 17, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adds async unit tests to verify that the main.run() entry point correctly delegates to the appropriate transport-specific server functions for stdio and streamable-http, including argument propagation.

File-Level Changes

Change Details Files
Added async unit tests for the run() entry point to cover transport-specific delegation logic and argument propagation.
  • Introduce an async pytest test that patches the stdio server helper and asserts run() with transport='stdio' awaits _run_stdio_server with the expected keyword arguments.
  • Introduce an async pytest test that patches the HTTP server helper and asserts run() with transport='streamable-http' awaits _run_http_server with the expected keyword arguments.
  • Ensure both tests import run from codeweaver.main inside the test body so the patch targets are applied correctly at import time.
tests/unit/test_main.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • The two new tests are nearly identical aside from argument values; consider parametrizing them with pytest.mark.parametrize to reduce duplication and make it easier to add more transports in the future.
  • To make the intent clearer and avoid drift if run’s signature changes, you could build a shared kwargs dict for the call and the assertion in each test rather than repeating the same keyword arguments twice.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The two new tests are nearly identical aside from argument values; consider parametrizing them with `pytest.mark.parametrize` to reduce duplication and make it easier to add more transports in the future.
- To make the intent clearer and avoid drift if `run`’s signature changes, you could build a shared `kwargs` dict for the call and the assertion in each test rather than repeating the same keyword arguments twice.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click πŸ‘ or πŸ‘Ž on each comment and I'll use the feedback to improve your reviews.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds missing unit coverage for codeweaver.main.run()’s transport branching to ensure stdio vs streamable-http correctly delegates to the appropriate internal runner.

Changes:

  • Added an async unit test verifying transport="stdio" delegates to _run_stdio_server with the expected args.
  • Added an async unit test verifying transport="streamable-http" delegates to _run_http_server with the expected args.

πŸ’‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/unit/test_main.py

@pytest.mark.asyncio
@patch("codeweaver.main._run_http_server")
async def test_run_http_transport(mock_run_http):
Comment thread tests/unit/test_main.py
Comment on lines +71 to +78
mock_run_stdio.assert_called_once_with(
config_file=None,
project_path=None,
host="127.0.0.1",
port=8080,
verbose=True,
debug=False,
)
Comment thread tests/unit/test_main.py
Comment on lines +97 to +104
mock_run_http.assert_called_once_with(
config_file=None,
project_path=None,
host="0.0.0.0",
port=9090,
verbose=False,
debug=True,
)
Comment thread tests/unit/test_main.py
Comment on lines +55 to +58
@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server")
async def test_run_stdio_transport(mock_run_stdio):
"""Test that run() with transport='stdio' delegates to _run_stdio_server."""
@github-actions

Copy link
Copy Markdown
Contributor

PR Review - Test Coverage for Transport Conditional Branches

I've reviewed this PR and the code changes look good overall. Here's my detailed analysis:

Code Quality βœ…

Strengths:

  1. Clear Test Intent: Both test functions have descriptive names and docstrings that clearly explain what they're testing
  2. Proper Mocking: Uses @patch decorator correctly to mock internal server functions
  3. Comprehensive Parameter Testing: Tests verify that all parameters (config_file, project_path, host, port, verbose, debug) are correctly passed through to the delegated handlers
  4. Good Coverage: Tests both transport modes (stdio and streamable-http), covering the conditional logic in main.py:327-344

Implementation Details:

  • The tests correctly use pytest.mark.asyncio since run() is an async function
  • Mock assertions use assert_called_once_with() to ensure correct delegation
  • Different parameter values are used in each test to verify proper routing

Regarding Comment #2944228606

The Copilot comment suggests adding return type annotations (-> None) to satisfy ANN201. This suggestion is incorrect.

Looking at ruff.toml:179-197, the tests/*.py pattern explicitly ignores "ANN" rules, which includes ANN201. I verified this by running:

ruff check tests/unit/test_main.py --select ANN201
# Result: All checks passed!

The test file matches the tests/*.py glob pattern and is therefore exempt from annotation requirements.

CI Failures Analysis πŸ”

The PR has some failing CI checks, but they appear unrelated to the code changes:

  • Test / Test Python 3.13t (experimental) - Failed during "Setup Python environment with Mise" (environment setup issue)
  • Test / Test Python 3.14 - Failed during "Run tests with coverage" step
  • Test / Test Python 3.14t (experimental) - Failed during "Setup Python environment with Mise"

The lint check passed successfully, which confirms the code meets the project's style requirements.

Recommendation

The code changes are good and ready to merge once CI issues are resolved. The test implementation is solid and follows the existing test patterns in the codebase. No changes to return type annotations are needed.

The CI failures appear to be environmental/infrastructure issues rather than code quality problems. I recommend:

  1. Re-running the failed CI jobs
  2. If failures persist, investigating the Python setup issues separately from this PR

The test logic itself is sound and improves the codebase's test coverage as intended.


Review conducted by Claude Code

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Detailed Code Review

I've thoroughly reviewed the test implementation and it looks excellent. Here are my findings:

Test Implementation Analysis

test_run_stdio_transport (lines 55-78)

  • βœ… Correctly mocks _run_stdio_server
  • βœ… Verifies all 6 parameters are passed correctly
  • βœ… Uses realistic test values (127.0.0.1:8080, verbose=True, debug=False)

test_run_http_transport (lines 81-104)

  • βœ… Correctly mocks _run_http_server
  • βœ… Verifies all 6 parameters are passed correctly
  • βœ… Uses different test values to ensure proper routing (0.0.0.0:9090, verbose=False, debug=True)

Code Alignment with Existing Patterns

The tests follow the same patterns used in the existing test functions above them (lines 12-53):

  • Consistent use of @patch decorators
  • Same docstring style
  • Similar assertion patterns with assert_called_once_with

Security & Performance

No security or performance concerns. The tests are pure unit tests that mock external dependencies appropriately.

Addressing the Copilot Comment

Regarding the suggestion to add -> None return type annotations: This is not necessary. The ruff.toml configuration at lines 179-197 explicitly exempts tests/*.py from all ANN rules. I verified this with a direct lint check that passed.

Conclusion

Approve βœ… - The code is well-written, follows project conventions, and successfully adds the intended test coverage for the transport conditional logic in main.py:327-344. No changes needed.

@github-actions

Copy link
Copy Markdown
Contributor

Re: Comment about ANN201 return type annotations

The suggestion to add -> None return type annotations to the test functions is not necessary. Here's why:

  1. Ruff Configuration Exempts Tests: In ruff.toml lines 179-197, the pattern tests/*.py has "ANN" in its ignore list, which exempts all test files from annotation requirements (including ANN201).

  2. Verified with Linting: Running ruff check tests/unit/test_main.py --select ANN201 returns "All checks passed!"

  3. CI Lint Check Passed: The "Lint / Lint and Format" check passed successfully for this PR.

The test file tests/unit/test_main.py matches the tests/*.py glob pattern and is therefore correctly exempt from return type annotation requirements per the project's linting configuration.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

Thank you for adding test coverage for the transport conditional branches! This is valuable coverage for the main entry point. However, I've identified a few issues that need to be addressed:

πŸ”΄ Critical: Async Mock Issue

The tests are using @patch which creates synchronous MagicMock objects by default, but _run_stdio_server and _run_http_server are async functions. You should use AsyncMock instead.

Current code (tests/unit/test_main.py:56-57, 82-83):

@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server")
async def test_run_stdio_transport(mock_run_stdio):

Suggested fix:

from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server", new_callable=AsyncMock)
async def test_run_stdio_transport(mock_run_stdio):

Apply the same fix to test_run_http_transport at line 82-83.

This pattern is used elsewhere in the codebase - see tests/unit/cli/test_start_command.py for examples.

🟑 Observation: Unused Parameter in Implementation

While reviewing the tests, I noticed that _run_http_server has a port parameter (line 109 in main.py) that is never used in the function body:

  • The function uses mcp_port for the MCP server (line 153)
  • The function uses mgmt_port from settings for the management server (line 182)
  • The port parameter is completely ignored

In src/codeweaver/main.py:103-114:

async def _run_http_server(
    *,
    config_file: FilePath | None = None,
    project_path: Path | None = None,
    host: str = LOCALHOST,
    mcp_port: int = DEFAULT_MCP_PORT,
    port: int = DEFAULT_MANAGEMENT_PORT,  # ← This parameter is never used\!
    verbose: bool = False,
    debug: bool = False,
    # ...
)

This suggests either:

  1. The parameter should be removed as dead code, OR
  2. There's a bug where the parameter should be used but isn't

This is a separate issue from the tests themselves, but the tests would pass even with this unused parameter, which might not be ideal.

βœ… What the tests do well:

  • Clear test names and comprehensive docstrings
  • Good coverage of both transport modes (stdio and streamable-http)
  • Follows the existing test patterns in the file
  • Validates that parameters are passed through correctly

πŸ“ Recommendation:

  1. Fix the AsyncMock issue (required for tests to properly validate async behavior)
  2. Consider filing a separate issue about the unused port parameter in _run_http_server to clean up the implementation

Once the AsyncMock changes are made, these tests will provide solid coverage for the transport routing logic!

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review: Transport Branch Tests

Summary

This PR adds unit tests for the transport conditional branches in codeweaver.main.run(), improving test coverage for the main entry point logic. The new tests verify that the transport parameter correctly delegates to either _run_stdio_server or _run_http_server.

Test Quality: βœ… Excellent

Strengths:

  1. Clear test structure: Both tests follow a consistent pattern with descriptive names and docstrings
  2. Proper mocking: Uses @patch decorators to mock the internal server functions, avoiding actual server startup
  3. Comprehensive parameter validation: Verifies all parameters are passed correctly from run() to the internal handlers
  4. Async handling: Correctly uses @pytest.mark.asyncio for async test functions
  5. Good test data: Uses different port numbers and settings between the two tests to ensure proper delegation

Code Style: βœ… Compliant

  • Follows existing test patterns in test_main.py
  • Proper imports and formatting
  • Consistent with the codebase's testing conventions

Coverage Impact: βœ… Positive

The tests cover the previously untested conditional branch at main.py:327-344, which is the primary routing logic for transport selection. This is valuable regression protection.

CI Status: ⚠️ Note on Failures

The new tests themselves PASS in all Python versions (3.12, 3.13, 3.13t, 3.14, 3.14t). The CI failures are in unrelated integration/e2e tests:

  • tests/e2e/test_user_journeys.py
  • tests/integration/real/test_full_pipeline.py
  • tests/integration/real/test_search_behavior.py

These failures appear to be pre-existing flaky tests unrelated to this PR's changes. The PR only modifies tests/unit/test_main.py and doesn't touch any production code.

Potential Issue: Parameter Mapping (Informational)

While reviewing, I noticed a potential bug in the existing implementation (not introduced by this PR):

In main.py:341, when calling _run_http_server(), the code passes:

await _run_http_server(
    ...
    port=port,  # This maps to management port
    ...
)

However, _run_http_server() has TWO port parameters:

  • mcp_port: int = DEFAULT_MCP_PORT (9328) - for the MCP server
  • port: int = DEFAULT_MANAGEMENT_PORT (9329) - for the management server

The run() function's port parameter defaults to DEFAULT_MCP_PORT but gets passed as the management port. This might cause unexpected behavior when users specify a custom port. Consider opening a separate issue to clarify the port parameter semantics for HTTP transport mode.

Recommendation: βœ… Approve with Note

The tests are well-written and provide valuable coverage. The CI failures are unrelated to this PR. The parameter mapping issue I identified exists in the production code but is not introduced by this PR - the tests correctly validate the current implementation.

Suggested next steps:

  1. Merge this PR (tests are solid)
  2. Investigate/fix the flaky integration tests separately
  3. Consider opening an issue about the port parameter semantics in HTTP mode

@bashandbone

Copy link
Copy Markdown
Contributor Author

jules please address the below PR review issue

Code Review

Thank you for adding test coverage for the transport conditional branches! This is valuable coverage for the main entry point. However, I've identified a few issues that need to be addressed:

πŸ”΄ Critical: Async Mock Issue

The tests are using @patch which creates synchronous MagicMock objects by default, but _run_stdio_server and _run_http_server are async functions. You should use AsyncMock instead.

Current code (tests/unit/test_main.py:56-57, 82-83):

@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server")
async def test_run_stdio_transport(mock_run_stdio):

Suggested fix:

from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server", new_callable=AsyncMock)
async def test_run_stdio_transport(mock_run_stdio):

Apply the same fix to test_run_http_transport at line 82-83.

This pattern is used elsewhere in the codebase - see tests/unit/cli/test_start_command.py for examples.

🟑 Observation: Unused Parameter in Implementation

While reviewing the tests, I noticed that _run_http_server has a port parameter (line 109 in main.py) that is never used in the function body:

  • The function uses mcp_port for the MCP server (line 153)
  • The function uses mgmt_port from settings for the management server (line 182)
  • The port parameter is completely ignored

In src/codeweaver/main.py:103-114:

async def _run_http_server(
    *,
    config_file: FilePath | None = None,
    project_path: Path | None = None,
    host: str = LOCALHOST,
    mcp_port: int = DEFAULT_MCP_PORT,
    port: int = DEFAULT_MANAGEMENT_PORT,  # ← This parameter is never used\!
    verbose: bool = False,
    debug: bool = False,
    # ...
)

This suggests either:

  1. The parameter should be removed as dead code, OR
  2. There's a bug where the parameter should be used but isn't

This is a separate issue from the tests themselves, but the tests would pass even with this unused parameter, which might not be ideal.

βœ… What the tests do well:

  • Clear test names and comprehensive docstrings
  • Good coverage of both transport modes (stdio and streamable-http)
  • Follows the existing test patterns in the file
  • Validates that parameters are passed through correctly

πŸ“ Recommendation:

  1. Fix the AsyncMock issue (required for tests to properly validate async behavior)
  2. Consider filing a separate issue about the unused port parameter in _run_http_server to clean up the implementation

Once the AsyncMock changes are made, these tests will provide solid coverage for the transport routing logic!

@google-labs-jules

Copy link
Copy Markdown
Contributor

jules please address the below PR review issue

Code Review

Thank you for adding test coverage for the transport conditional branches! This is valuable coverage for the main entry point. However, I've identified a few issues that need to be addressed:

πŸ”΄ Critical: Async Mock Issue

The tests are using @patch which creates synchronous MagicMock objects by default, but _run_stdio_server and _run_http_server are async functions. You should use AsyncMock instead.

Current code (tests/unit/test_main.py:56-57, 82-83):

@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server")
async def test_run_stdio_transport(mock_run_stdio):

Suggested fix:

from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
@patch("codeweaver.main._run_stdio_server", new_callable=AsyncMock)
async def test_run_stdio_transport(mock_run_stdio):

Apply the same fix to test_run_http_transport at line 82-83.

This pattern is used elsewhere in the codebase - see tests/unit/cli/test_start_command.py for examples.

🟑 Observation: Unused Parameter in Implementation

While reviewing the tests, I noticed that _run_http_server has a port parameter (line 109 in main.py) that is never used in the function body:

  • The function uses mcp_port for the MCP server (line 153)
  • The function uses mgmt_port from settings for the management server (line 182)
  • The port parameter is completely ignored

In src/codeweaver/main.py:103-114:

async def _run_http_server(
    *,
    config_file: FilePath | None = None,
    project_path: Path | None = None,
    host: str = LOCALHOST,
    mcp_port: int = DEFAULT_MCP_PORT,
    port: int = DEFAULT_MANAGEMENT_PORT,  # ← This parameter is never used\!
    verbose: bool = False,
    debug: bool = False,
    # ...
)

This suggests either:

  1. The parameter should be removed as dead code, OR
  2. There's a bug where the parameter should be used but isn't

This is a separate issue from the tests themselves, but the tests would pass even with this unused parameter, which might not be ideal.

βœ… What the tests do well:

  • Clear test names and comprehensive docstrings
  • Good coverage of both transport modes (stdio and streamable-http)
  • Follows the existing test patterns in the file
  • Validates that parameters are passed through correctly

πŸ“ Recommendation:

  1. Fix the AsyncMock issue (required for tests to properly validate async behavior)
  2. Consider filing a separate issue about the unused port parameter in _run_http_server to clean up the implementation

Once the AsyncMock changes are made, these tests will provide solid coverage for the transport routing logic!

Thank you for the review! I have updated the @patch decorators for both test_run_stdio_transport and test_run_http_transport to use new_callable=AsyncMock, correctly matching the mocked async functions _run_stdio_server and _run_http_server.

Also, I acknowledge the observation regarding the unused port parameter in _run_http_server. As recommended, that cleanup has been left out of this testing-focused PR and should be filed as a separate issue.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
@bashandbone
Adam Poulemanos (bashandbone) merged commit 7340c96 into main Mar 17, 2026
15 of 20 checks passed
@bashandbone
Adam Poulemanos (bashandbone) deleted the test/add-main-run-conditional-branch-tests-12817532639525235297 branch March 17, 2026 18:39
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.

2 participants