Skip to content

refactor(test): API call methods and enhance test coverage #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2025

Conversation

jeandemeusy
Copy link
Owner

@jeandemeusy jeandemeusy commented Jun 27, 2025

Summary by CodeRabbit

  • New Features

    • Added a new test API endpoint that simulates slow responses for latency testing.
  • Bug Fixes

    • Improved error handling for unreachable endpoints and timeouts in API calls.
  • Tests

    • Refactored and expanded test coverage to include direct API call scenarios, response type checks, and timeout handling.
    • Updated tests to expect more specific exceptions and to validate HTTP status codes.
  • Chores

    • Simplified and reduced the test API, removing unused routes and classes.
    • Updated coverage configuration to exclude logging statements from coverage reports.

@jeandemeusy jeandemeusy self-assigned this Jun 27, 2025
Copy link

coderabbitai bot commented Jun 27, 2025

Walkthrough

This update refactors internal API call methods in api_lib, simplifying error handling, removing retry logic, and switching from boolean to HTTP status code-based success checks. The test REST API is streamlined, removing async wrappers and unused endpoints, while tests are rewritten for direct, granular status and type checks. Coverage configuration and import statements are also updated.

Changes

Files / Groups Change Summary
.coveragerc Updated to exclude logger.* and logging.* patterns from coverage measurement.
api_lib/api_lib.py Refactored: renamed methods (__call_call, __call_api_with_timeout_call_api_with_timeout), simplified error handling, removed retries, switched to status code-based success checks.
test/config/rest_api.py Removed RestAPI class and async wrappers, deleted several endpoints, added /slow_endpoint, simplified responses.
test/conftest.py Changed import of run_server from absolute to relative.
test/test_api_lib.py Replaced high-level tests with granular tests for status codes, types, timeouts, and error handling.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Suite
    participant ApiLib as ApiLib
    participant Server as Test REST API

    Test->>ApiLib: _call(method, path, ...)
    ApiLib->>Server: HTTP request
    Server-->>ApiLib: HTTP status code, response
    ApiLib-->>Test: (status, response) tuple

    Note over ApiLib: If status is 2xx, response is returned<br/>If not, returns None
Loading

Possibly related PRs

Poem

In the warren of code, we hop and we call,
No more retries—just status for all!
Endpoints are lighter, the tests are precise,
With coverage exclusions, the reports look nice.
A slow endpoint yawns, but we’re quick on our feet—
This rabbit loves changes that make code neat! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
api_lib/api_lib.py (1)

59-113: Critical behavioral change: Retry logic removed.

The removal of retry logic represents a significant behavioral change. The method now returns (None, None) immediately on any exception instead of attempting retries, which could impact application reliability.

Please verify that the removal of retry logic is intentional and that calling code can handle immediate failures. Also, there's a potential logging format issue flagged by static analysis.

Let me check if there are other places in the codebase that might depend on the retry behavior:

#!/bin/bash
# Search for any documentation or comments mentioning retry behavior
rg -i "retry|retries" --type py -A 3 -B 3

# Search for any error handling that might expect retries
ast-grep --pattern 'try {
  $$$
  _call_api_with_timeout($$$)
  $$$
} catch {
  $$$
}'
🧹 Nitpick comments (3)
test/config/rest_api.py (1)

42-45: Consider the impact of the 30-second sleep.

While the slow endpoint is useful for testing timeout behavior, the 30-second sleep duration could significantly slow down test execution if not properly managed with appropriate timeouts in tests.

Consider adding a comment to clarify the intended use case:

 @app.route("/slow_endpoint", methods=["GET"])
 def slow_endpoint():
+    # Simulates a slow API response for timeout testing
     time.sleep(30)
     return jsonify({"success": True}), 200
api_lib/api_lib.py (1)

28-57: Method refactoring looks good, but consider exception handling.

The renaming from __call to _call and the simplified return of status code and data is a good improvement. However, the generic exception handling at lines 54-55 is unnecessary.

Remove the redundant generic exception handling:

 try:
     data: dict = await res.json()
 except aiohttp.ContentTypeError:
     data: str = await res.text()
-except Exception as e:
-    raise e
test/test_api_lib.py (1)

2-2: Consider the implications of testing private methods.

While the direct testing of _call and _call_api_with_timeout provides good coverage, testing private methods (those with underscore prefix) can make tests more fragile to internal refactoring. Consider whether some of these tests could focus on the public API instead.

That said, given this appears to be a library where these methods represent core functionality, the current approach provides valuable coverage and aligns well with the refactoring objectives.

Also applies to: 9-93

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf685ec and ab8d2cb.

📒 Files selected for processing (5)
  • .coveragerc (1 hunks)
  • api_lib/api_lib.py (4 hunks)
  • test/config/rest_api.py (2 hunks)
  • test/conftest.py (1 hunks)
  • test/test_api_lib.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/conftest.py (1)
test/config/rest_api.py (1)
  • run_server (50-52)
api_lib/api_lib.py (2)
api_lib/objects/request.py (2)
  • as_dict (18-23)
  • RequestData (16-35)
api_lib/method.py (1)
  • Method (4-9)
🪛 Pylint (3.3.7)
api_lib/api_lib.py

[refactor] 59-59: Too many arguments (6/5)

(R0913)


[refactor] 59-59: Too many positional arguments (6/5)

(R0917)


[error] 94-102: Too many arguments for logging format string

(E1205)

🔇 Additional comments (9)
.coveragerc (1)

6-7: Good addition to coverage exclusions.

Excluding logging statements from coverage reports is a best practice, as these lines typically don't require explicit testing and can artificially inflate coverage metrics without meaningful test value.

test/config/rest_api.py (1)

14-25: Good simplification of test endpoints.

The new /returns_list endpoint provides a clean, simple response for testing list handling functionality.

api_lib/api_lib.py (1)

125-133: Status code handling implementation is correct.

The updated logic to use HTTP status codes instead of boolean flags provides better granularity and aligns well with the refactored _call_api_with_timeout method.

test/conftest.py (1)

11-11: Good change to relative import.

The switch from absolute to relative import follows Python packaging best practices and maintains consistency with the package structure.

test/test_api_lib.py (5)

9-14: Good direct testing of internal API calls.

Testing the _call method directly provides good coverage of the core functionality and allows for precise status code verification.


30-33: Excellent timeout test implementation.

The test correctly verifies that the timeout functionality works as expected, returning (None, None) when the request times out. The 2-second timeout against the 30-second endpoint is well-designed for fast test execution.


54-55: Correct exception handling for unreachable endpoints.

The change from expecting RuntimeError to ClientConnectorError is more precise and aligns with the refactored error handling that no longer wraps connection errors.


60-61: Status return type change handled correctly.

The test correctly expects an integer status code instead of a boolean, reflecting the API refactoring changes.


83-92: Good addition of granular error testing.

These tests provide excellent coverage for both try_req (returning None on failure) and req (raising RuntimeError on failure) scenarios.

@jeandemeusy jeandemeusy merged commit c01c77c into master Jun 27, 2025
2 checks passed
@jeandemeusy jeandemeusy deleted the test-coverage-increase branch June 27, 2025 09:18
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