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

chore: move testing.http to a single folder #814

Merged
merged 1 commit into from
Jan 10, 2025

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Jan 9, 2025

📑 Description

Summary by CodeRabbit

  • Refactor

    • Updated package structure and naming conventions in testing utilities
    • Enhanced test request and response handling with more explicit dependency injection
    • Improved JSON and session management in test components
  • New Features

    • Added support for more flexible JSON and routing configurations in test environments
    • Integrated foundation JSON and session management into testing utilities
  • Chores

    • Restructured test case implementations
    • Updated method signatures to support more comprehensive testing scenarios

@hwbrzzl hwbrzzl requested a review from a team as a code owner January 9, 2025 16:05
Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request introduces a comprehensive refactoring of the HTTP testing infrastructure within the Goravel framework. The changes primarily focus on enhancing the TestRequest, TestResponse, and AssertableJson structures by introducing more flexible dependency injection. The modifications include adding new fields for JSON handling, routing, and session management, updating method signatures, and changing package names from testing to http. The refactoring aims to improve the modularity and extensibility of the testing components.

Changes

File Change Summary
testing/http/assertable_json.go - Package renamed to http
- json field changed to foundation.Json
- Added jsonStr field
- Updated NewAssertableJSON method signature
testing/http/test_request.go - Package renamed to http
- Added json, route, and session fields
- Updated NewTestRequest method to accept new dependencies
testing/http/test_response.go - Package renamed to http
- Added json and session fields
- Updated NewTestResponse method signature
- Modified JSON and session handling methods
testing/test_case.go - Updated Http method to use new http.NewTestRequest with additional parameters

Sequence Diagram

sequenceDiagram
    participant TestCase
    participant TestRequest
    participant Route
    participant Session
    participant JSON

    TestCase->>TestRequest: Create with dependencies
    TestRequest->>Route: Inject route
    TestRequest->>Session: Inject session manager
    TestRequest->>JSON: Inject JSON handler
    TestRequest-->>TestCase: Return configured test request
Loading

Possibly related PRs

Finishing Touches

  • 📝 Generate Docstrings

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
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 (6)
testing/http/assertable_json.go (1)

117-122: Refactor duplicate code into a helper function

The code for marshaling items and creating a new AssertableJson instance is duplicated in the First, HasWithScope, and Each methods. To improve maintainability and reduce code duplication, consider abstracting this logic into a helper function.

Apply this refactor:

+// Helper function to create AssertableJson from an item
+func (r *AssertableJson) newAssertableJsonFromItem(item any, errorMessage string) (contractstesting.AssertableJSON, bool) {
+    itemJson, err := r.json.Marshal(item)
+    if !assert.NoError(r.t, err, errorMessage) {
+        return nil, false
+    }
+    newJson, err := NewAssertableJSON(r.t, r.json, string(itemJson))
+    if !assert.NoError(r.t, err, errorMessage) {
+        return nil, false
+    }
+    return newJson, true
+}

 // Inside `First` method:
-    itemJson, err := r.json.Marshal(firstItem)
-    if assert.NoError(r.t, err, "Failed to marshal the first item") {
-        newJson, err := NewAssertableJSON(r.t, r.json, string(itemJson))
-        if assert.NoError(r.t, err, "Failed to create AssertableJSON for first item") {
-            callback(newJson)
-        }
-    }
+    if newJson, ok := r.newAssertableJsonFromItem(firstItem, "Failed to create AssertableJSON for first item"); ok {
+        callback(newJson)
+    }

 // Inside `HasWithScope` method:
-    itemJson, err := r.json.Marshal(array[0])
-    if !assert.NoError(r.t, err, "Failed to marshal the first item of array") {
-        return r
-    }
-    newJson, err := NewAssertableJSON(r.t, r.json, string(itemJson))
-    if !assert.NoError(r.t, err, "Failed to create AssertableJSON for first item in scoped array") {
-        return r
-    }
+    if newJson, ok := r.newAssertableJsonFromItem(array[0], "Failed to create AssertableJSON for first item in scoped array"); ok {
+        callback(newJson)
+    }

 // Inside `Each` method:
-    itemJson, err := r.json.Marshal(item)
-    if !assert.NoError(r.t, err) {
-        continue
-    }
-    newJson, err := NewAssertableJSON(r.t, r.json, string(itemJson))
-    if !assert.NoError(r.t, err) {
-        continue
-    }
+    if newJson, ok := r.newAssertableJsonFromItem(item, "Failed to create AssertableJSON for item in Each"); ok {
+        callback(newJson)
+    }

Also applies to: 144-150, 172-178

testing/test_case.go (1)

10-10: Consider using an alias for the http package import.

Since we're moving testing.http to a dedicated folder, consider using an alias like httptest to avoid confusion with the standard http package.

-import "github.com/goravel/framework/testing/http"
+import httptest "github.com/goravel/framework/testing/http"
testing/http/test_request_test.go (1)

34-43: Consider extracting test constants.

The initialization of test request contains several magic strings and empty maps. Consider extracting these into named constants or test fixtures.

+const (
+    defaultTestContext = "test_context"
+)
+
 s.testRequest = &TestRequest{
     t:                 s.T(),
-    ctx:               context.Background(),
+    ctx:               defaultTestContext,
     defaultHeaders:    make(map[string]string),
     defaultCookies:    make(map[string]string),
     sessionAttributes: make(map[string]any),
     json:              &testJson{},
     route:             s.mockRoute,
     session:           s.mockSessionManager,
 }
testing/http/assertable_json_test.go (1)

26-26: Consider using a test helper for AssertableJSON initialization.

The initialization of &testJson{} is duplicated across multiple test cases. Consider extracting this into a test helper function to improve maintainability.

+func newTestAssertableJSON(t *testing.T, jsonStr string) (contractstesting.AssertableJSON, error) {
+    return NewAssertableJSON(t, &testJson{}, jsonStr)
+}

-assertable, err := NewAssertableJSON(s.T(), &testJson{}, validJSON)
+assertable, err := newTestAssertableJSON(s.T(), validJSON)

Also applies to: 30-30, 37-37, 52-52, 63-63, 75-75, 87-87, 99-99, 118-118, 139-139, 152-152, 172-172, 194-194, 210-210

testing/http/test_response_test.go (2)

20-20: Extract test response creation into a helper function.

The creation of test responses with NewTestResponse is duplicated across multiple test cases. Consider extracting this into a helper function to reduce duplication and improve maintainability.

+func newTestResponse(t *testing.T, res *http.Response) contractstesting.TestResponse {
+    return NewTestResponse(t, res, &testJson{}, nil)
+}

-r := NewTestResponse(t, res, &testJson{}, nil)
+r := newTestResponse(t, res)

Also applies to: 26-26, 32-32, 40-40, 46-46, 52-52, 58-58, 64-64, 70-70, 76-76, 82-82, 88-88, 94-94, 100-100, 106-106, 112-112, 118-118, 124-124, 130-130, 136-136, 142-142, 148-148, 154-154, 160-160


344-346: Consider using a builder pattern for TestResponseImpl initialization.

The initialization of TestResponseImpl with session is repeated across test cases. Consider implementing a builder pattern to make the test setup more readable and maintainable.

+type TestResponseBuilder struct {
+    response *TestResponseImpl
+}
+
+func NewTestResponseBuilder() *TestResponseBuilder {
+    return &TestResponseBuilder{
+        response: &TestResponseImpl{},
+    }
+}
+
+func (b *TestResponseBuilder) WithSession(session interface{}) *TestResponseBuilder {
+    b.response.session = session
+    return b
+}
+
+func (b *TestResponseBuilder) Build() *TestResponseImpl {
+    return b.response
+}

-testResponse := &TestResponseImpl{
-    session: mockSessionManager,
-}
+testResponse := NewTestResponseBuilder().
+    WithSession(mockSessionManager).
+    Build()

Also applies to: 358-360, 373-375, 382-384

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 634f3b3 and 36e9c6a.

📒 Files selected for processing (7)
  • testing/http/assertable_json.go (5 hunks)
  • testing/http/assertable_json_test.go (13 hunks)
  • testing/http/test_request.go (6 hunks)
  • testing/http/test_request_test.go (2 hunks)
  • testing/http/test_response.go (7 hunks)
  • testing/http/test_response_test.go (12 hunks)
  • testing/test_case.go (1 hunks)
⏰ Context from checks skipped due to timeout of 300000ms (2)
  • GitHub Check: test / windows (1.23)
  • GitHub Check: test / windows (1.22)
🔇 Additional comments (3)
testing/http/test_request.go (1)

28-30: Ensure route is properly initialized

In the call method, there's a check for r.route being nil that results in a fatal error if true. To prevent unexpected test terminations, ensure that route is properly initialized before making requests.

Also applies to: 165-169

testing/http/test_response.go (1)

72-89: Handle session initialization errors

In the Session method, when r.session is nil, an error errors.SessionFacadeNotSet is returned. Verify that this error is properly defined and handled, and consider providing a more descriptive error message to aid in debugging.

testing/test_case.go (1)

17-17: ⚠️ Potential issue

Fix undefined variable references.

The implementation references undefined variables json, routeFacade, and sessionFacade. These dependencies need to be properly initialized or injected.

Let's verify if these variables are defined elsewhere:

Copy link

codecov bot commented Jan 9, 2025

Codecov Report

Attention: Patch coverage is 77.77778% with 8 lines in your changes missing coverage. Please review.

Project coverage is 69.56%. Comparing base (634f3b3) to head (36e9c6a).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
testing/http/test_request.go 41.66% 4 Missing and 3 partials ⚠️
testing/test_case.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #814      +/-   ##
==========================================
- Coverage   69.57%   69.56%   -0.01%     
==========================================
  Files         215      215              
  Lines       18499    18508       +9     
==========================================
+ Hits        12870    12876       +6     
- Misses       4962     4965       +3     
  Partials      667      667              

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

@hwbrzzl hwbrzzl merged commit bc907a5 into master Jan 10, 2025
12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/optimize-testing-http-1 branch January 10, 2025 02:52
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