Skip to content

Conversation

@tisnik
Copy link
Contributor

@tisnik tisnik commented Aug 10, 2025

Description

Use proper Request object to test REST API endpoints handlers

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Summary by CodeRabbit

  • Tests
    • Updated unit tests for query and streaming query endpoints to use properly constructed request objects, improving test accuracy and reliability. No changes to test logic or assertions.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 10, 2025

Warning

Rate limit exceeded

@tisnik has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 8 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c88b383 and 223e3b4.

📒 Files selected for processing (4)
  • tests/unit/app/endpoints/test_config.py (3 hunks)
  • tests/unit/app/endpoints/test_info.py (2 hunks)
  • tests/unit/app/endpoints/test_metrics.py (2 hunks)
  • tests/unit/app/endpoints/test_root.py (1 hunks)

Walkthrough

The test files for query and streaming query endpoint handlers were updated to replace None arguments with properly constructed request objects (QueryRequest or Request) in test cases. This ensures that all tests simulate valid request scenarios without altering test logic or assertions. No changes were made to public APIs.

Changes

Cohort / File(s) Change Summary
Unit Tests: Query Endpoint
tests/unit/app/endpoints/test_query.py
Updated the test test_query_endpoint_handler_configuration_not_loaded to use a valid QueryRequest object instead of None when calling the handler, ensuring the test simulates a proper request scenario.
Unit Tests: Streaming Query Endpoint
tests/unit/app/endpoints/test_streaming_query.py
Modified multiple tests to pass a valid Request object (with minimal HTTP scope) instead of None as the first argument to the streaming query endpoint handler, maintaining consistent request simulation across all relevant test cases.

Sequence Diagram(s)

No sequence diagram generated, as the changes are limited to test input construction and do not alter control flow or introduce new features.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Poem

In the warren of tests, we hop with delight,
Swapping out None for requests that are right.
With queries and streams, our coverage is strong,
Each rabbit ensures the mocks all belong.
Now every test passes, so fluffy and bright!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
  • 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.

Support

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

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 generate unit tests to generate unit tests for 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.

@tisnik tisnik force-pushed the use-proper-request-object-to-test-endpoints branch from e286b59 to c88b383 Compare August 10, 2025 07:02
Copy link
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: 2

♻️ Duplicate comments (5)
tests/unit/app/endpoints/test_streaming_query.py (5)

153-157: Minimal Request construction is fine here too

Same note as above—this is correct, and a dummy_request fixture could reduce repetition.


269-273: Request construction: OK

No functional issues. Consider reusing a dummy_request fixture to reduce duplication across tests.


1277-1281: Request construction: OK

Minimal scope is sufficient since _request is unused. Can be replaced by a fixture for DRY.


1324-1328: Request construction: OK

Repeated pattern—consider a single helper fixture to reduce duplication.


1369-1373: Request construction: OK

Same DRY suggestion as above.

🧹 Nitpick comments (2)
tests/unit/app/endpoints/test_query.py (1)

72-72: Use a tuple (or MOCK_AUTH) for the auth parameter for type consistency

Auth is modeled as a tuple by the handler. Passing a tuple (or the already-declared MOCK_AUTH) improves consistency.

-        await query_endpoint_handler(query_request, auth=["test-user", "", "token"])
+        await query_endpoint_handler(query_request, auth=MOCK_AUTH)
tests/unit/app/endpoints/test_streaming_query.py (1)

121-125: Constructing a minimal Request is correct; consider a helper to avoid repetition

Using Request(scope={"type": "http"}) is sufficient since the handler ignores _request. To DRY repeated construction, add a small fixture:

# conftest.py or in this module
import pytest
from fastapi import Request

@pytest.fixture
def dummy_request():
    return Request(scope={"type": "http"})

Then use dummy_request in tests to reduce duplication.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a23527b and c88b383.

📒 Files selected for processing (2)
  • tests/unit/app/endpoints/test_query.py (1 hunks)
  • tests/unit/app/endpoints/test_streaming_query.py (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/unit/app/endpoints/test_query.py (2)
src/models/requests.py (1)
  • QueryRequest (70-212)
src/app/endpoints/query.py (1)
  • query_endpoint_handler (69-126)
tests/unit/app/endpoints/test_streaming_query.py (1)
src/app/endpoints/streaming_query.py (1)
  • streaming_query_endpoint_handler (383-465)
🔇 Additional comments (6)
tests/unit/app/endpoints/test_query.py (1)

69-71: Good switch to a real QueryRequest

Creating a minimal valid QueryRequest here is correct and keeps the test realistic without adding complexity.

tests/unit/app/endpoints/test_streaming_query.py (5)

11-11: Importing Request is necessary for constructing real FastAPI Request objects

This import aligns with the new usage. LGTM.


275-277: Passing the constructed Request is correct

This aligns the signature to the handler. LGTM.


1283-1283: Handler invocation with Request looks good

This enables proper context for the streaming handler. LGTM.


1330-1331: LGTM

Properly passing Request alongside query_request.


1375-1376: LGTM

Correct usage with the new signature.

Comment on lines 127 to 131
with pytest.raises(HTTPException) as e:
await streaming_query_endpoint_handler(None, query_request, auth=MOCK_AUTH)
await streaming_query_endpoint_handler(request, query_request, auth=MOCK_AUTH)
assert e.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert e.detail["response"] == "Configuration is not loaded"

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix pytest.raises assertions (must assert outside the context and use e.value)

Asserting on e.status_code/e.detail inside the with-block and without using e.value is incorrect and can raise AttributeError. Move assertions outside and use e.value.

with pytest.raises(HTTPException) as e:
    await streaming_query_endpoint_handler(request, query_request, auth=MOCK_AUTH)

assert e.value.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert e.value.detail["response"] == "Configuration is not loaded"
🤖 Prompt for AI Agents
In tests/unit/app/endpoints/test_streaming_query.py around lines 127 to 131, the
assertions on the HTTPException are incorrectly placed inside the pytest.raises
context and use e instead of e.value. Move the assertions outside the with-block
and change them to use e.value.status_code and e.value.detail to correctly
access the exception attributes.

Comment on lines 159 to 163
with pytest.raises(HTTPException) as e:
await streaming_query_endpoint_handler(None, query_request, auth=MOCK_AUTH)
await streaming_query_endpoint_handler(request, query_request, auth=MOCK_AUTH)
assert e.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert e.detail["response"] == "Configuration is not loaded"

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Simulate connection error at the correct call and fix assertions and expected message

Two issues:

  • APIConnectionError should be raised by client.models.list(), not by accessing client.models.
  • Inside-with assertions and using e instead of e.value are incorrect.
  • The expected message for connection failures should be “Unable to connect to Llama Stack”.
# raise the error when listing models
mock_client.models.list.side_effect = APIConnectionError(request=query_request)

with pytest.raises(HTTPException) as e:
    await streaming_query_endpoint_handler(request, query_request, auth=MOCK_AUTH)

assert e.value.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert e.value.detail["response"] == "Unable to connect to Llama Stack"

Also, you can remove one of the duplicate patches:

# Keep just one
mocker.patch("client.AsyncLlamaStackClientHolder.get_client", return_value=mock_client)
🤖 Prompt for AI Agents
In tests/unit/app/endpoints/test_streaming_query.py around lines 159 to 163, fix
the test to simulate the APIConnectionError correctly by setting the side_effect
on mock_client.models.list() instead of accessing client.models. Move the
assertions outside the with block and use e.value for accessing the exception.
Update the expected error message to "Unable to connect to Llama Stack". Also,
remove the duplicate patch for AsyncLlamaStackClientHolder.get_client, keeping
only one instance.

@tisnik tisnik merged commit d1f42c3 into lightspeed-core:main Aug 10, 2025
17 of 18 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