Skip to content
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

feat: Optimize testing.http #788

Merged
merged 7 commits into from
Dec 25, 2024
Merged

feat: Optimize testing.http #788

merged 7 commits into from
Dec 25, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Dec 24, 2024

📑 Description

Add Bind method: Http(t).Bind(&user).Get("/")

Summary by CodeRabbit

  • New Features

    • Enhanced TestRequest interface with new HTTP methods for improved request handling.
    • Introduced a Bind method for binding response content to variables.
    • Added JSON handling capabilities in the ServiceProvider.
    • Improved mocking capabilities for TestRequest with new expectations and methods.
  • Bug Fixes

    • Improved error handling for JSON unmarshalling in TestRequest.
  • Tests

    • Expanded test suite with new tests for JSON binding and request handling.
    • Improved structure and clarity of the test suite.
    • Enhanced JSON assertion capabilities in tests.

✅ Checks

  • Added test cases for my code

Copy link
Contributor

coderabbitai bot commented Dec 24, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces significant modifications to the TestRequest interface and its implementations across multiple files. The changes primarily focus on enhancing the testing infrastructure by adding HTTP method support, introducing a new Bind method for JSON response handling, and restructuring the interface methods. The modifications span several files in the contracts/testing, mocks/testing, and testing directories, with updates to method signatures, mock implementations, and test suites.

Changes

File Change Summary
contracts/testing/test_request.go Restructured TestRequest interface with new HTTP method signatures (Get, Post, Put, Delete, etc.), added Bind method, repositioned WithBasicAuth, WithContext, and WithHeaders methods
mocks/testing/TestRequest.go Added mock implementation for Bind method, introduced TestRequest_Bind_Call type for enhanced mocking capabilities
testing/assertable_json.go Removed encoding/json import
testing/service_provider.go Added json variable of type foundation.Json
testing/test_request.go Added bind field to TestRequest, reintroduced HTTP methods with enhanced binding functionality
testing/test_request_test.go Updated test suite with new fields, added TestBindAndCall method, modified existing test methods
testing/assertable_json_test.go Encapsulated tests in AssertableJsonTestSuite struct for better organization and management
testing/test_response_test.go Added json variable of type *testJson for JSON assertion handling

Sequence Diagram

sequenceDiagram
    participant Client
    participant TestRequest
    participant Route
    participant Response

    Client->>TestRequest: Create Request
    Client->>TestRequest: Bind(value)
    TestRequest->>Route: Send HTTP Request
    Route-->>TestRequest: Return Response
    TestRequest->>Response: Unmarshal JSON
    TestRequest-->>Client: Return TestResponse
Loading

Possibly related PRs

Suggested reviewers

  • kkumar-gcc

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5d24287 and 77ca7c0.

📒 Files selected for processing (4)
  • testing/assertable_json_test.go (10 hunks)
  • testing/test_request.go (4 hunks)
  • testing/test_request_test.go (5 hunks)
  • testing/test_response_test.go (4 hunks)

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • 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 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

codecov bot commented Dec 24, 2024

Codecov Report

Attention: Patch coverage is 24.32432% with 28 lines in your changes missing coverage. Please review.

Project coverage is 69.65%. Comparing base (8c0a04a) to head (77ca7c0).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
testing/test_request.go 25.00% 24 Missing and 3 partials ⚠️
testing/service_provider.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #788      +/-   ##
==========================================
- Coverage   69.69%   69.65%   -0.04%     
==========================================
  Files         215      215              
  Lines       18523    18545      +22     
==========================================
+ Hits        12909    12917       +8     
- Misses       4910     4916       +6     
- Partials      704      712       +8     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@hwbrzzl hwbrzzl marked this pull request as draft December 24, 2024 12:02
@hwbrzzl hwbrzzl marked this pull request as ready for review December 25, 2024 02:01
@hwbrzzl hwbrzzl closed this Dec 25, 2024
@hwbrzzl hwbrzzl reopened this Dec 25, 2024
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 (11)
contracts/testing/test_request.go (2)

9-16: Add validation or documentation for request body usage.

The newly added HTTP methods do not specify how request bodies should be validated or handled (e.g., io.Reader usage). Consider clarifying usage expectations in doc comments or ensuring that all callers safely handle potential nil inputs.


24-24: Avoid potential header duplication.

WithHeaders merges headers but might cause duplicates if the same key was already set. Consider clarifying or enforcing overwrites vs merges.

testing/service_provider.go (1)

15-15: Ensure the global variable does not become a hidden dependency.

A global json variable is introduced. If multiple tests or routines mutate it accidentally, it may cause hard-to-track test fragility.

testing/test_request_test.go (6)

4-9: Avoid potential naming collisions in imports.

The import alias encodingjson "encoding/json" is more explicit than typical. Confirm it will not cause confusion in the broader codebase.


34-35: Consider a more descriptive variable name than json.

Reusing json as a package-level variable and also reassigning here could be confusing. Consider something more descriptive e.g. jsonHandler.


37-40: Initialize testRequest with a more descriptive constructor.

Creating the struct directly is fine, but consider using NewTestRequest(s.T()) if that constructor is consistently used elsewhere to keep initialization uniform.


68-71: Group variable declarations with the same scope.

Lines 69-71 define mockDriver and mockSession. Consider grouping them or clarifying usage so that each variable’s purpose is clearer.


75-75: setup function naming.

setup is vague. Consider naming it for clarity, e.g. setupDriverFailure or a semantic name that explains the scenario.


123-123: Encapsulated call to set session.

request := s.testRequest.WithSession(...) followed by setSession() is a straightforward approach. Consider verifying session state with additional assertions if needed.

testing/test_request.go (2)

41-43: Document body usage.

When Post is called with body io.Reader, confirm that large bodies or streaming scenarios are safely handled, e.g., no partial reads or concurrency issues.


49-51: Ensure safe usage for Delete with body.

While some semantics allow a body in DELETE requests, some servers ignore it. The code is fine but clarify usage in doc comments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f48470 and 5d24287.

📒 Files selected for processing (6)
  • contracts/testing/test_request.go (1 hunks)
  • mocks/testing/TestRequest.go (1 hunks)
  • testing/assertable_json.go (0 hunks)
  • testing/service_provider.go (2 hunks)
  • testing/test_request.go (3 hunks)
  • testing/test_request_test.go (5 hunks)
💤 Files with no reviewable changes (1)
  • testing/assertable_json.go
🔇 Additional comments (27)
contracts/testing/test_request.go (2)

17-17: Confirm thread safety and concurrency behavior for Bind.

The new Bind(value any) TestRequest method mutates the internal state (bind field). If code is executed concurrently, consider clarifying whether a single TestRequest instance is safe for concurrent calls.


19-20: Enforce or document authentication usage constraints.

The repositioned WithBasicAuth and WithContext methods add flexible integration points for auth and context passing. Ensure (or document) consistent usage patterns and validate any credentials or context data as needed.

testing/service_provider.go (1)

45-46: Verify JSON instance lifecycle.

json = app.GetJson() sets the global instance. Confirm the lifecycle and ensure that subsequent usage doesn’t rely on environment-specific configurations or produce race conditions in concurrent tests.

testing/test_request_test.go (13)

15-15: Mock usage validated.

Adding mocksroute "github.com/goravel/framework/mocks/route" ensures we can stub route calls in tests effectively. Looks good.


21-22: Test suite alignment.

The new fields testRequest and mockRoute are consistent with typical suite-based testing patterns, enhancing clarity and maintainability.


32-32: Check for concurrent test runs.

s.mockRoute = mocksroute.NewRoute(s.T()) is fine, but ensure that no concurrency issues arise if multiple tests or test suites manipulate shared route mocks.


44-45: Prevent potential side effects by nil assignments.

json = nil and routeFacade = nil ensure a clean teardown, but confirm that no other global references share these variables.


49-65: Thorough test coverage for JSON binding.

The TestBindAndCall method adequately tests the new Bind logic with JSON. Ensure coverage includes error scenarios (e.g. malformed JSON, empty body).


83-83: Short function style is good.

The anonymous function to simulate driver retrieval error is easy to read and clearly associates the mock with the test scenario.


91-91: Consistency in mocking session building.

Again, the short style is consistent with the approach in line 83. Good maintainability.


100-100: Check for concurrency issues.

The lines that mock session usage demonstrate multiple method calls on the same mock. Confirm tests are not run concurrently against the same mock instance.


118-119: Proper instantiation of new mock objects.

Each test block re-initializes mockDriver and mockSession, avoiding leftover state from previous tests. Good practice.


121-121: Clear test arrangement.

tc.setup() is easy to read. The library usage for .On() mocking is consistent.


159-159: Reuse testRequest.

Reusing s.testRequest for session-based tests is consistent, ensuring the same instance logic is tested. Looks good.


167-167: No side effects on an empty session.

TestSetSessionUsingWithoutSession ensures no calls to the session manager if no attributes are set. Great for preventing unintended side effects.


173-182: Minimalistic testJson struct is beneficial.

The Marshal and Unmarshal methods are direct pass-throughs to the stdlib. This is helpful for test override scenarios if needed (e.g., custom encoding).

testing/test_request.go (9)

21-21: Document concurrency assumptions for the new bind field.

Since bind any can be set then used in call, confirm that a single TestRequest is not used in parallel.


37-39: HTTP method handlers are consistent.

The Get method calls r.call(...); approach is coherent with the new pattern for each HTTP method.


45-47: Use consistent approach for Put.

Matches the Post structure. Looks acceptable.


53-55: Patch follows the same pattern.

No issues found.


57-59: Head usage is consistent.

No unusual code references.


61-63: Options usage.

Well-defined and consistent, calls call.


65-68: Bind method clarity.

Storing value any in r.bind is a simple approach. Just confirm that subsequent calls do not override or conflict.


153-163: Guard the response body read process.

Ensure the response body is always closed. If testResponse handles closing in Content(), confirm it’s consistently tested for potential read errors.


165-165: Return the testResponse last.

Returning testResponse after the optional unmarshal is good. No issues found.

mocks/testing/TestRequest.go (2)

27-45: Bind method mocking is consistent.

The method simply delegates to _m.Called(value). This allows flexible test scenarios.


47-74: Helper struct for Bind call chaining.

TestRequest_Bind_Call provides a clear mechanism for chaining .Run and .Return. This is properly aligned with typical testify/mock usage patterns.

@hwbrzzl hwbrzzl merged commit b261a62 into master Dec 25, 2024
9 of 12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/optimize-testing-http branch December 25, 2024 03:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant