Thanks to visit codestin.com
Credit goes to github.com

Skip to content

LCORE-381: new unit tests for client.py and models endpoints#287

Merged
tisnik merged 2 commits into
lightspeed-core:mainfrom
tisnik:lcore-381-new-unit-tests
Jul 25, 2025
Merged

LCORE-381: new unit tests for client.py and models endpoints#287
tisnik merged 2 commits into
lightspeed-core:mainfrom
tisnik:lcore-381-new-unit-tests

Conversation

@tisnik

@tisnik tisnik commented Jul 25, 2025

Copy link
Copy Markdown
Contributor

Description

LCORE-381: new unit tests for client.py and models endpoints

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

Related Tickets & Documents

  • Related Issue #LCORE-381

Summary by CodeRabbit

  • Tests
    • Added new tests to verify error handling when the /models endpoint cannot connect to Llama Stack.
    • Introduced tests to ensure proper behavior of client retrieval methods before and after initialization.
    • Enhanced existing tests to assert correct client availability after loading.

@coderabbitai

coderabbitai Bot commented Jul 25, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

New unit tests were added to verify error handling and initialization logic in the /models REST API endpoint and the LlamaStack client holders. The tests cover scenarios where the client is uninitialized or encounters connection errors, and assert that appropriate exceptions and messages are raised.

Changes

File(s) Change Summary
tests/unit/app/endpoints/test_models.py Added a test for models_endpoint_handler handling APIConnectionError; minor mocking update.
tests/unit/test_client.py Added tests for get_client method on uninitialized and initialized LlamaStack client holders.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

In the warren where the test bunnies play,
New checks for errors now hop on their way.
If Llama Stack stumbles or clients aren’t set,
Our tests will catch it—no need to fret!
With every assertion, our code grows robust—
A rabbit’s review, in quality we trust! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between baacb1d and 6494660.

📒 Files selected for processing (2)
  • tests/unit/app/endpoints/test_models.py (3 hunks)
  • tests/unit/test_client.py (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/unit/app/endpoints/test_models.py
  • tests/unit/test_client.py
✨ 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.
    • @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 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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

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

162-210: Comprehensive test for API connection error handling.

The new test effectively covers the scenario where LlamaStack client raises an APIConnectionError and verifies that the endpoint handler properly converts it to an HTTP 500 exception. The test setup is thorough and the assertions are correct.

However, there are a few minor improvements that could be made:

  1. The test configuration setup is duplicated across multiple tests - consider extracting it to a fixture
  2. The assertion statements after pytest.raises (lines 209-210) will never execute due to the context manager behavior
    with pytest.raises(HTTPException) as e:
        models_endpoint_handler(request)
-        assert e.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
-        assert e.detail["response"] == "Unable to connect to Llama Stack"
+    
+    assert e.value.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR  
+    assert e.value.detail["response"] == "Unable to connect to Llama Stack"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6459aac and baacb1d.

📒 Files selected for processing (2)
  • tests/unit/app/endpoints/test_models.py (3 hunks)
  • tests/unit/test_client.py (5 hunks)
🧰 Additional context used
🪛 GitHub Actions: Black
tests/unit/app/endpoints/test_models.py

[error] 1-1: Black formatting check failed. File would be reformatted. Run 'black --write' to fix code style issues.

🪛 GitHub Actions: Python linter
tests/unit/app/endpoints/test_models.py

[error] 10-10: pylint: third party import "llama_stack_client.APIConnectionError" should be placed before first party imports (wrong-import-order)

tests/unit/test_client.py

[error] 27-27: pylint: Line too long (103/100) (line-too-long)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-pr
🔇 Additional comments (3)
tests/unit/app/endpoints/test_models.py (1)

145-145: Good consistency improvement.

Using mocker.Mock() instead of Mock() improves consistency with the pytest-mock pattern used throughout the test suite.

tests/unit/test_client.py (2)

9-18: Excellent test for uninitialized client error handling.

This test properly verifies that calling get_client() on an uninitialized LlamaStackClientHolder raises a RuntimeError with the expected message. The regex pattern correctly escapes the parentheses in the error message.


44-45: Good additions to verify client retrieval after initialization.

These additions properly test that get_client() returns a valid client instance after successful initialization. This complements the new tests for uninitialized clients and provides comprehensive coverage of the get_client() method behavior.

Also applies to: 60-61, 93-94, 109-110

Comment thread tests/unit/app/endpoints/test_models.py Outdated
Comment thread tests/unit/test_client.py
Comment on lines +21 to +32
def test_async_client_get_client_method() -> None:
"""Test how get_client method works for unitialized client."""
client = AsyncLlamaStackClientHolder()

with pytest.raises(
RuntimeError,
match="AsyncLlamaStackClient has not been initialised. Ensure 'load\\(..\\)' has been called.",
):
client.get_client()

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.

⚠️ Potential issue

Fix line length and improve test documentation.

The test logic is correct, but there's a line length violation and a minor documentation issue.

def test_async_client_get_client_method() -> None:
-    """Test how get_client method works for unitialized client."""
+    """Test how get_client method works for uninitialized async client."""
    client = AsyncLlamaStackClientHolder()

    with pytest.raises(
        RuntimeError,
-        match="AsyncLlamaStackClient has not been initialised. Ensure 'load\\(..\\)' has been called.",
+        match="AsyncLlamaStackClient has not been initialised. "
+              "Ensure 'load\\(..\\)' has been called.",
    ):
        client.get_client()
📝 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_async_client_get_client_method() -> None:
"""Test how get_client method works for unitialized client."""
client = AsyncLlamaStackClientHolder()
with pytest.raises(
RuntimeError,
match="AsyncLlamaStackClient has not been initialised. Ensure 'load\\(..\\)' has been called.",
):
client.get_client()
def test_async_client_get_client_method() -> None:
"""Test how get_client method works for uninitialized async client."""
client = AsyncLlamaStackClientHolder()
with pytest.raises(
RuntimeError,
match="AsyncLlamaStackClient has not been initialised. "
"Ensure 'load\\(..\\)' has been called.",
):
client.get_client()
🧰 Tools
🪛 GitHub Actions: Python linter

[error] 27-27: pylint: Line too long (103/100) (line-too-long)

🤖 Prompt for AI Agents
In tests/unit/test_client.py around lines 21 to 29, the test function's
docstring is brief and the line with the pytest.raises call exceeds the
recommended line length. Expand the docstring to better describe the test
purpose and split the long line into multiple shorter lines to comply with line
length standards.

@tisnik tisnik force-pushed the lcore-381-new-unit-tests branch from baacb1d to 6494660 Compare July 25, 2025 07:10
@tisnik tisnik merged commit 4bbda24 into lightspeed-core:main Jul 25, 2025
17 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