Skip to content

🧪 [Add test coverage for _save_best_model_to_disk]#379

Open
sheepdestroyer wants to merge 1 commit into
masterfrom
test-save-best-model-to-disk-14923860609239298859
Open

🧪 [Add test coverage for _save_best_model_to_disk]#379
sheepdestroyer wants to merge 1 commit into
masterfrom
test-save-best-model-to-disk-14923860609239298859

Conversation

@sheepdestroyer

@sheepdestroyer sheepdestroyer commented Jul 24, 2026

Copy link
Copy Markdown
Owner

🎯 What: Added tests for the _save_best_model_to_disk function in router/main.py.
📊 Coverage: Covered the successful execution (verifying the JSON payload augmented with updated_at timestamp) and handled exception path (PermissionError).
Result: Improved test coverage and reliability by verifying that the best_free_model.json is correctly structured and saved.


PR created automatically by Jules for task 14923860609239298859 started by @sheepdestroyer

Summary by Sourcery

Add test coverage for the _save_best_model_to_disk helper to validate correct JSON output and error handling.

Tests:

  • Add unit tests that verify _save_best_model_to_disk writes the expected JSON payload including updated_at.
  • Add a test ensuring PermissionError during file write is handled without propagating the exception.

Summary by CodeRabbit

  • Tests
    • Added coverage for saving the best model metadata to disk.
    • Verified correct JSON formatting, timestamp handling, file path usage, and graceful handling of permission errors.

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@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.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@sourcery-ai

sourcery-ai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR adds unit tests for the private helper _save_best_model_to_disk to ensure it writes the correct JSON payload (including an updated_at timestamp) to disk and gracefully handles PermissionError during file operations.

File-Level Changes

Change Details Files
Add tests covering successful JSON write and PermissionError handling in _save_best_model_to_disk.
  • Introduce test_save_best_model_to_disk_success to validate file path, write mode, and JSON payload with updated_at timestamp.
  • Use mock_open, json.dump patching, and datetime.datetime patching to simulate file IO and deterministic timestamps.
  • Introduce test_save_best_model_to_disk_exception_handled to confirm that a PermissionError from open is swallowed and the function still attempts the write.
router/tests/test_save_best_model_to_disk.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

@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds unit tests for _save_best_model_to_disk, covering the expected JSON payload, output path, timestamp formatting, indentation, and handled PermissionError behavior.

Changes

Best Model Persistence

Layer / File(s) Summary
Best model save behavior tests
router/tests/test_save_best_model_to_disk.py
Adds success-path assertions for JSON serialization and output formatting, plus exception-path coverage for permission errors.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: adding test coverage for _save_best_model_to_disk.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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-save-best-model-to-disk-14923860609239298859

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.

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

Hey - I've found 1 issue, and left some high level feedback:

  • Patching datetime.datetime at the top-level (patch("datetime.datetime")) is brittle and may affect other users of datetime; consider patching the object in the module under test instead (e.g., patch("router.main.datetime")) so the test is better isolated and follows where _save_best_model_to_disk actually imports it from.
  • The tests hard-code "/config/router_dir/best_free_model.json"; if the production code derives this path from a constant or helper, consider importing and asserting against that value instead so the tests stay in sync if the path changes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Patching `datetime.datetime` at the top-level (`patch("datetime.datetime")`) is brittle and may affect other users of `datetime`; consider patching the object in the module under test instead (e.g., `patch("router.main.datetime")`) so the test is better isolated and follows where `_save_best_model_to_disk` actually imports it from.
- The tests hard-code `"/config/router_dir/best_free_model.json"`; if the production code derives this path from a constant or helper, consider importing and asserting against that value instead so the tests stay in sync if the path changes.

## Individual Comments

### Comment 1
<location path="router/tests/test_save_best_model_to_disk.py" line_range="8-17" />
<code_context>
+def test_save_best_model_to_disk_success():
+    best_model = {"model_name": "agent-gemma", "score": 100}
+
+    mock_file = mock_open()
+
+    with patch("builtins.open", mock_file), \
+         patch("json.dump") as mock_json_dump, \
+         patch("datetime.datetime") as mock_datetime:
+
+        # Setup mock datetime
+        mock_now = mock_datetime.now.return_value
+        mock_now.isoformat.return_value = "2023-10-25T12:00:00+00:00"
+
+        main._save_best_model_to_disk(best_model)
+
+        # Verify file opened correctly
+        mock_file.assert_called_once_with("/config/router_dir/best_free_model.json", "w")
+
+        # Verify json.dump called with correct payload
</code_context>
<issue_to_address>
**suggestion (testing):** Strengthen the exception-path test and consider additional error conditions.

The PermissionError test only asserts that `open` was called; pytest will fail on unexpected exceptions, but it would be clearer to assert the function’s return value (e.g., `None`) or that `json.dump` is not called. If `_save_best_model_to_disk` is meant to handle other filesystem errors (such as `FileNotFoundError` or `OSError`), consider parametrized tests for these cases to ensure all error paths are explicitly covered.

Suggested implementation:

```python
@pytest.mark.parametrize("exception_type", [PermissionError, FileNotFoundError, OSError])
def test_save_best_model_to_disk_exception_handled(exception_type):
    best_model = {"model_name": "agent-gemma", "score": 100}

    mock_file = mock_open()

    with patch("builtins.open", mock_file), patch("json.dump") as mock_json_dump:
        # Simulate different filesystem-related exceptions when opening the file
        mock_file.side_effect = exception_type("unable to open file")

        result = main._save_best_model_to_disk(best_model)

        # Explicitly assert that the exception path returns a neutral value
        assert result is None

        # Ensure json.dump is never called on failure
        mock_json_dump.assert_not_called()

        # open should still be called with the expected path and mode
        mock_file.assert_called_once_with("/config/router_dir/best_free_model.json", "w")

```

1. If `_save_best_model_to_disk` does not currently return `None` on error, update its implementation accordingly or adjust the assertion to match the intended return value.
2. Ensure `_save_best_model_to_disk` is actually catching and handling `PermissionError`, `FileNotFoundError`, and `OSError`; if not, add the appropriate `try/except` blocks in `router/main.py` so these tests pass.
</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 +8 to +17
mock_file = mock_open()

with patch("builtins.open", mock_file), \
patch("json.dump") as mock_json_dump, \
patch("datetime.datetime") as mock_datetime:

# Setup mock datetime
mock_now = mock_datetime.now.return_value
mock_now.isoformat.return_value = "2023-10-25T12:00:00+00:00"

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.

suggestion (testing): Strengthen the exception-path test and consider additional error conditions.

The PermissionError test only asserts that open was called; pytest will fail on unexpected exceptions, but it would be clearer to assert the function’s return value (e.g., None) or that json.dump is not called. If _save_best_model_to_disk is meant to handle other filesystem errors (such as FileNotFoundError or OSError), consider parametrized tests for these cases to ensure all error paths are explicitly covered.

Suggested implementation:

@pytest.mark.parametrize("exception_type", [PermissionError, FileNotFoundError, OSError])
def test_save_best_model_to_disk_exception_handled(exception_type):
    best_model = {"model_name": "agent-gemma", "score": 100}

    mock_file = mock_open()

    with patch("builtins.open", mock_file), patch("json.dump") as mock_json_dump:
        # Simulate different filesystem-related exceptions when opening the file
        mock_file.side_effect = exception_type("unable to open file")

        result = main._save_best_model_to_disk(best_model)

        # Explicitly assert that the exception path returns a neutral value
        assert result is None

        # Ensure json.dump is never called on failure
        mock_json_dump.assert_not_called()

        # open should still be called with the expected path and mode
        mock_file.assert_called_once_with("/config/router_dir/best_free_model.json", "w")
  1. If _save_best_model_to_disk does not currently return None on error, update its implementation accordingly or adjust the assertion to match the intended return value.
  2. Ensure _save_best_model_to_disk is actually catching and handling PermissionError, FileNotFoundError, and OSError; if not, add the appropriate try/except blocks in router/main.py so these tests pass.

@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

🤖 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 `@router/tests/test_save_best_model_to_disk.py`:
- Around line 10-18: Update the test around main._save_best_model_to_disk to
assert that mock_datetime.now is called with datetime.timezone.utc, while
preserving the existing ISO timestamp and Z-transformation assertions.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bcf8d4b2-967f-48cd-83e6-888cdf0edc22

📥 Commits

Reviewing files that changed from the base of the PR and between dcdd018 and 16997ef.

📒 Files selected for processing (1)
  • router/tests/test_save_best_model_to_disk.py

Comment on lines +10 to +18
with patch("builtins.open", mock_file), \
patch("json.dump") as mock_json_dump, \
patch("datetime.datetime") as mock_datetime:

# Setup mock datetime
mock_now = mock_datetime.now.return_value
mock_now.isoformat.return_value = "2023-10-25T12:00:00+00:00"

main._save_best_model_to_disk(best_model)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that the timestamp is generated in UTC.

The test verifies the Z transformation, but it would still pass if the implementation called datetime.now() without timezone.utc. Assert mock_datetime.now was called with datetime.timezone.utc to cover the upstream contract.

Suggested assertion
+import datetime
+
...
         main._save_best_model_to_disk(best_model)
+        mock_datetime.now.assert_called_once_with(datetime.timezone.utc)
📝 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
with patch("builtins.open", mock_file), \
patch("json.dump") as mock_json_dump, \
patch("datetime.datetime") as mock_datetime:
# Setup mock datetime
mock_now = mock_datetime.now.return_value
mock_now.isoformat.return_value = "2023-10-25T12:00:00+00:00"
main._save_best_model_to_disk(best_model)
with patch("builtins.open", mock_file), \
patch("json.dump") as mock_json_dump, \
patch("datetime.datetime") as mock_datetime:
# Setup mock datetime
mock_now = mock_datetime.now.return_value
mock_now.isoformat.return_value = "2023-10-25T12:00:00+00:00"
main._save_best_model_to_disk(best_model)
mock_datetime.now.assert_called_once_with(datetime.timezone.utc)
🤖 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 `@router/tests/test_save_best_model_to_disk.py` around lines 10 - 18, Update
the test around main._save_best_model_to_disk to assert that mock_datetime.now
is called with datetime.timezone.utc, while preserving the existing ISO
timestamp and Z-transformation assertions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant