Skip to content

🧪 QA: Add test for load_knowledge_base edge case#127

Open
daggerstuff wants to merge 1 commit intostagingfrom
test/load-knowledge-base-d7e2f-5471369406424211851
Open

🧪 QA: Add test for load_knowledge_base edge case#127
daggerstuff wants to merge 1 commit intostagingfrom
test/load-knowledge-base-d7e2f-5471369406424211851

Conversation

@daggerstuff
Copy link
Copy Markdown
Owner

@daggerstuff daggerstuff commented Apr 2, 2026

💡 What: Added TestKnowledgeBase to test_service.py with cases for load_knowledge_base method (available, not available, exception cases).
🎯 Why: Covers missing edge cases and improves coverage for the EmbeddingAgentService.
✅ Verification: Runs successfully via pytest.


PR created automatically by Jules for task 5471369406424211851 started by @daggerstuff

Summary by Sourcery

Add tests for EmbeddingAgentService knowledge base loading behavior across availability and error scenarios.

Documentation:

  • Document a QA pattern for patching module-level flags across multiple namespaces in the Jules QA guide.

Tests:

  • Add TestKnowledgeBase suite covering load_knowledge_base when the clinical embedder is unavailable, available, and raising exceptions.

Summary by cubic

Add tests for EmbeddingAgentService.load_knowledge_base to cover when the clinical embedder is unavailable, available, and when it raises an exception. Also update .Jules/qa.md with guidance on patching the CLINICAL_EMBEDDER_AVAILABLE flag in both api.embedding_agent.service and app.api.embedding_agent.service.

Written for commit 7186ed3. Summary will update on new commits.

Summary by CodeRabbit

  • Tests

    • Enhanced test coverage for embedding agent service with additional test scenarios for knowledge base loading.
  • Documentation

    • Updated QA checklist with testing guidelines for module-level patching requirements.

Co-authored-by: daggerstuff <261005129+daggerstuff@users.noreply.github.com>
@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.

Copilot AI review requested due to automatic review settings April 2, 2026 02:01
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 2, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
ai Error Error Apr 2, 2026 2:01am

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Apr 2, 2026

Reviewer's Guide

Adds focused tests for EmbeddingAgentService.load_knowledge_base covering availability, success, and exception paths, and documents a QA pattern for patching module-level flags used by EmbeddingAgentService.

Sequence diagram for EmbeddingAgentService.load_knowledge_base test coverage

sequenceDiagram
    participant TestKnowledgeBase
    participant PatchPrimaryFlag as Patch_api_embedding_agent_flag
    participant PatchFallbackFlag as Patch_app_api_embedding_agent_flag
    participant EmbeddingAgentService
    participant ModuleFlag as EmbeddingAgentModuleFlag

    TestKnowledgeBase->>PatchPrimaryFlag: apply_patch(create_true)
    TestKnowledgeBase->>PatchFallbackFlag: apply_patch(create_true)
    TestKnowledgeBase->>EmbeddingAgentService: instantiate_service()

    rect rgb(230,230,255)
        TestKnowledgeBase->>ModuleFlag: set_available_true()
        TestKnowledgeBase->>EmbeddingAgentService: load_knowledge_base()
        EmbeddingAgentService->>ModuleFlag: read_available_flag()
        EmbeddingAgentService-->>TestKnowledgeBase: return_loaded_knowledge_base()
    end

    rect rgb(230,255,230)
        TestKnowledgeBase->>ModuleFlag: set_available_false()
        TestKnowledgeBase->>EmbeddingAgentService: load_knowledge_base()
        EmbeddingAgentService->>ModuleFlag: read_available_flag()
        EmbeddingAgentService-->>TestKnowledgeBase: return_none_or_skip()
    end

    rect rgb(255,230,230)
        TestKnowledgeBase->>ModuleFlag: set_available_true()
        TestKnowledgeBase->>EmbeddingAgentService: load_knowledge_base()
        EmbeddingAgentService->>ModuleFlag: read_available_flag()
        EmbeddingAgentService->>EmbeddingAgentService: raise_internal_exception()
        EmbeddingAgentService-->>TestKnowledgeBase: propagate_exception()
    end
Loading

Class diagram for EmbeddingAgentService and new TestKnowledgeBase tests

classDiagram
    class EmbeddingAgentService {
        +bool knowledge_base_available_flag
        +load_knowledge_base() KnowledgeBase
    }

    class EmbeddingAgentModuleFlag {
        +bool knowledge_base_available
    }

    class TestKnowledgeBase {
        +setup_method() void
        +test_load_knowledge_base_available() void
        +test_load_knowledge_base_not_available() void
        +test_load_knowledge_base_exception() void
    }

    TestKnowledgeBase ..> EmbeddingAgentService : uses
    EmbeddingAgentService ..> EmbeddingAgentModuleFlag : reads
Loading

File-Level Changes

Change Details Files
Add unit tests for EmbeddingAgentService.load_knowledge_base covering edge cases around the clinical embedder availability and error handling.
  • Introduce TestKnowledgeBase test class in test_service.py for load_knowledge_base behavior.
  • Test behavior when CLINICAL_EMBEDDER_AVAILABLE is False, asserting no knowledge is loaded and return value is 0.
  • Test behavior when CLINICAL_EMBEDDER_AVAILABLE is True, mocking _initialize_clinical_embedder and process_all_knowledge to return two items and asserting internal state and return value.
  • Test exception path where process_all_knowledge raises, asserting graceful handling and zero return value.
  • Use patch and MagicMock to control module-level CLINICAL_EMBEDDER_AVAILABLE flag and embedder behavior across different module import paths.
api/embedding_agent/tests/test_service.py
Document QA guidance for mocking module-level variables used by EmbeddingAgentService in tests.
  • Add a QA note describing the need to patch module-level flags like CLINICAL_EMBEDDER_AVAILABLE across multiple namespaces depending on test runner paths.
  • Specify use of patch with create=True on app.api.embedding_agent.service and a direct patch on api.embedding_agent.service for defensive mocking.
.Jules/qa.md

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

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 2, 2026

📝 Walkthrough

Walkthrough

Added test coverage for EmbeddingAgentService.load_knowledge_base() method with three test scenarios using mocked patches of module-level flags, and documented the module-level patching requirements in a QA checklist entry.

Changes

Cohort / File(s) Summary
Documentation
.Jules/qa.md
Added QA checklist entry (2026-04-02) documenting defensive patching requirements for EmbeddingAgentService module-level flags across import namespaces, including create=True fallback strategy.
Test Coverage
api/embedding_agent/tests/test_service.py
Added TestKnowledgeBase class with test coverage for load_knowledge_base() method across three scenarios: unavailable embedder (returns 0), successful knowledge loading (returns count and updates state), and exception handling (returns 0). Imports MagicMock, patch, and module reference for defensive patching.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 With patches we weave through each namespace with care,
Test scenarios bloom in the module-patched air,
Three branches of logic, all covered just right,
Our knowledge base loads through the test-driven light!
✨🔧

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title mentions adding tests for load_knowledge_base edge cases, which directly aligns with the main change of adding TestKnowledgeBase test coverage for EmbeddingAgentService.load_knowledge_base().
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/load-knowledge-base-d7e2f-5471369406424211851

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.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

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 repeated nested patching of CLINICAL_EMBEDDER_AVAILABLE across api.embedding_agent.service and app.api.embedding_agent.service makes the tests a bit noisy; consider extracting a small helper or fixture (e.g., with_clinical_embedder_available) or using ExitStack to centralize and reuse this pattern.
  • To make the tests more intention-revealing, you could avoid directly manipulating the private attributes _clinical_embedder and _knowledge_items by either exposing a small test hook or verifying behavior via the public interface (e.g., inspecting the return values of methods that depend on the loaded knowledge base).
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The repeated nested patching of `CLINICAL_EMBEDDER_AVAILABLE` across `api.embedding_agent.service` and `app.api.embedding_agent.service` makes the tests a bit noisy; consider extracting a small helper or fixture (e.g., `with_clinical_embedder_available`) or using `ExitStack` to centralize and reuse this pattern.
- To make the tests more intention-revealing, you could avoid directly manipulating the private attributes `_clinical_embedder` and `_knowledge_items` by either exposing a small test hook or verifying behavior via the public interface (e.g., inspecting the return values of methods that depend on the loaded knowledge base).

Fix all in Cursor


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.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7186ed3261

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


def test_load_knowledge_base_available(self, config: EmbeddingAgentConfig):
"""Test loading when clinical embedder is available."""
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Patch a real module path for clinical embedder flag

The target app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE is not importable in this repository, and patch(..., create=True) does not create missing modules—it only allows missing attributes. As a result, this test raises ModuleNotFoundError: No module named 'app' before reaching the assertions, so the new knowledge-base coverage fails in the default test environment. Patch only the importable module (api.embedding_agent.service...) or guard the alternate namespace without importing a nonexistent package.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds unit test coverage for EmbeddingAgentService.load_knowledge_base() edge cases (clinical embedder unavailable, successful load, and exception during load) and documents a QA pattern for patching module-level flags.

Changes:

  • Added TestKnowledgeBase test cases for load_knowledge_base() behaviors.
  • Added a QA note describing how to patch module-level availability flags in tests.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
api/embedding_agent/tests/test_service.py Adds tests covering load_knowledge_base() return values and state updates under different conditions.
.Jules/qa.md Adds a documented pattern for mocking module-level variables in tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +304 to +323
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
service = EmbeddingAgentService(config)
service._clinical_embedder = MagicMock()
service._clinical_embedder.process_all_knowledge.return_value = (["item1", "item2"], None)

assert service.load_knowledge_base() == 2
assert service._knowledge_items == ["item1", "item2"]

def test_load_knowledge_base_exception(self, config: EmbeddingAgentConfig):
"""Test exception handling during knowledge base loading."""
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
service = EmbeddingAgentService(config)
service._clinical_embedder = MagicMock()
service._clinical_embedder.process_all_knowledge.side_effect = Exception("Test error")

assert service.load_knowledge_base() == 0
Copy link

Copilot AI Apr 2, 2026

Choose a reason for hiding this comment

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

patch('app.api.embedding_agent.service...') will raise ModuleNotFoundError unless an app package is importable. The repo doesn't contain an app/ package, so this makes the tests environment-dependent/flaky. Patch only the module actually used by EmbeddingAgentService (e.g., api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE, ideally via patch.object(api.embedding_agent.service, ...)) and drop the app.api... patch (or create an explicit alias in sys.modules if you truly need both).

Suggested change
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
service = EmbeddingAgentService(config)
service._clinical_embedder = MagicMock()
service._clinical_embedder.process_all_knowledge.return_value = (["item1", "item2"], None)
assert service.load_knowledge_base() == 2
assert service._knowledge_items == ["item1", "item2"]
def test_load_knowledge_base_exception(self, config: EmbeddingAgentConfig):
"""Test exception handling during knowledge base loading."""
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
service = EmbeddingAgentService(config)
service._clinical_embedder = MagicMock()
service._clinical_embedder.process_all_knowledge.side_effect = Exception("Test error")
assert service.load_knowledge_base() == 0
with patch.object(api.embedding_agent.service, "CLINICAL_EMBEDDER_AVAILABLE", True):
with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
service = EmbeddingAgentService(config)
service._clinical_embedder = MagicMock()
service._clinical_embedder.process_all_knowledge.return_value = (["item1", "item2"], None)
assert service.load_knowledge_base() == 2
assert service._knowledge_items == ["item1", "item2"]
def test_load_knowledge_base_exception(self, config: EmbeddingAgentConfig):
"""Test exception handling during knowledge base loading."""
with patch.object(api.embedding_agent.service, "CLINICAL_EMBEDDER_AVAILABLE", True):
with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
service = EmbeddingAgentService(config)
service._clinical_embedder = MagicMock()
service._clinical_embedder.process_all_knowledge.side_effect = Exception("Test error")
assert service.load_knowledge_base() == 0

Copilot uses AI. Check for mistakes.
@@ -1 +1,2 @@
## 2026-03-27 - Mocking File I/O for TranscriptCorrector | Pattern: Explicitly mock Path.exists and builtins.open when initializing utilities that read config files to avoid FileNotFoundError | Action: Use @patch('pathlib.Path.exists', return_value=True) and @patch('builtins.open', new_callable=mock_open) with a valid JSON string
## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags requires defensive mocking across multiple potential namespaces (e.g., `api.embedding_agent...` and `app.api.embedding_agent...` with `create=True`) depending on test runner execution path | Action: Apply `patch` directly to the module attribute path and add a fallback patch with `create=True` when testing behavior dependent on global flags.
Copy link

Copilot AI Apr 2, 2026

Choose a reason for hiding this comment

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

This QA note recommends patching app.api.embedding_agent..., but the repository does not contain an app package, so this guidance is likely incorrect and may lead to brittle tests. Consider updating the note to recommend patching the real import path used in tests/runtime (e.g., api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE) and avoid suggesting fallback patches to non-importable module paths.

Suggested change
## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags requires defensive mocking across multiple potential namespaces (e.g., `api.embedding_agent...` and `app.api.embedding_agent...` with `create=True`) depending on test runner execution path | Action: Apply `patch` directly to the module attribute path and add a fallback patch with `create=True` when testing behavior dependent on global flags.
## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags should target the actual import path used at runtime (for example, `api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE`) rather than attempting to patch fallback or non-importable module namespaces | Action: Apply `patch` directly to the concrete module attribute path used by the code under test (e.g., `api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE`) when testing behavior dependent on global flags.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown

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

🧹 Nitpick comments (2)
api/embedding_agent/tests/test_service.py (2)

296-300: Inconsistent patching pattern compared to other tests.

This test uses only a single patch.object() call, while test_load_knowledge_base_available and test_load_knowledge_base_exception defensively patch both api.embedding_agent.service and app.api.embedding_agent.service namespaces. The QA checklist in .Jules/qa.md recommends this defensive approach for test runner variability.

Consider aligning this test with the documented pattern for consistency:

♻️ Proposed fix for consistency
 def test_load_knowledge_base_not_available(self, config: EmbeddingAgentConfig):
     """Test loading when clinical embedder is not available."""
-    with patch.object(api.embedding_agent.service, 'CLINICAL_EMBEDDER_AVAILABLE', False):
-        service = EmbeddingAgentService(config)
-        assert service.load_knowledge_base() == 0
+    with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', False, create=True):
+        with patch.object(api.embedding_agent.service, 'CLINICAL_EMBEDDER_AVAILABLE', False):
+            service = EmbeddingAgentService(config)
+            assert service.load_knowledge_base() == 0
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/embedding_agent/tests/test_service.py` around lines 296 - 300, The test
test_load_knowledge_base_not_available should patch CLINICAL_EMBEDDER_AVAILABLE
defensively in both module namespaces like the other tests; update the test to
use patch.object on both api.embedding_agent.service and
app.api.embedding_agent.service to set CLINICAL_EMBEDDER_AVAILABLE to False
before instantiating EmbeddingAgentService and calling load_knowledge_base so
the environment matches test_load_knowledge_base_available and
test_load_knowledge_base_exception.

302-323: Test coverage for available and exception cases looks solid.

The tests correctly verify:

  • Return value matches len(knowledge_items) when successful
  • _knowledge_items state is updated after loading
  • Exception during process_all_knowledge() returns 0 gracefully

The triple-nested patch setup is duplicated between both tests. If you'd like to reduce this duplication, consider extracting a helper or using pytest.fixture with the patches, but this is optional for now.

♻️ Optional: Extract shared patch setup to reduce duplication
from contextlib import contextmanager

`@contextmanager`
def patch_clinical_embedder_available():
    """Context manager for patching CLINICAL_EMBEDDER_AVAILABLE to True."""
    with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
        with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
            with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
                yield

Then use it in tests:

def test_load_knowledge_base_available(self, config: EmbeddingAgentConfig):
    with patch_clinical_embedder_available():
        service = EmbeddingAgentService(config)
        # ... rest of test
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/embedding_agent/tests/test_service.py` around lines 302 - 323, Extract
the repeated triple-patch setup used in test_load_knowledge_base_available and
test_load_knowledge_base_exception into a shared helper (either a contextmanager
named patch_clinical_embedder_available or a pytest.fixture) that patches
CLINICAL_EMBEDDER_AVAILABLE in both app.api.embedding_agent.service and
api.embedding_agent.service and mocks
EmbeddingAgentService._initialize_clinical_embedder; then update both tests to
call the helper before instantiating EmbeddingAgentService and setting
service._clinical_embedder, ensuring the behavior of process_all_knowledge
(return value or side_effect) remains the same.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@api/embedding_agent/tests/test_service.py`:
- Around line 296-300: The test test_load_knowledge_base_not_available should
patch CLINICAL_EMBEDDER_AVAILABLE defensively in both module namespaces like the
other tests; update the test to use patch.object on both
api.embedding_agent.service and app.api.embedding_agent.service to set
CLINICAL_EMBEDDER_AVAILABLE to False before instantiating EmbeddingAgentService
and calling load_knowledge_base so the environment matches
test_load_knowledge_base_available and test_load_knowledge_base_exception.
- Around line 302-323: Extract the repeated triple-patch setup used in
test_load_knowledge_base_available and test_load_knowledge_base_exception into a
shared helper (either a contextmanager named patch_clinical_embedder_available
or a pytest.fixture) that patches CLINICAL_EMBEDDER_AVAILABLE in both
app.api.embedding_agent.service and api.embedding_agent.service and mocks
EmbeddingAgentService._initialize_clinical_embedder; then update both tests to
call the helper before instantiating EmbeddingAgentService and setting
service._clinical_embedder, ensuring the behavior of process_all_knowledge
(return value or side_effect) remains the same.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 95a972f3-12ba-48ac-af3c-48604e49ef4a

📥 Commits

Reviewing files that changed from the base of the PR and between c6f81f1 and 7186ed3.

📒 Files selected for processing (2)
  • .Jules/qa.md
  • api/embedding_agent/tests/test_service.py

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name=".Jules/qa.md">

<violation number="1" location=".Jules/qa.md:2">
P2: This QA note recommends a "fallback patch" with `create=True` targeting `app.api.embedding_agent...`, but `create=True` does not create missing modules — only missing attributes. Since no `app` package exists, following this guidance produces `ModuleNotFoundError`. Update the note to recommend patching only the real import path (`api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE`).</violation>
</file>

<file name="api/embedding_agent/tests/test_service.py">

<violation number="1" location="api/embedding_agent/tests/test_service.py:304">
P1: This patch target points to a non-existent module path (`app.api...`) and can fail the test with `ModuleNotFoundError`.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.


def test_load_knowledge_base_available(self, config: EmbeddingAgentConfig):
"""Test loading when clinical embedder is available."""
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 2, 2026

Choose a reason for hiding this comment

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

P1: This patch target points to a non-existent module path (app.api...) and can fail the test with ModuleNotFoundError.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At api/embedding_agent/tests/test_service.py, line 304:

<comment>This patch target points to a non-existent module path (`app.api...`) and can fail the test with `ModuleNotFoundError`.</comment>

<file context>
@@ -288,6 +290,39 @@ def test_empty_batch(self, service: EmbeddingAgentService):
+
+    def test_load_knowledge_base_available(self, config: EmbeddingAgentConfig):
+        """Test loading when clinical embedder is available."""
+        with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
+            with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
+                with patch.object(EmbeddingAgentService, '_initialize_clinical_embedder'):
</file context>
Suggested change
with patch('app.api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True, create=True):
with patch('api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE', True):
Fix with Cubic

@@ -1 +1,2 @@
## 2026-03-27 - Mocking File I/O for TranscriptCorrector | Pattern: Explicitly mock Path.exists and builtins.open when initializing utilities that read config files to avoid FileNotFoundError | Action: Use @patch('pathlib.Path.exists', return_value=True) and @patch('builtins.open', new_callable=mock_open) with a valid JSON string
## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags requires defensive mocking across multiple potential namespaces (e.g., `api.embedding_agent...` and `app.api.embedding_agent...` with `create=True`) depending on test runner execution path | Action: Apply `patch` directly to the module attribute path and add a fallback patch with `create=True` when testing behavior dependent on global flags.
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot Apr 2, 2026

Choose a reason for hiding this comment

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

P2: This QA note recommends a "fallback patch" with create=True targeting app.api.embedding_agent..., but create=True does not create missing modules — only missing attributes. Since no app package exists, following this guidance produces ModuleNotFoundError. Update the note to recommend patching only the real import path (api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .Jules/qa.md, line 2:

<comment>This QA note recommends a "fallback patch" with `create=True` targeting `app.api.embedding_agent...`, but `create=True` does not create missing modules — only missing attributes. Since no `app` package exists, following this guidance produces `ModuleNotFoundError`. Update the note to recommend patching only the real import path (`api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE`).</comment>

<file context>
@@ -1 +1,2 @@
 ## 2026-03-27 - Mocking File I/O for TranscriptCorrector | Pattern: Explicitly mock Path.exists and builtins.open when initializing utilities that read config files to avoid FileNotFoundError | Action: Use @patch('pathlib.Path.exists', return_value=True) and @patch('builtins.open', new_callable=mock_open) with a valid JSON string
+## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags requires defensive mocking across multiple potential namespaces (e.g., `api.embedding_agent...` and `app.api.embedding_agent...` with `create=True`) depending on test runner execution path | Action: Apply `patch` directly to the module attribute path and add a fallback patch with `create=True` when testing behavior dependent on global flags.
</file context>
Suggested change
## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags requires defensive mocking across multiple potential namespaces (e.g., `api.embedding_agent...` and `app.api.embedding_agent...` with `create=True`) depending on test runner execution path | Action: Apply `patch` directly to the module attribute path and add a fallback patch with `create=True` when testing behavior dependent on global flags.
## 2026-04-02 - Mocking Module-Level Variables for EmbeddingAgentService | Pattern: Patching module-level flags should target the actual import path used at runtime (for example, `api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE`) rather than attempting to patch fallback or non-importable module namespaces | Action: Apply `patch` directly to the concrete module attribute path used by the code under test (e.g., `api.embedding_agent.service.CLINICAL_EMBEDDER_AVAILABLE`) when testing behavior dependent on global flags.
Fix with Cubic

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