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(server): refactoring e2e test code #1393

Merged
merged 2 commits into from
Feb 5, 2025

Conversation

hexaforce
Copy link
Contributor

@hexaforce hexaforce commented Jan 31, 2025

Overview

refined the test code.

What I've done

I consolidated redundant processes to reduce the amount of code.

What I haven't done

How I tested

Which point I want you to review particularly

Memo

Summary by CodeRabbit

Summary by CodeRabbit

Based on the comprehensive summary, here are the updated release notes:

  • Refactoring

    • Simplified server initialization process for end-to-end tests.
    • Streamlined GraphQL request handling across multiple test files.
    • Introduced a new unified Request function for making GraphQL requests.
  • Test Improvements

    • Enhanced modularity of test code.
    • Reduced complexity in server and request configuration.
    • Maintained existing test logic and expected outcomes.
  • Code Cleanup

    • Removed redundant configuration and header management.
    • Simplified import statements.
    • Improved overall code readability.

These changes primarily focus on improving the internal testing infrastructure without introducing user-facing changes.

@hexaforce hexaforce requested a review from pyshx as a code owner January 31, 2025 09:00
Copy link

coderabbitai bot commented Jan 31, 2025

Walkthrough

The pull request introduces significant changes to the end-to-end (e2e) testing infrastructure in the server directory. The modifications primarily focus on simplifying server initialization, streamlining GraphQL request handling, and refactoring test code across multiple test files. The changes include introducing a new Request function, simplifying server startup methods, and removing explicit configuration settings in test setups. The overall goal appears to be improving test code modularity and reducing complexity in request handling and server initialization.

Changes

File Change Summary
server/e2e/common.go - Added initAccountGateway and initServerWithAccountGateway functions
- Modified server initialization methods
- Added GraphQLRequest struct
server/e2e/dataset_export_test.go - Simplified server initialization
- Removed config import
server/e2e/gql_asset_test.go - Replaced multiple chained method calls with new Request function
- Removed net/http import
server/e2e/gql_featureCollection_test.go - Replaced direct HTTP requests with new Request function
- Simplified server initialization
server/e2e/gql_me_test.go - Replaced chained method calls with new Request function
server/e2e/gql_project_export_test.go - Simplified server initialization
- Replaced multiple chained method calls with new Request function
server/e2e/gql_project_import_test.go - Simplified server initialization
- Replaced direct HTTP requests with new Request function
server/e2e/gql_project_test.go - Simplified server initialization
- Updated callRequest function to use new Request function
server/e2e/gql_style_test.go - Replaced direct HTTP requests with new Request function
- Simplified server initialization
server/e2e/mock_test.go - Replaced direct HTTP requests with new Request function

Suggested labels

web

Suggested reviewers

  • pyshx
  • airslice

Poem

🐰 Hopping through code with glee,
Refactoring tests, setting functions free!
GraphQL requests now sleek and light,
Server setup, no more complex might.
Testing rabbit's joyful redesign! 🚀

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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:

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

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

netlify bot commented Jan 31, 2025

Deploy Preview for reearth-web ready!

Name Link
🔨 Latest commit c6825fc
🔍 Latest deploy log https://app.netlify.com/sites/reearth-web/deploys/67a31552da5a9d00089ed46c
😎 Deploy Preview https://deploy-preview-1393--reearth-web.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Nitpick comments (4)
server/e2e/common.go (2)

127-128: Consider capturing the ignored return values if needed.
You are ignoring gateway.Container and accountgateway.Container from StartGQLServerWithRepos. If they are not required for these tests, this is fine. If future tests need these, consider capturing them.


183-185: Consider capturing ignored return values.
Similar to above, if repo.Container or gateway.Container might be needed by other tests or future logic, capture them. Otherwise, this is acceptable for a simple test context.

server/e2e/gql_project_export_test.go (1)

Line range hint 95-106: Consider improving file handling in exporProject function.

The current implementation could be enhanced for better error handling and resource cleanup:

  1. Use defer immediately after file creation
  2. Consider using os.CreateTemp() for safer temporary file handling
 func exporProject(t *testing.T, e *httpexpect.Expect, p string) string {
     // ... existing code ...
-    fileName := "project_data.zip"
-    err := os.WriteFile(fileName, []byte(downloadResponse), os.ModePerm)
-    assert.Nil(t, err)
-    return fileName
+    tmpFile, err := os.CreateTemp("", "project_data_*.zip")
+    assert.Nil(t, err)
+    fileName := tmpFile.Name()
+    defer tmpFile.Close()
+    
+    _, err = tmpFile.Write([]byte(downloadResponse))
+    assert.Nil(t, err)
+    
+    return fileName
 }
server/e2e/gql_asset_test.go (1)

Line range hint 115-146: Consider improving test file cleanup in createAsset function.

The current implementation could benefit from more robust cleanup of test files:

  1. Use t.Cleanup() for guaranteed cleanup even if tests fail
  2. Add error handling for file operations
 func createAsset(t *testing.T, e *httpexpect.Expect, filePath string, coreSupport bool, teamId string) *httpexpect.Value {
     file, err := os.Open(filePath)
     if err != nil {
         t.Fatalf("failed to open file: %v", err)
     }
-    defer func() {
-        if cerr := file.Close(); cerr != nil && err == nil {
-            err = cerr
-        }
-    }()
+    t.Cleanup(func() {
+        if err := file.Close(); err != nil {
+            t.Errorf("failed to close file: %v", err)
+        }
+    })
     // ... rest of the function
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d004b64 and 9972115.

📒 Files selected for processing (10)
  • server/e2e/common.go (5 hunks)
  • server/e2e/dataset_export_test.go (1 hunks)
  • server/e2e/gql_asset_test.go (1 hunks)
  • server/e2e/gql_featureCollection_test.go (3 hunks)
  • server/e2e/gql_me_test.go (1 hunks)
  • server/e2e/gql_project_export_test.go (3 hunks)
  • server/e2e/gql_project_import_test.go (2 hunks)
  • server/e2e/gql_project_test.go (6 hunks)
  • server/e2e/gql_style_test.go (5 hunks)
  • server/e2e/mock_test.go (1 hunks)
🧰 Additional context used
📓 Learnings (2)
server/e2e/gql_project_import_test.go (2)
Learnt from: hexaforce
PR: reearth/reearth-visualizer#1141
File: server/e2e/gql_import_export_test.go:48-80
Timestamp: 2024-11-12T15:21:04.151Z
Learning: In `server/e2e/gql_import_export_test.go`, test functions like `TestCallImportProject` may have disabled assertions due to problems with GraphQL.
Learnt from: hexaforce
PR: reearth/reearth-visualizer#1141
File: server/e2e/gql_import_export_test.go:12-44
Timestamp: 2024-11-12T15:21:04.150Z
Learning: The response body assertions in `TestCallExportProject` are disabled due to existing problems with GraphQL.
server/e2e/gql_project_export_test.go (2)
Learnt from: hexaforce
PR: reearth/reearth-visualizer#1141
File: server/e2e/gql_import_export_test.go:12-44
Timestamp: 2024-11-12T15:21:04.150Z
Learning: The response body assertions in `TestCallExportProject` are disabled due to existing problems with GraphQL.
Learnt from: hexaforce
PR: reearth/reearth-visualizer#1141
File: server/e2e/gql_import_export_test.go:48-80
Timestamp: 2024-11-12T15:21:04.151Z
Learning: In `server/e2e/gql_import_export_test.go`, test functions like `TestCallImportProject` may have disabled assertions due to problems with GraphQL.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - reearth-web
  • GitHub Check: Header rules - reearth-web
  • GitHub Check: Pages changed - reearth-web
🔇 Additional comments (24)
server/e2e/common.go (7)

66-70: No issues found with initAccountGateway.
The function appears straightforward and well-structured, returning a functional mailer container without unnecessary complexity.


72-82: Server initialization logic looks good.
Returning the WebServer, gateway.Container, and accountgateway.Container enhances modularity. No further concerns.


Line range hint 85-116: Concurrent server startup approach is appropriate.
Using a goroutine and channel to handle server shutdown is standard for test scenarios. Implementation is clear and error handling is properly addressed.


131-140: Initialization logic is consistent.
initServer correctly encapsulates server setup. This maintains clarity and consistency across the codebase.


142-142: General startup logic is standard for test environments.
Short-mode skip, background context creation, and listening on a random port help ensure clean and isolated test runs.

Also applies to: 146-146, 150-150, 156-156, 174-174


177-181: Chaining server and repo initialization is clear.
StartServerAndRepos effectively delegates to StartServerWithRepos. The approach is straightforward and easy to maintain.


212-216: GraphQL request struct is well-defined.
Using any is fine in Go 1.18+ for unstructured JSON variables, and the overall structure is clean and consistent.

server/e2e/gql_me_test.go (1)

24-24: Request utility usage is clear.
Leveraging Request(e, uID.String(), requestBody) simplifies the test and helps standardize request creation across scenarios.

server/e2e/mock_test.go (1)

44-44: Refactor to Request(...) is an improvement.
Replacing manual POST setup with a dedicated helper function centralizes request logic and enhances maintainability.

server/e2e/dataset_export_test.go (1)

11-11: LGTM! Server initialization refactored successfully.

The simplified server initialization maintains test functionality while reducing complexity.

server/e2e/gql_project_export_test.go (1)

18-18: LGTM! Server initialization refactored successfully.

The simplified server initialization maintains test functionality while reducing complexity.

server/e2e/gql_style_test.go (1)

52-52: LGTM! Request handling refactored consistently.

The changes successfully implement the new Request() pattern across all GraphQL operations while maintaining comprehensive test coverage.

Also applies to: 76-76, 94-94, 116-116, 143-143, 148-148

server/e2e/gql_asset_test.go (1)

218-218: LGTM! Request handling refactored successfully.

The change successfully implements the new Request() pattern for asset queries.

server/e2e/gql_project_import_test.go (2)

80-80: LGTM!

The function has been refactored to use the new Request function while maintaining proper response validation.


17-17: Verify if assertions are affected by GraphQL problems.

Based on the retrieved learnings from similar test files, assertions in GraphQL-related tests were disabled due to existing problems. Please verify if the assertions in this test are also affected by these GraphQL problems.

✅ Verification successful

Assertions are active and functional

The test contains multiple active assertions that are being executed, unlike the disabled assertions mentioned in the learnings. The assertions are properly checking the response structure and values, indicating they are not affected by the GraphQL problems mentioned in other test files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for disabled assertions in GraphQL test files.

# Test: Search for commented assertions or disabled test cases.
rg -A 5 '(//\s*assert|//\s*t\.Assert|//\s*r\.Value|//\s*r\.Object|//\s*r\.Array|//\s*r\.Equal|//\s*r\.NotNull|//\s*r\.True|//\s*r\.False)' server/e2e/gql_*.go

Length of output: 670


Script:

#!/bin/bash
# Get the implementation of TestCallImportProject and surrounding context
rg -B 2 -A 10 "func TestCallImportProject" server/e2e/gql_project_import_test.go

# Also check for any assertion patterns in the file
rg "assert|r\.(Value|Object|Array|Equal|NotNull|True|False)" server/e2e/gql_project_import_test.go

Length of output: 935

server/e2e/gql_featureCollection_test.go (4)

73-73: LGTM!

The function has been refactored to use the new Request function while maintaining proper response handling.


144-144: LGTM!

The function has been refactored to use the new Request function while maintaining proper response handling.


170-170: LGTM!

The function has been refactored to use the new Request function while maintaining proper response handling.


177-177: LGTM!

The server initialization has been simplified using the new Server function.

server/e2e/gql_project_test.go (5)

20-20: LGTM!

The server initialization has been simplified using the new Server function.


57-57: LGTM!

The server initialization has been simplified using the new Server function.


155-155: LGTM!

The server initialization has been simplified using the new Server function.


309-309: LGTM!

The server initialization has been simplified using the new Server function.


454-454: LGTM!

The function has been refactored to use the new Request function while maintaining proper response handling.

@hexaforce hexaforce force-pushed the chore/server-e2e-test-refactoring branch 2 times, most recently from a10fe49 to 84bf996 Compare February 3, 2025 04:45
@hexaforce hexaforce force-pushed the chore/server-e2e-test-refactoring branch from fe07980 to b957ac8 Compare February 5, 2025 03:27
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: 0

🧹 Nitpick comments (3)
server/e2e/common.go (3)

66-70: Consider making the mailer config configurable.

The function initializes a mailer with an empty config, which might not be suitable for all test scenarios. Consider accepting a mailer config parameter to make the function more flexible.

-func initAccountGateway(ctx context.Context) *accountgateway.Container {
+func initAccountGateway(ctx context.Context, mailerConfig *mailer.Config) *accountgateway.Container {
 	return &accountgateway.Container{
-		Mailer: mailer.New(ctx, &mailer.Config{}),
+		Mailer: mailer.New(ctx, mailerConfig),
 	}
}

72-83: Consider making debug mode configurable.

The function hardcodes debug mode to true. Consider accepting a debug parameter to make the function more flexible for different test scenarios.

-func initServerWithAccountGateway(cfg *config.Config, repos *repo.Container, ctx context.Context) (*app.WebServer, *gateway.Container, *accountgateway.Container) {
+func initServerWithAccountGateway(cfg *config.Config, repos *repo.Container, ctx context.Context, debug bool) (*app.WebServer, *gateway.Container, *accountgateway.Container) {
 	gateways := initGateway()
 	accountGateway := initAccountGateway(ctx)
 	return app.NewServer(ctx, &app.ServerConfig{
 		Config:          cfg,
 		Repos:           repos,
 		AccountRepos:    repos.AccountRepos(),
 		Gateways:        gateways,
 		AccountGateways: accountGateway,
-		Debug:           true,
+		Debug:           debug,
 	}), gateways, accountGateway
}

131-140: Consider code reuse and making debug mode configurable.

The function shares similar code with initServerWithAccountGateway. Consider:

  1. Making debug mode configurable
  2. Reusing code to avoid duplication
-func initServer(cfg *config.Config, repos *repo.Container, ctx context.Context) (*app.WebServer, *gateway.Container) {
+func initServer(cfg *config.Config, repos *repo.Container, ctx context.Context, debug bool) (*app.WebServer, *gateway.Container) {
-	gateways := initGateway()
-	return app.NewServer(ctx, &app.ServerConfig{
-		Config:       cfg,
-		Repos:        repos,
-		AccountRepos: repos.AccountRepos(),
-		Gateways:     gateways,
-		Debug:        true,
-	}), gateways
+	srv, gateways, _ := initServerWithAccountGateway(cfg, repos, ctx, debug)
+	return srv, gateways
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84bf996 and b957ac8.

📒 Files selected for processing (10)
  • server/e2e/common.go (5 hunks)
  • server/e2e/dataset_export_test.go (1 hunks)
  • server/e2e/gql_asset_test.go (1 hunks)
  • server/e2e/gql_featureCollection_test.go (3 hunks)
  • server/e2e/gql_me_test.go (1 hunks)
  • server/e2e/gql_project_export_test.go (3 hunks)
  • server/e2e/gql_project_import_test.go (2 hunks)
  • server/e2e/gql_project_test.go (6 hunks)
  • server/e2e/gql_style_test.go (5 hunks)
  • server/e2e/mock_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • server/e2e/mock_test.go
  • server/e2e/gql_me_test.go
  • server/e2e/gql_asset_test.go
  • server/e2e/dataset_export_test.go
  • server/e2e/gql_project_import_test.go
  • server/e2e/gql_featureCollection_test.go
  • server/e2e/gql_project_export_test.go
  • server/e2e/gql_style_test.go
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Redirect rules - reearth-web
  • GitHub Check: Header rules - reearth-web
  • GitHub Check: Pages changed - reearth-web
  • GitHub Check: ci-server / ci-server-lint
  • GitHub Check: ci-server / ci-server-test
🔇 Additional comments (3)
server/e2e/common.go (2)

85-117: LGTM!

The function has been improved to return additional components (gateways and accountGateway) while maintaining robust error handling and proper cleanup.


212-216: LGTM!

The struct is well-defined with proper JSON tags for GraphQL operations.

server/e2e/gql_project_test.go (1)

20-20: LGTM! Code refactoring improves maintainability.

The changes improve code maintainability by:

  1. Simplifying server initialization using the Server function
  2. Standardizing request handling using the new Request function

Also applies to: 57-57, 155-155, 367-367, 454-454

@hexaforce hexaforce enabled auto-merge (squash) February 5, 2025 03:35
@hexaforce hexaforce disabled auto-merge February 5, 2025 07:42
@hexaforce hexaforce merged commit 6c9312c into main Feb 5, 2025
17 checks passed
@hexaforce hexaforce deleted the chore/server-e2e-test-refactoring branch February 5, 2025 07:44
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.

2 participants