Skip to content

feat(HttpMocker): adding support for PUT requests and bytes responses #342

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 3 commits into from
Feb 17, 2025

Conversation

maxi297
Copy link
Contributor

@maxi297 maxi297 commented Feb 17, 2025

This is needed for the new destination we are currently implementing (the exact PR is not yet up but see https://github.com/airbytehq/airbyte-enterprise/pull/89 for more context)

Summary by CodeRabbit

  • New Features

    • Added support for handling PUT requests to enhance HTTP interaction simulations.
    • Improved response handling by accommodating both text and binary data for enhanced flexibility.
  • Tests

    • Expanded test coverage to validate PUT request support and ensure correct responses, including scenarios with compressed content.

@github-actions github-actions bot added the enhancement New feature or request label Feb 17, 2025
@maxi297
Copy link
Contributor Author

maxi297 commented Feb 17, 2025

/autofix

Auto-Fix Job Info

This job attempts to auto-fix any linting or formating issues. If any fixes are made,
those changes will be automatically committed and pushed back to the PR.

Note: This job can only be run by maintainers. On PRs from forks, this command requires
that the PR author has enabled the Allow edits from maintainers option.

PR auto-fix job started... Check job output.

✅ Changes applied successfully.

Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

📝 Walkthrough

Walkthrough

This pull request adds support for the PUT HTTP method in the HTTP mocking framework. The SupportedHttpMethods enumeration now includes a PUT value, and a new put method is implemented in the HttpMocker class, which utilizes _mock_request_method to handle PUT requests. The response assembly logic within _mock_request_method is adjusted to set a key based on whether the response body is a string or bytes. In addition, the HttpResponse class now accepts response bodies as either str or bytes, and new unit tests are added to validate these features.

Changes

File(s) Change Summary
airbyte_cdk/test/mock_http/mocker.py Added support for PUT requests: updated SupportedHttpMethods with a PUT value; introduced HttpMocker.put() method; modified _mock_request_method to handle the new method and conditionally assign "text" or "content" based on the type of response.body.
airbyte_cdk/test/mock_http/response.py Updated the HttpResponse class constructor and its body property to accept and return a union of str and bytes instead of just str.
unit_tests/test/mock_http/test_mocker.py Added two new test methods to HttpMockerTest: one verifies the matching behavior for PUT requests with standard response strings, and the other checks handling for responses provided in bytes (including gzip compressed data).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HttpMocker
    participant _mock_request_method
    participant ResponseHandler

    Client->>HttpMocker: PUT(request, responses)
    HttpMocker->>_mock_request_method: Call with SupportedHttpMethods.PUT
    _mock_request_method->>ResponseHandler: Process response.body
    alt response.body is a string
        ResponseHandler-->>_mock_request_method: Return {"text": <data>}
    else response.body is bytes
        ResponseHandler-->>_mock_request_method: Return {"content": <data>}
    end
    _mock_request_method-->>HttpMocker: Return response dictionary
    HttpMocker-->>Client: Return mocked response
Loading

Suggested reviewers

  • lazebnyi

Would you like any further details or modifications to this overview, wdyt?

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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
Contributor

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

🧹 Nitpick comments (2)
airbyte_cdk/test/mock_http/mocker.py (1)

81-81: Consider adding a docstring for the response body key selection logic.

The conditional logic for selecting between "text" and "content" keys is crucial for handling different response types. Would you consider adding a brief docstring explaining this behavior, wdyt?

 def _mock_request_method(
     self,
     method: SupportedHttpMethods,
     request: HttpRequest,
     responses: Union[HttpResponse, List[HttpResponse]],
 ) -> None:
+    """Mock HTTP requests with support for both string and bytes responses.
+    
+    The response body is set using:
+    - "text" key for string responses
+    - "content" key for bytes responses
+    """
unit_tests/test/mock_http/test_mocker.py (1)

93-105: LGTM! Great test for bytes response handling.

The test effectively validates gzip compressed response handling. Consider adding a test for non-compressed bytes responses as well, wdyt?

@HttpMocker()
def test_given_raw_bytes_response_when_decorate_then_match(self, http_mocker):
    response_content = bytes("Raw bytes response", "utf-8")
    http_mocker.put(
        HttpRequest(_A_URL, _SOME_QUERY_PARAMS, _SOME_HEADERS, _SOME_REQUEST_BODY_STR),
        HttpResponse(response_content, 474),
    )

    response = requests.put(
        _A_URL, params=_SOME_QUERY_PARAMS, headers=_SOME_HEADERS, data=_SOME_REQUEST_BODY_STR
    )

    assert response.content == response_content
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dcff834 and 98ea40f.

📒 Files selected for processing (3)
  • airbyte_cdk/test/mock_http/mocker.py (3 hunks)
  • airbyte_cdk/test/mock_http/response.py (1 hunks)
  • unit_tests/test/mock_http/test_mocker.py (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Linters
airbyte_cdk/test/mock_http/mocker.py

[warning] 1-1: File would be reformatted. Please ensure the code adheres to the formatting standards.

airbyte_cdk/test/mock_http/response.py

[warning] 1-1: File would be reformatted. Please ensure the code adheres to the formatting standards.

⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Check: 'source-pokeapi' (skip=false)
  • GitHub Check: Check: 'source-amplitude' (skip=false)
  • GitHub Check: Check: 'source-shopify' (skip=false)
  • GitHub Check: Check: 'source-hardcoded-records' (skip=false)
  • GitHub Check: Pytest (All, Python 3.11, Ubuntu)
  • GitHub Check: Pytest (All, Python 3.10, Ubuntu)
  • GitHub Check: Pytest (Fast)
  • GitHub Check: Analyze (python)
🔇 Additional comments (4)
airbyte_cdk/test/mock_http/response.py (1)

4-4: LGTM! Clean type hint updates.

The changes elegantly extend the HttpResponse class to support both string and bytes responses without requiring implementation changes.

Also applies to: 9-9, 16-16

airbyte_cdk/test/mock_http/mocker.py (2)

20-20: LGTM! Clean enum extension.

The PUT method is added consistently with other HTTP methods.


102-105: LGTM! Clean PUT method implementation.

The put method follows the established pattern consistently.

unit_tests/test/mock_http/test_mocker.py (1)

79-91: LGTM! Comprehensive PUT request test.

The test follows the established pattern and provides good coverage.

Copy link
Contributor

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

🧹 Nitpick comments (1)
airbyte_cdk/test/mock_http/mocker.py (1)

81-81: Consider making the response type handling more explicit?

The type check works, but what do you think about making it more explicit and future-proof? Here's a suggestion, wdyt?

-                    "text" if isinstance(response.body, str) else "content": response.body,
+                    # requests library uses 'text' for str and 'content' for bytes
+                    "text" if isinstance(response.body, str) else "content" if isinstance(response.body, bytes) else None: response.body,

This would:

  1. Document the requests library convention
  2. Explicitly handle only str/bytes types
  3. Fail fast if an unsupported type is provided
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 98ea40f and 766aef6.

📒 Files selected for processing (2)
  • airbyte_cdk/test/mock_http/mocker.py (3 hunks)
  • airbyte_cdk/test/mock_http/response.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • airbyte_cdk/test/mock_http/response.py
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Check: 'source-pokeapi' (skip=false)
  • GitHub Check: Check: 'source-amplitude' (skip=false)
  • GitHub Check: Check: 'source-shopify' (skip=false)
  • GitHub Check: Check: 'source-hardcoded-records' (skip=false)
  • GitHub Check: Pytest (All, Python 3.11, Ubuntu)
  • GitHub Check: Pytest (All, Python 3.10, Ubuntu)
  • GitHub Check: Pytest (Fast)
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
airbyte_cdk/test/mock_http/mocker.py (2)

20-20: LGTM! Clean addition of PUT method.

The PUT method is added cleanly to the enum, maintaining alphabetical order with existing methods.


102-104: LGTM! Clean implementation of PUT method.

The implementation follows the established pattern consistently with other HTTP methods.

Copy link
Contributor

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

🧹 Nitpick comments (2)
airbyte_cdk/test/mock_http/mocker.py (2)

89-92: LGTM! Clean implementation of response body field handling.

Nice encapsulation of the response field logic! Would you consider adding a docstring to explain the purpose and return values? Something like:

@staticmethod
def _get_body_field(response: HttpResponse) -> str:
    """Determine the appropriate response field based on body type.
    
    Returns:
        str: 'text' for string responses, 'content' for bytes responses
    """
    return "text" if isinstance(response.body, str) else "content"

wdyt? 🤔


106-108: LGTM! Consistent implementation of PUT method.

The implementation follows the established pattern perfectly. Since we're adding a new method, would you be interested in adding docstrings to all HTTP methods to improve documentation? We could start with:

def put(self, request: HttpRequest, responses: Union[HttpResponse, List[HttpResponse]]) -> None:
    """Mock PUT requests matching the given request with the specified response(s).
    
    Args:
        request: The HTTP request to match
        responses: Single response or list of responses to return in sequence
    """
    self._mock_request_method(SupportedHttpMethods.PUT, request, responses)

wdyt about adding similar docs to all methods? 📚

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 766aef6 and c188a1d.

📒 Files selected for processing (1)
  • airbyte_cdk/test/mock_http/mocker.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Check: 'source-pokeapi' (skip=false)
  • GitHub Check: Check: 'source-amplitude' (skip=false)
  • GitHub Check: Check: 'source-shopify' (skip=false)
  • GitHub Check: Check: 'source-hardcoded-records' (skip=false)
  • GitHub Check: Pytest (All, Python 3.11, Ubuntu)
  • GitHub Check: Pytest (All, Python 3.10, Ubuntu)
  • GitHub Check: Pytest (Fast)
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
airbyte_cdk/test/mock_http/mocker.py (1)

20-20: LGTM! Nice addition of PUT method.

The PUT method is added to the enum in alphabetical order, maintaining good code organization.

@maxi297 maxi297 merged commit 263343a into main Feb 17, 2025
22 of 23 checks passed
@maxi297 maxi297 deleted the maxi297/httpmocker-support-put-and-binary-responses branch February 17, 2025 15:42
rpopov added a commit to rpopov/airbyte-python-cdk that referenced this pull request Mar 5, 2025
* main:
  fix: update cryptography package to latest version to address CVE (airbytehq#377)
  fix: (CDK) (HttpRequester) - Make the `HttpRequester.path` optional (airbytehq#370)
  feat: improved custom components handling (airbytehq#350)
  feat: add microseconds timestamp format (airbytehq#373)
  fix: Replace Unidecode with anyascii for permissive license (airbytehq#367)
  feat: add IncrementingCountCursor (airbytehq#346)
  feat: (low-code cdk)  datetime format with milliseconds (airbytehq#369)
  fix: (CDK) (AsyncRetriever) - Improve UX on variable naming and interpolation (airbytehq#368)
  fix: (CDK) (AsyncRetriever) - Add the `request` and `response` to each `async` operations (airbytehq#356)
  fix: (CDK) (ConnectorBuilder) - Add `auxiliary requests` to slice; support `TestRead` for AsyncRetriever (part 1/2) (airbytehq#355)
  feat(concurrent perpartition cursor): Add parent state updates (airbytehq#343)
  fix: update csv parser for builder compatibility (airbytehq#364)
  feat(low-code cdk): add interpolation for limit field in Rate (airbytehq#353)
  feat(low-code cdk): add AbstractStreamFacade processing as concurrent streams in declarative source (airbytehq#347)
  fix: (CDK) (CsvParser) - Fix the `\\` escaping when passing the `delimiter` from Builder's UI (airbytehq#358)
  feat: expose `str_to_datetime` jinja macro (airbytehq#351)
  fix: update CDK migration for 6.34.0 (airbytehq#348)
  feat: Removes `stream_state` interpolation from CDK (airbytehq#320)
  fix(declarative): Pass `extra_fields` in `global_substream_cursor` (airbytehq#195)
  feat(concurrent perpartition cursor): Refactor ConcurrentPerPartitionCursor (airbytehq#331)
  feat(HttpMocker): adding support for PUT requests and bytes responses (airbytehq#342)
  chore: use certified source for manifest-only test (airbytehq#338)
  feat: check for request_option mapping conflicts in individual components (airbytehq#328)
  feat(file-based): sync file acl permissions and identities (airbytehq#260)
  fix: (CDK) (Connector Builder) - refactor the `MessageGrouper` > `TestRead` (airbytehq#332)
  fix(low code): Fix missing cursor for ClientSideIncrementalRecordFilterDecorator (airbytehq#334)
  feat(low-code): Add API Budget (airbytehq#314)
  chore(decoder): clean decoders and make csvdecoder available (airbytehq#326)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants