Skip to content

RHIDP-14000: update unit tests for shields#1872

Merged
tisnik merged 2 commits into
lightspeed-core:mainfrom
Jdubrick:update-shields-tests
Jun 8, 2026
Merged

RHIDP-14000: update unit tests for shields#1872
tisnik merged 2 commits into
lightspeed-core:mainfrom
Jdubrick:update-shields-tests

Conversation

@Jdubrick

@Jdubrick Jdubrick commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Description

  • Fixes some asserts that were not firing because an exception would be raised before they executed
  • Adds 2 new unit tests to improve coverage

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
  • Benchmarks improvement

Tools used to create PR

Identify any AI code assistants used in this PR (for transparency and review context)

  • Assisted-by: Claude
  • Generated by: (e.g., tool name and version; N/A if not used)

Related Tickets & Documents

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

Summary by CodeRabbit

  • Tests
    • Improved test coverage for the /shields REST API endpoint, enhancing error handling validation across multiple failure scenarios including configuration issues, connection failures, and unexpected exceptions.
    • Added tests for edge cases including malformed shield data handling.

Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Unit tests for the /shields REST API endpoint were refined with more specific assertions on existing error scenarios and expanded with two new test cases. Error-handling tests now validate exact HTTP status codes and error message content. New tests cover unexpected exception propagation and handling of malformed shield objects.

Changes

Shields Endpoint Test Coverage

Layer / File(s) Summary
Enhanced assertions for existing error scenarios
tests/unit/app/endpoints/test_shields.py
Configuration not loaded, empty shields list retrieval, and LlamaStack connection error tests now assert specific HTTP status codes, exact error response strings, and expected error causes.
New test cases for unexpected exceptions and malformed objects
tests/unit/app/endpoints/test_shields.py
Two new async tests added: one validates that unexpected shield client exceptions propagate as RuntimeError, and another verifies that malformed/minimal shield objects are parsed and returned in a successful ShieldsResponse with the correct identifier and list length.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: updating unit tests for the shields endpoint, with specific reference to the ticket number (RHIDP-14000).

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

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

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/unit/app/endpoints/test_shields.py (1)

243-309: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Consider patching the configuration for test isolation.

Unlike other tests in this file (e.g., lines 27, 88, 161), this test creates an AppConfig instance (lines 291-292) but doesn't patch it into the endpoint's configuration module. While the test may work if the module already has a valid configuration, this makes the test dependent on external state.

Recommended fix to match other test patterns

Add after line 292:

 cfg = AppConfig()
 cfg.init_from_dict(config_dict)
+
+mocker.patch("app.endpoints.shields.configuration", cfg)

Then move the client holder patching (lines 286-289) after the configuration patch to maintain a consistent setup order.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/app/endpoints/test_shields.py` around lines 243 - 309, The test
creates an AppConfig instance (cfg.init_from_dict) but doesn't inject it into
the endpoint module, leaving the test dependent on external module state; set
the endpoint module's config to the new cfg (e.g. assign cfg to
app.endpoints.shields.cfg or whatever module-level config variable is used by
shields_endpoint_handler) immediately after cfg.init_from_dict, and then move
the AsyncLlamaStackClientHolder patching (mock_client_holder) to after that
assignment so the mocked client uses the test config; ensure you reference
AppConfig, cfg, AsyncLlamaStackClientHolder and shields_endpoint_handler when
making the changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/unit/app/endpoints/test_shields.py`:
- Around line 440-496: The test
test_shields_endpoint_handler_malformed_shield_objects uses
mocker.patch("client.AsyncLlamaStackClientHolder.get_client") but should follow
the file's consistent pattern; change the patch to
mocker.patch("app.endpoints.shields.AsyncLlamaStackClientHolder") (matching the
earlier tests) and set its return_value so that .get_client() returns
mock_client, and replace the generic mock_config patch of
app.endpoints.shields.configuration with the real cfg object already created, so
the test uses AsyncLlamaStackClientHolder -> get_client -> mock_client and the
actual cfg.

---

Outside diff comments:
In `@tests/unit/app/endpoints/test_shields.py`:
- Around line 243-309: The test creates an AppConfig instance
(cfg.init_from_dict) but doesn't inject it into the endpoint module, leaving the
test dependent on external module state; set the endpoint module's config to the
new cfg (e.g. assign cfg to app.endpoints.shields.cfg or whatever module-level
config variable is used by shields_endpoint_handler) immediately after
cfg.init_from_dict, and then move the AsyncLlamaStackClientHolder patching
(mock_client_holder) to after that assignment so the mocked client uses the test
config; ensure you reference AppConfig, cfg, AsyncLlamaStackClientHolder and
shields_endpoint_handler when making the changes.
🪄 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: ASSERTIVE

Plan: Pro

Run ID: a3c03fb8-dcdb-484b-ad2d-20e9514fb9c4

📥 Commits

Reviewing files that changed from the base of the PR and between d464fbc and 1a0dd23.

📒 Files selected for processing (1)
  • tests/unit/app/endpoints/test_shields.py
📜 Review details
⏰ 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). (17)
  • GitHub Check: check_dependencies
  • GitHub Check: spectral
  • GitHub Check: Pyright
  • GitHub Check: bandit
  • GitHub Check: integration_tests (3.12)
  • GitHub Check: unit_tests (3.12)
  • GitHub Check: build-pr
  • GitHub Check: Pylinter
  • GitHub Check: mypy
  • GitHub Check: E2E: server mode / ci / group 2
  • GitHub Check: E2E: library mode / ci / group 2
  • GitHub Check: E2E: server mode / ci / group 1
  • GitHub Check: E2E: server mode / ci / group 3
  • GitHub Check: E2E: library mode / ci / group 1
  • GitHub Check: E2E: library mode / ci / group 3
  • GitHub Check: E2E Tests for Lightspeed Evaluation job
  • GitHub Check: Konflux kflux-prd-rh02 / lightspeed-stack-on-pull-request
🧰 Additional context used
📓 Path-based instructions (1)
tests/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

tests/**/*.py: Use pytest for all unit and integration tests; do not use unittest
Use pytest.mark.asyncio marker for async tests

Files:

  • tests/unit/app/endpoints/test_shields.py
🧠 Learnings (3)
📓 Common learnings
Learnt from: max-svistunov
Repo: lightspeed-core/lightspeed-stack PR: 1580
File: docs/design/llama-stack-config-merge/poc-results/library-mode/synthesized-run.yaml:107-110
Timestamp: 2026-05-20T08:09:34.319Z
Learning: In the lightspeed-stack project (LCORE-836 unified config), the `provider_shield_id` for a Llama Guard safety shield entry must be a guard model identifier (e.g., `meta-llama/Llama-Guard-3-8B`), not a chat model id like `openai/gpt-4o-mini`. Using a chat model id there only means the native_override key landed — it does not mean the safety shield is actually gating queries. E2E tests for the implementation JIRA must exercise a real Llama Guard model to validate the shield.
📚 Learning: 2026-05-20T08:09:34.319Z
Learnt from: max-svistunov
Repo: lightspeed-core/lightspeed-stack PR: 1580
File: docs/design/llama-stack-config-merge/poc-results/library-mode/synthesized-run.yaml:107-110
Timestamp: 2026-05-20T08:09:34.319Z
Learning: In the lightspeed-stack project (LCORE-836 unified config), the `provider_shield_id` for a Llama Guard safety shield entry must be a guard model identifier (e.g., `meta-llama/Llama-Guard-3-8B`), not a chat model id like `openai/gpt-4o-mini`. Using a chat model id there only means the native_override key landed — it does not mean the safety shield is actually gating queries. E2E tests for the implementation JIRA must exercise a real Llama Guard model to validate the shield.

Applied to files:

  • tests/unit/app/endpoints/test_shields.py
📚 Learning: 2026-05-06T06:57:52.173Z
Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-05-06T06:57:52.173Z
Learning: Applies to src/app/**/*.py : Use FastAPI `HTTPException` with appropriate status codes for API endpoints and handle `APIConnectionError` from Llama Stack

Applied to files:

  • tests/unit/app/endpoints/test_shields.py
🔇 Additional comments (5)
tests/unit/app/endpoints/test_shields.py (5)

41-42: LGTM!


238-239: LGTM!


388-437: LGTM!


440-496: LGTM!


306-308: Don’t assume "Connection error" is in detail["cause"] without checking the local APIConnectionError string formatting.
The attempted verification failed because llama_stack_client isn’t importable in this environment, so str(APIConnectionError(request=None)) can’t be validated from the provided script; inspect the repo’s APIConnectionError implementation/__str__ (the exact type used by the endpoint) before relying on that substring.

Comment thread tests/unit/app/endpoints/test_shields.py
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
@Jdubrick Jdubrick changed the title test: update unit tests for shields RHIDP-14000: update unit tests for shields Jun 8, 2026

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

LGTM

@tisnik tisnik merged commit 6f0cb03 into lightspeed-core:main Jun 8, 2026
29 of 32 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.

2 participants