Skip to content

POC PR - Unit testing with mocking <Not for merge>#1754

Draft
pinkygupta-hub wants to merge 3 commits intokruize:mvp_demofrom
pinkygupta-hub:unit_testing_with_mocking
Draft

POC PR - Unit testing with mocking <Not for merge>#1754
pinkygupta-hub wants to merge 3 commits intokruize:mvp_demofrom
pinkygupta-hub:unit_testing_with_mocking

Conversation

@pinkygupta-hub
Copy link
Copy Markdown
Contributor

@pinkygupta-hub pinkygupta-hub commented Jan 6, 2026

Description

POC: Add Unit Tests with Mocked Dependencies (Reduce Live Cluster Dependency)

Type of change

  • Bug fix
  • New feature
  • Docs update
  • Breaking change (What changes might users need to make in their application due to this PR?)
  • Requires DB changes

How has this been tested?

Please describe the tests that were run to verify your changes and steps to reproduce. Please specify any test configuration required.

  • New Test X
  • Functional testsuite

Test Configuration

  • Kubernetes clusters tested on: Mocking Tests

Checklist 🎯

  • Followed coding guidelines
  • Comments added
  • Dependent changes merged
  • Documentation updated
  • Tests added or updated

Additional information

Include any additional information such as links, test results, screenshots here
Screenshot From 2026-01-06 14-46-24

Summary by Sourcery

Introduce mocked unit tests for the bulk REST API to validate behavior without requiring a live cluster.

Tests:

  • Add fully mocked POST /bulk tests validating job_id handling across different payload shapes.
  • Add partially mocked bulk API test that uses a mocked Kruize URL and backend responses to validate successful bulk job submission and status handling.
  • Add parameterized tests covering varied bulk API responses, including missing job_id and connection error scenarios.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Jan 6, 2026

Reviewer's Guide

Adds mocked unit test coverage for the bulk REST API, including fully and partially mocked scenarios to validate job_id handling, filtering behavior, and connection failures without requiring a live cluster.

File-Level Changes

Change Details Files
Introduce mocked unit tests for the bulk /bulk REST API to validate job_id behavior across payload variants.
  • Define reusable base and filtered payload generators to construct common bulk API request bodies.
  • Add a fully mocked bulk API test that patches post_bulk_api and asserts job_id presence for empty, base, and filtered payloads using parametrization.
  • Use caplog and logging to verify behavior and log successful mock job creation when job_id is present.
tests/scripts/local_monitoring_tests/rest_apis/test_bulk_mocked.py
Add partially mocked bulk API tests to exercise filter construction and success-path behavior while mocking network interactions.
  • Patch the global Kruize URL, requests.post, and get_bulk_job_status to avoid real HTTP calls and cluster dependencies.
  • Build payloads dynamically from various include/exclude filter setups and assert that post_bulk_api returns a successful response.
  • Mock bulk job status responses with realistic nested metadata to simulate datasource, cluster, namespace, workload, and container hierarchy.
tests/scripts/local_monitoring_tests/rest_apis/test_bulk_mocked.py
Cover additional bulk API edge cases including varied job_id responses and connection failures.
  • Parametrize tests to handle responses with and without job_id and assert correct detection of job_id presence.
  • Mock post_bulk_api to raise requests.exceptions.ConnectionError and assert that the caller correctly propagates the exception.
  • Ensure all mocked responses return HTTP 200 where appropriate to focus validation on JSON payload structure and error propagation.
tests/scripts/local_monitoring_tests/rest_apis/test_bulk_mocked.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

@pinkygupta-hub pinkygupta-hub changed the base branch from master to mvp_demo January 6, 2026 09:26
@pinkygupta-hub pinkygupta-hub marked this pull request as ready for review January 8, 2026 08:21
Copy link
Copy Markdown
Contributor

@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 found 2 issues, and left some high level feedback:

  • The test module manipulates sys.path (sys.path.append("../../")) to import helpers; consider using a proper Python package layout and conftest.py/pytest pythonpath configuration instead so tests don't rely on relative path hacks.
  • In test_bulk_api_partial_mocked, the expected parameter from the parametrization is never used; if the intent is to validate filter shaping, add explicit assertions against the payload passed to the mocked calls or remove expected to avoid confusion.
  • Calling logging.basicConfig at import time in the test module can interfere with other tests' logging configuration; prefer using caplog or per-test logger setup rather than globally configuring logging in the test file.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The test module manipulates `sys.path` (`sys.path.append("../../")`) to import helpers; consider using a proper Python package layout and `conftest.py`/pytest `pythonpath` configuration instead so tests don't rely on relative path hacks.
- In `test_bulk_api_partial_mocked`, the `expected` parameter from the parametrization is never used; if the intent is to validate filter shaping, add explicit assertions against the payload passed to the mocked calls or remove `expected` to avoid confusion.
- Calling `logging.basicConfig` at import time in the test module can interfere with other tests' logging configuration; prefer using `caplog` or per-test logger setup rather than globally configuring logging in the test file.

## Individual Comments

### Comment 1
<location> `tests/scripts/local_monitoring_tests/rest_apis/test_bulk_mocked.py:86-95` </location>
<code_context>
+@patch.object(helpers.kruize, "URL", "http://mock-cluster:8080", create=True)
</code_context>

<issue_to_address>
**issue (testing):** Parametrized `expected` filter is never asserted, so the partial-mocked test does not actually validate filter behavior

This test parametrizes `filter_setup` and `expected`, but only checks `response.status_code == 200`; `expected` is never used. As written, it doesn’t actually verify how include/exclude filters or label modes are handled.

Please add assertions that:
- The POST is called with the correct payload derived from `filter_setup` (e.g. via `mock_post_bulk_api.assert_called_with` or `call_args`).
- The GET response or any logic using `get_bulk_job_status` is interpreted as intended.

If the intent is to validate filter composition, use `expected` to assert on the downstream structure/query. Otherwise, consider removing `expected` from the parameters to avoid implying behavior the test doesn’t cover.
</issue_to_address>

### Comment 2
<location> `tests/scripts/local_monitoring_tests/rest_apis/test_bulk_mocked.py:7-12` </location>
<code_context>
+import sys
+from unittest.mock import patch, MagicMock
+
+sys.path.append("../../")
+
+# Kruize helpers
+import helpers.kruize
+from helpers.kruize import post_bulk_api
+from helpers.utils import form_kruize_url, get_kruize_url
+
+
</code_context>

<issue_to_address>
**nitpick:** Consider avoiding `sys.path.append` in tests in favor of a package-aware import strategy

Using `sys.path.append("../../")` makes the tests sensitive to how they’re invoked (repo root vs subdirectory, IDE vs CI), which can cause hard‑to‑debug import issues. Prefer a package-aware approach instead, for example:
- Structure the project as a package (with `__init__.py`) and use normal absolute imports, or
- Configure `pytest` (e.g., via `conftest.py` / `pythonpath`) to expose shared helpers.

This isn’t functionally incorrect, but updating it would improve maintainability and environment-independence of the tests.
</issue_to_address>

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.

Comment on lines +86 to +95
@patch.object(helpers.kruize, "URL", "http://mock-cluster:8080", create=True)
@patch("helpers.kruize.requests.post")
@patch("helpers.kruize.get_bulk_job_status")
@pytest.mark.parametrize(
"filter_setup, expected",
[
({"include": {"namespace": ["default"], "workload": ["wl1"], "containers": ["ctr1"]}},
{"namespace": ["default"], "workload": ["wl1"], "containers": ["ctr1"]}),
({"include": {"namespace": ["default"]}}, {"namespace": ["default"]}),
({"include": {"labels": {"cost": "true"}}}, {"labels": {"cost": "true"}, "mode": "include"}),
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.

issue (testing): Parametrized expected filter is never asserted, so the partial-mocked test does not actually validate filter behavior

This test parametrizes filter_setup and expected, but only checks response.status_code == 200; expected is never used. As written, it doesn’t actually verify how include/exclude filters or label modes are handled.

Please add assertions that:

  • The POST is called with the correct payload derived from filter_setup (e.g. via mock_post_bulk_api.assert_called_with or call_args).
  • The GET response or any logic using get_bulk_job_status is interpreted as intended.

If the intent is to validate filter composition, use expected to assert on the downstream structure/query. Otherwise, consider removing expected from the parameters to avoid implying behavior the test doesn’t cover.

Comment on lines +7 to +12
sys.path.append("../../")

# Kruize helpers
import helpers.kruize
from helpers.kruize import post_bulk_api
from helpers.utils import form_kruize_url, get_kruize_url
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.

nitpick: Consider avoiding sys.path.append in tests in favor of a package-aware import strategy

Using sys.path.append("../../") makes the tests sensitive to how they’re invoked (repo root vs subdirectory, IDE vs CI), which can cause hard‑to‑debug import issues. Prefer a package-aware approach instead, for example:

  • Structure the project as a package (with __init__.py) and use normal absolute imports, or
  • Configure pytest (e.g., via conftest.py / pythonpath) to expose shared helpers.

This isn’t functionally incorrect, but updating it would improve maintainability and environment-independence of the tests.

Signed-off-by: Pinky Gupta <pinky.gupta1@ibm.com>
Signed-off-by: Pinky Gupta <pinky.gupta1@ibm.com>
@pinkygupta-hub pinkygupta-hub changed the title Unit testing with mocking POC PR - Unit testing with mocking <Not for merge> Jan 14, 2026
@pinkygupta-hub pinkygupta-hub marked this pull request as draft January 14, 2026 06:08
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