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): Increase domain package unit test coverage (asset and integrationapi) #1302

Merged
merged 14 commits into from
Nov 29, 2024

Conversation

jasonkarel
Copy link
Contributor

@jasonkarel jasonkarel commented Nov 8, 2024

Overview

Increase unit testing coverage in asset (85% to 99%) and integrationapi (2% to 51.5%) packages

What I've done

added more ut to cover codes in asset and integrationapi packages

What I haven't done

How I tested

run package coverage test

Screenshot

Which point I want you to review particularly

test cases of asset and integrationapi packages.

Memo

Summary by CodeRabbit

  • New Features

    • Introduced new test functions to validate various functionalities, including asset creation, upload handling, and project instantiation.
    • Enhanced test coverage for edge cases, including handling of nil inputs and various status conditions.
  • Bug Fixes

    • Adjusted existing tests to improve error handling and ensure proper assertions for edge cases.
  • Tests

    • Expanded the test suite with multiple new functions and refined existing ones for better clarity and coverage.

Copy link

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request introduces several changes across multiple test files within the server/pkg/asset and server/pkg/integrationapi directories. Key modifications include the addition of new fields, specifically flatFiles, to various structs and the introduction of numerous new test functions aimed at enhancing test coverage. Existing tests have been refined, particularly to handle edge cases and improve structure through table-driven tests. Overall, these changes aim to bolster the robustness and clarity of the testing framework for asset management functionalities.

Changes

File Path Change Summary
server/pkg/asset/asset_test.go Added field flatFiles to Asset struct; initialized to false in TestAsset_Type with assertion for got.FlatFiles().
server/pkg/asset/builder_test.go Added field flatFiles to Input struct; utilized in TestBuilder_Build for asset creation.
server/pkg/asset/file_test.go Added new test functions Test_Clone and Test_FilePath; refactored existing tests to handle nil cases and adopted table-driven approach for Test_File_Files and Test_File_RootPath.
server/pkg/asset/preview_type_test.go Added TestPreviewType_Prev; adjusted TestPreviewType_DetectPreviewType for syntax; expanded TestPreviewType_PreviewTypeFromExtension with additional assertion.
server/pkg/asset/status_test.go Added test case in TestStatus_StatusFromRef for invalid input handling in ArchiveExtractionStatusFromRef.
server/pkg/asset/upload_builder_test.go Introduced new file with tests for UploadBuilder, validating creation and attribute settings.
server/pkg/asset/upload_test.go Added TestUpload_Upload to validate Upload struct behavior and attribute correctness.
server/pkg/integrationapi/asset_test.go Added Test_NewAsset, TestToAssetArchiveExtractionStatus, and TestToPreviewType for validating asset-related functionalities; modified TestToAssetFile for nil input.
server/pkg/integrationapi/comment_test.go Introduced new file with TestNewComment to validate NewComment function behavior across various scenarios.
server/pkg/integrationapi/condition_test.go New file with tests for condition types and operators, ensuring correct conversion logic and error handling.
server/pkg/integrationapi/item_export_test.go New file with tests for GeometryType and FeatureCollectionFromItems functions, validating conversions and error handling.
server/pkg/integrationapi/project_test.go Added Test_NewProject to validate NewProject function's behavior and expected output.

Possibly related PRs

Suggested reviewers

  • nourbalaha
  • yk-eukarya

Poem

🐰 In the land of tests, we hop and play,
New fields and functions brighten the day.
With flatFiles added, our coverage grows,
In structured tests, our confidence shows.
So let’s celebrate with a joyful cheer,
For robust tests bring us all good cheer! 🎉


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

netlify bot commented Nov 8, 2024

Deploy Preview for reearth-cms canceled.

Name Link
🔨 Latest commit 2693fca
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/67497e29a038fc000832c373

@github-actions github-actions bot added the server label Nov 8, 2024
@jasonkarel jasonkarel marked this pull request as draft November 8, 2024 06:22
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: 4

🧹 Outside diff range and nitpick comments (12)
server/pkg/asset/upload_test.go (2)

10-28: Consider enhancing test coverage with additional test cases.

While the current test implementation is good for basic validation, consider the following improvements:

  1. Convert to table-driven tests for better maintainability
  2. Add negative test cases (e.g., empty values, invalid UUIDs)
  3. Add edge cases (e.g., very large content length)
  4. Make time-based tests more reliable

Here's a suggested refactor:

 func TestUpload_Upload(t *testing.T) {
+    // Define test cases
+    tests := []struct {
+        name          string
+        upload        *Upload
+        wantUUID     string
+        wantFileName string
+        wantLength   int64
+        wantExpired  bool
+    }{
+        {
+            name: "valid upload",
+            upload: &Upload{
+                uuid:          "1",
+                project:       NewProjectID(),
+                fileName:      "file.test",
+                contentLength: 1,
+                expiresAt:     time.Now().Add(time.Hour),
+            },
+            wantUUID:     "1",
+            wantFileName: "file.test",
+            wantLength:   1,
+            wantExpired:  false,
+        },
+        {
+            name: "expired upload",
+            upload: &Upload{
+                uuid:          "2",
+                project:       NewProjectID(),
+                fileName:      "expired.test",
+                contentLength: 0,
+                expiresAt:     time.Now().Add(-time.Hour),
+            },
+            wantUUID:     "2",
+            wantFileName: "expired.test",
+            wantLength:   0,
+            wantExpired:  true,
+        },
+        // Add more test cases here
+    }
+
+    for _, tt := range tests {
+        t.Run(tt.name, func(t *testing.T) {
+            assert.Equal(t, tt.wantUUID, tt.upload.UUID())
+            assert.Equal(t, tt.wantFileName, tt.upload.FileName())
+            assert.Equal(t, tt.wantLength, tt.upload.ContentLength())
+            assert.Equal(t, tt.wantExpired, tt.upload.Expired(time.Now()))
+        })
+    }
 }

10-10: Add test function documentation.

Consider adding a doc comment explaining the purpose and scope of this test function.

+// TestUpload_Upload verifies that Upload struct's getter methods
+// return the expected values and correctly handles expiration checks
 func TestUpload_Upload(t *testing.T) {
server/pkg/asset/upload_builder_test.go (1)

10-15: Consider using table-driven tests for better coverage.

While the current test structure is good, consider using table-driven tests to cover more edge cases and make the tests more maintainable. This would allow testing various initialization scenarios more systematically.

Here's a suggested refactor:

 func TestUploadBuilder_NewUpload(t *testing.T) {
-	ub := &UploadBuilder{
-		u: &Upload{},
-	}
-	assert.Equal(t, ub, NewUpload())
+	tests := []struct {
+		name string
+		want *UploadBuilder
+	}{
+		{
+			name: "empty upload",
+			want: &UploadBuilder{u: &Upload{}},
+		},
+		// Add more test cases here
+	}
+	
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got := NewUpload()
+			assert.Equal(t, tt.want, got)
+		})
+	}
server/pkg/asset/status_test.go (1)

78-80: LGTM! Consider enhancing test readability with table-driven tests.

The new test case improves coverage by verifying the behavior with invalid input. The implementation is correct and follows the existing test pattern.

Consider refactoring the entire test function to use table-driven tests for better maintainability and readability. Here's a suggested approach:

func TestStatus_StatusFromRef(t *testing.T) {
-	sk := ArchiveExtractionStatusSkipped
-	p := ArchiveExtractionStatusPending
-	ip := ArchiveExtractionStatusInProgress
-	d := ArchiveExtractionStatusDone
-	f := ArchiveExtractionStatusFailed
-
-	s := lo.ToPtr("skipped")
-	res := ArchiveExtractionStatusFromRef(s)
-	assert.Equal(t, &sk, res)
-	// ... other test cases ...
+	tests := []struct {
+		name     string
+		input    *string
+		expected *ArchiveExtractionStatus
+	}{
+		{
+			name:     "skipped status",
+			input:    lo.ToPtr("skipped"),
+			expected: lo.ToPtr(ArchiveExtractionStatusSkipped),
+		},
+		{
+			name:     "invalid status",
+			input:    lo.ToPtr("test"),
+			expected: nil,
+		},
+		{
+			name:     "nil input",
+			input:    nil,
+			expected: nil,
+		},
+		// ... other test cases ...
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			res := ArchiveExtractionStatusFromRef(tt.input)
+			assert.Equal(t, tt.expected, res)
+		})
+	}
}
server/pkg/asset/asset_test.go (1)

37-37: Consider adding test coverage for both flatFiles states.

While the test covers the false case for flatFiles, consider using table-driven tests to cover both true and false cases for better test coverage.

Here's a suggested approach:

func TestAsset_Type(t *testing.T) {
+    tests := []struct {
+        name      string
+        flatFiles bool
+    }{
+        {"with flat files disabled", false},
+        {"with flat files enabled", true},
+    }
+
+    for _, tt := range tests {
+        t.Run(tt.name, func(t *testing.T) {
             aid := NewID()
             // ... other initializations ...
             
             got := Asset{
                 id: aid,
                 // ... other fields ...
-                flatFiles: false,
+                flatFiles: tt.flatFiles,
             }
             
             // ... other assertions ...
-            assert.Equal(t, false, got.FlatFiles())
+            assert.Equal(t, tt.flatFiles, got.FlatFiles())
         })
+    }
}
server/pkg/asset/preview_type_test.go (1)

324-326: Simplify the test implementation for better readability.

The current implementation using an immediately invoked function expression (IIFE) is unnecessarily complex.

Consider simplifying the test like this:

-func TestPreviewType_Prev(t *testing.T) {
-	assert.Equal(t, func() *PreviewType { pt := PreviewType("image"); return &pt }(), PreviewTypeImage.Ref())
+func TestPreviewType_Prev(t *testing.T) {
+	expected := PreviewType("image")
+	assert.Equal(t, &expected, PreviewTypeImage.Ref())
+}
server/pkg/asset/file_test.go (5)

71-101: LGTM with a minor suggestion for error message improvement

The conversion to table-driven tests is excellent and improves maintainability. Consider enhancing the error message to include the test case name for better debugging:

-				t.Errorf("expected %v, got %v", tt.want, flatten)
+				t.Errorf("%s: expected %v, got %v", tt.name, tt.want, flatten)

228-255: LGTM with the same error message improvement suggestion

The table-driven test conversion is well-structured and includes good test cases. Consider the same error message enhancement:

-				t.Errorf("expected %q, got %q", tt.want, result)
+				t.Errorf("%s: expected %q, got %q", tt.name, tt.want, result)

257-300: LGTM with suggestion for additional test case

The Clone test is well-structured and covers the basic cases. Consider adding a test case to verify that mutations to the cloned object don't affect the original:

{
    name: "clone mutations don't affect original",
    file: &File{
        name: "test",
        children: []*File{{name: "child"}},
    },
    verify: func(t *testing.T, original, cloned *File) {
        cloned.name = "modified"
        cloned.children[0].name = "modified_child"
        assert.Equal(t, "test", original.name)
        assert.Equal(t, "child", original.children[0].name)
    },
},

302-313: Consider expanding test coverage and converting to table-driven format

While the test is functional, it could be more comprehensive. Consider:

  1. Converting to table-driven format for consistency with other tests
  2. Adding edge cases (nil file, empty files array)
  3. Testing more complex nested structures
func Test_FilePath(t *testing.T) {
    tests := []struct {
        name string
        file *File
        want []string
    }{
        {
            name: "single file",
            file: &File{
                files: []*File{{path: "/hello/c.txt"}},
            },
            want: []string{"/hello/c.txt"},
        },
        {
            name: "nil file",
            file: nil,
            want: nil,
        },
        {
            name: "empty files",
            file: &File{files: []*File{}},
            want: []string{},
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            assert.Equal(t, tt.want, tt.file.FilePaths())
        })
    }
}

89-89: Fix typo in test name

Correct the spelling of "empyy" to "empty".

-			name:  "file object is empyy",
+			name:  "file object is empty",
server/pkg/asset/builder_test.go (1)

223-224: Add FlatFiles to MustBuild test cases

The FlatFiles builder method is correctly added to the main test cases, but it's missing from the TestBuilder_MustBuild test cases. Consider adding it there as well for consistency and complete coverage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4c24a9c and 7f5b07f.

⛔ Files ignored due to path filters (1)
  • go.work.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • server/pkg/asset/asset_test.go (2 hunks)
  • server/pkg/asset/builder_test.go (4 hunks)
  • server/pkg/asset/file_test.go (4 hunks)
  • server/pkg/asset/preview_type_test.go (3 hunks)
  • server/pkg/asset/status_test.go (1 hunks)
  • server/pkg/asset/upload_builder_test.go (1 hunks)
  • server/pkg/asset/upload_test.go (1 hunks)
🔇 Additional comments (8)
server/pkg/asset/upload_test.go (1)

1-9: LGTM! Clean and minimal imports.

The package declaration and imports are appropriate for the test file.

server/pkg/asset/upload_builder_test.go (1)

1-9: LGTM! Clean and well-organized imports.

The package declaration and imports follow Go best practices with proper separation between standard library and third-party packages.

server/pkg/asset/asset_test.go (2)

50-50: LGTM!

The assertion follows the established testing pattern and is properly placed among other field verifications.


Line range hint 1-156: Consider implementing test coverage tracking.

Since this PR aims to increase test coverage, consider adding a coverage badge to the README.md and setting up coverage thresholds in the CI pipeline to maintain high test coverage over time.

Let's check if coverage tracking is already in place:

server/pkg/asset/preview_type_test.go (2)

215-215: LGTM: Clean struct initialization syntax.

The removal of trailing commas improves code consistency.

Also applies to: 223-223


281-284: LGTM: Good addition of edge case test.

Testing empty extension input improves coverage and ensures robust handling of edge cases.

server/pkg/asset/file_test.go (1)

4-4: LGTM: Good defensive programming practice!

The addition of nil object tests is a valuable enhancement to the test coverage, ensuring that the code handles nil receivers gracefully by returning appropriate zero values.

Also applies to: 31-37

server/pkg/asset/builder_test.go (1)

31-31: LGTM: Clean addition of flatFiles field

The new field follows the codebase's naming conventions and is appropriately typed.

Comment on lines 16 to 202
projectID := NewProjectID()
ubWithData := &UploadBuilder{
u: &Upload{
uuid: "1",
project: projectID,
fileName: "file.test",
contentLength: int64(1),
expiresAt: time.Now(),
},
}

timeNow := time.Now
assert.Equal(t, ubWithData, ubWithData.UUID("1"))
assert.Equal(t, ubWithData, ubWithData.Project(projectID))
assert.Equal(t, ubWithData, ubWithData.FileName("file.test"))
assert.Equal(t, ubWithData, ubWithData.ContentLength(int64(1)))
assert.Equal(t, ubWithData, ubWithData.ExpiresAt(timeNow()))
assert.Equal(t, ubWithData.u, ubWithData.Build())
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add negative test cases for better coverage.

The test suite would benefit from negative test cases to verify proper handling of invalid inputs.

Consider adding tests for:

  • Empty or invalid UUIDs
  • Nil ProjectID
  • Empty file names
  • Negative content length
  • Past expiration times

Example addition:

func TestUploadBuilder_Validation(t *testing.T) {
	tests := []struct {
		name    string
		build   func() *Upload
		wantErr bool
	}{
		{
			name: "negative content length",
			build: func() *Upload {
				return NewUpload().
					ContentLength(-1).
					Build()
			},
			wantErr: true,
		},
		// Add more negative test cases
	}
	// ... implement test loop
}

Comment on lines 27 to 28
timeNow := time.Now
assert.Equal(t, ubWithData, ubWithData.UUID("1"))
Copy link

@coderabbitai coderabbitai bot Nov 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential test flakiness with time.Now.

Using time.Now() directly can make tests non-deterministic. Consider using a fixed timestamp for testing.

-	timeNow := time.Now
+	fixedTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
-	assert.Equal(t, ubWithData, ubWithData.ExpiresAt(timeNow()))
+	assert.Equal(t, ubWithData, ubWithData.ExpiresAt(fixedTime))

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasonkarel plz use util.MockNow from reearthx

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines 28 to 33
assert.Equal(t, ubWithData, ubWithData.UUID("1"))
assert.Equal(t, ubWithData, ubWithData.Project(projectID))
assert.Equal(t, ubWithData, ubWithData.FileName("file.test"))
assert.Equal(t, ubWithData, ubWithData.ContentLength(int64(1)))
assert.Equal(t, ubWithData, ubWithData.ExpiresAt(timeNow()))
assert.Equal(t, ubWithData.u, ubWithData.Build())
Copy link

@coderabbitai coderabbitai bot Nov 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation between builder method calls.

The current test only verifies that the builder is returned. Consider validating the actual state of the Upload struct after each builder method call.

+	// Test UUID
 	assert.Equal(t, ubWithData, ubWithData.UUID("1"))
+	assert.Equal(t, "1", ubWithData.u.uuid)
+
+	// Test Project
 	assert.Equal(t, ubWithData, ubWithData.Project(projectID))
+	assert.Equal(t, projectID, ubWithData.u.project)
+
+	// Test FileName
 	assert.Equal(t, ubWithData, ubWithData.FileName("file.test"))
+	assert.Equal(t, "file.test", ubWithData.u.fileName)
+
+	// Test ContentLength
 	assert.Equal(t, ubWithData, ubWithData.ContentLength(int64(1)))
+	assert.Equal(t, int64(1), ubWithData.u.contentLength)

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ignoring this since it returns builder object.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasonkarel, understood. Thanks for letting me know.


✏️ Learnings added
Learnt from: jasonkarel
PR: reearth/reearth-cms#1302
File: server/pkg/asset/upload_builder_test.go:28-33
Timestamp: 2024-11-12T05:50:03.778Z
Learning: In this codebase, it's acceptable for tests to verify that the builder object is returned without checking the internal state after each method call.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@@ -53,6 +54,7 @@ func TestBuilder_Build(t *testing.T) {
uuid: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
thread: thid,
archiveExtractionStatus: lo.ToPtr(ArchiveExtractionStatusPending),
flatFiles: false,
Copy link

@coderabbitai coderabbitai bot Nov 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add test case for true flatFiles value

While the current test case covers flatFiles: false, consider adding another test case where flatFiles is set to true to ensure complete coverage of this new field's behavior.

Here's a suggested additional test case:

 tests := Tests{
+    {
+        name: "should create an asset with flatFiles enabled",
+        input: Input{
+            id:                      aid,
+            project:                 pid,
+            createdAt:               tim,
+            createdByUser:           uid,
+            fileName:                "hoge",
+            size:                    size,
+            previewType:             lo.ToPtr(PreviewTypeImage),
+            uuid:                    "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
+            thread:                  thid,
+            archiveExtractionStatus: lo.ToPtr(ArchiveExtractionStatusPending),
+            flatFiles:               true,
+        },
+        want: &Asset{
+            id:                      aid,
+            project:                 pid,
+            createdAt:               tim,
+            user:                    &uid,
+            fileName:                "hoge",
+            size:                    size,
+            previewType:             PreviewTypeFromRef(lo.ToPtr("image")),
+            uuid:                    "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
+            thread:                  thid,
+            archiveExtractionStatus: lo.ToPtr(ArchiveExtractionStatusPending),
+            flatFiles:               true,
+        },
+    },

Also applies to: 70-70

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the code deosnt handle if flatfiles is true/ false.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasonkarel, understood. Since the code doesn't handle different behaviors when flatFiles is true or false, adding an additional test case isn't necessary. Thank you for the clarification.


✏️ Learnings added
Learnt from: jasonkarel
PR: reearth/reearth-cms#1302
File: server/pkg/asset/builder_test.go:57-57
Timestamp: 2024-11-12T05:50:23.518Z
Learning: In the `server/pkg/asset` package, the `flatFiles` field does not affect behavior based on its value, so adding test cases for different `flatFiles` values is unnecessary.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@jasonkarel jasonkarel marked this pull request as ready for review November 12, 2024 10:12
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: 6

🧹 Outside diff range and nitpick comments (9)
server/pkg/integrationapi/project_test.go (1)

12-15: Consider making the test more deterministic and reusable

While the setup is functional, consider these improvements:

  1. Use a fixed timestamp for better test reliability
  2. Extract project creation into a helper function for potential reuse in other tests
+func createTestProject(t *testing.T) *project.Project {
+    // Use a fixed timestamp for deterministic tests
+    fixedTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+    return project.New().
+        ID(project.NewID()).
+        Workspace(project.NewWorkspaceID()).
+        Name("test").
+        Description("testing").
+        Alias("testalias").
+        UpdatedAt(fixedTime).
+        MustBuild()
+}

 func Test_NewProject(t *testing.T) {
-    timeNow := time.Now()
-    p1 := project.New().ID(project.NewID()).Workspace(project.NewWorkspaceID()).
-        Name("test").Description("testing").Alias("testalias").UpdatedAt(timeNow).MustBuild()
+    p1 := createTestProject(t)
server/pkg/integrationapi/comment_test.go (1)

12-20: Consider improving variable names and adding setup documentation

While the setup is functionally correct, consider:

  1. Using more descriptive variable names (e.g., userID instead of uid, userComment instead of c)
  2. Adding comments to explain the test setup and data preparation
-	uid := thread.NewUserID()
-	iid := operator.NewIntegrationID()
-	authorUser := operator.OperatorFromUser(uid)
-	authorIntegration := operator.OperatorFromIntegration(iid)
-	c := thread.NewComment(thread.NewCommentID(), authorUser, "test")
-	cIntegration := thread.NewComment(thread.NewCommentID(), authorIntegration, "test")
-	authorID := c.Author().User().Ref()
-	authorIntegrationID := cIntegration.Author().Integration().Ref()
+	// Create test user and integration IDs
+	userID := thread.NewUserID()
+	integrationID := operator.NewIntegrationID()
+
+	// Create operators for both user and integration
+	userOperator := operator.OperatorFromUser(userID)
+	integrationOperator := operator.OperatorFromIntegration(integrationID)
+
+	// Create test comments with different author types
+	userComment := thread.NewComment(thread.NewCommentID(), userOperator, "test")
+	integrationComment := thread.NewComment(thread.NewCommentID(), integrationOperator, "test")
+
+	// Extract author references for assertions
+	userAuthorID := userComment.Author().User().Ref()
+	integrationAuthorID := integrationComment.Author().Integration().Ref()
server/pkg/integrationapi/item_export_test.go (2)

20-63: Well-structured test cases with room for enhancement

The table-driven tests are comprehensive and cover all geometry types including the nil case. Consider these enhancements:

  1. Add more descriptive test failure messages
  2. Include negative test cases for invalid geometry types

Consider this improvement for more descriptive failure messages:

-		assert.Equal(t, tt.expected, result, "For input %v, expected %v but got %v", tt.input, tt.expected, result)
+		assert.Equal(t, tt.expected, result, "Converting geometry type: input=%v, want=%v, got=%v", tt.input, tt.expected, result)

75-76: Document the geometry string format

The hardcoded geometry string would benefit from a comment explaining its structure and format for better maintainability.

+	// Example Point geometry in GeoJSON format
 	str := "{\"coordinates\":[139.28179282584915,36.58570985749664],\"type\":\"Point\"}"
server/pkg/integrationapi/value_test.go (2)

10-115: Consider enhancing test robustness.

While the test coverage is comprehensive, consider these improvements:

  1. Use a test assertion library like testify/assert for more readable assertions and better error messages.
  2. Add explicit nil safety checks when dereferencing pointers in the actual implementation.

Example refactor using testify:

+import "github.com/stretchr/testify/assert"

 func TestFromValueType(t *testing.T) {
     // ... test cases ...
     for _, tt := range tests {
         t.Run(tt.name, func(t *testing.T) {
             result := FromValueType(tt.input)
-            if result != tt.expected {
-                t.Errorf("expected %v, got %v", tt.expected, result)
-            }
+            assert.Equal(t, tt.expected, result)
         })
     }
 }

117-218: Consider additional edge cases and assertion improvements.

The test coverage is good, but consider these enhancements:

  1. Use a test assertion library for more readable assertions (same as previous function).
  2. Add test cases for empty string input and special characters.

Example additional test cases:

 tests := []struct {
     // ... existing test cases ...
+    {
+        name:     "Empty string type",
+        input:    value.Type(""),
+        expected: "",
+    },
+    {
+        name:     "Special characters type",
+        input:    value.Type("@#$%"),
+        expected: "",
+    },
 }
server/pkg/integrationapi/asset_test.go (1)

58-119: Consider adding more test cases for better coverage.

The test function has a good structure using table-driven tests. However, it could be enhanced with additional test cases to cover:

  • Partial nil cases (nil asset with valid file or vice versa)
  • Different file types and sizes
  • Various preview types
  • Empty strings for name/path
server/pkg/integrationapi/condition_test.go (2)

13-282: Consider standardizing test error messages and improving test names.

While the test implementations are solid, consider these improvements for consistency and clarity:

  1. Standardize error messages across all operator tests (some use assert.Equal, others use t.Errorf).
  2. Make test names more descriptive (e.g., "equals" -> "should_convert_equals_operator").

Example improvement for test names:

 		{
-			name:     "equals",
+			name:     "should_convert_equals_operator_successfully",
 			input:    ConditionBoolOperatorEquals,
 			expected: view.BoolOperatorEquals,
 		},

284-320: Maintain consistency with other test implementations.

These tests differ in style from the earlier ones:

  1. They don't use named test cases (missing the name field in test structs).
  2. They use t.Errorf instead of assert.Equal like other tests.

Consider aligning the implementation style with other tests in the file.

Example alignment:

 	tests := []struct {
+		name     string
 		input    ConditionNullableOperator
 		expected view.NullableOperator
 	}{
-		{Empty, view.NullableOperatorEmpty},
+		{
+			name:     "should_convert_empty_operator",
+			input:    Empty,
+			expected: view.NullableOperatorEmpty,
+		},
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7f5b07f and 4d904a8.

📒 Files selected for processing (7)
  • server/pkg/asset/upload_builder_test.go (1 hunks)
  • server/pkg/integrationapi/asset_test.go (2 hunks)
  • server/pkg/integrationapi/comment_test.go (1 hunks)
  • server/pkg/integrationapi/condition_test.go (1 hunks)
  • server/pkg/integrationapi/item_export_test.go (1 hunks)
  • server/pkg/integrationapi/project_test.go (1 hunks)
  • server/pkg/integrationapi/value_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/pkg/asset/upload_builder_test.go
🔇 Additional comments (13)
server/pkg/integrationapi/project_test.go (1)

1-10: LGTM: Package declaration and imports are well-organized

The package name matches the directory, and all imports are properly utilized.

server/pkg/integrationapi/comment_test.go (3)

1-11: LGTM: Well-organized imports

The imports are clean and all are being utilized in the test implementation.


55-61: LGTM: Clean test execution

The test execution follows best practices:

  • Uses subtests for better error reporting
  • Uses clear assertions

21-53: Consider adding more edge cases

While the current test cases cover the basic scenarios, consider adding tests for:

  1. Empty content
  2. Maximum content length (if applicable)
  3. Special characters in content
  4. Different timestamp scenarios
server/pkg/integrationapi/item_export_test.go (2)

1-18: LGTM! Well-structured test file setup

The package structure and imports are well-organized, following Go conventions and including all necessary dependencies for testing.


1-143: Verify test coverage improvement

While the tests are well-structured, let's verify that they actually increase the coverage as intended in the PR objectives.

server/pkg/integrationapi/value_test.go (2)

1-9: LGTM! Clean imports and good use of helper package.

The imports are minimal and well-organized. Good practice using the lo package for pointer operations.


1-218: Overall excellent test coverage with good structure!

The test file successfully achieves the PR objective of increasing test coverage. The table-driven tests are well-organized and cover most scenarios effectively. While there are some minor improvements suggested above, the overall quality of the tests is good.

server/pkg/integrationapi/asset_test.go (3)

54-55: LGTM! Good addition of nil input validation.

The nil check is a valuable addition that ensures proper handling of edge cases.


121-167: LGTM! Comprehensive status conversion tests.

Excellent test coverage with:

  • All possible status values
  • Edge cases (nil, unknown status)
  • Clear test case names
  • Proper value comparison

169-232: LGTM! Verify complete preview type coverage.

Excellent test coverage with comprehensive cases. Let's verify that all preview types from the asset package are covered.

✅ Verification successful

Based on the results from the shell scripts, I can now generate the final response:

All preview types are properly covered ✓

The test cases in TestToPreviewType cover all preview types defined in server/pkg/asset/preview_type.go:

  • PreviewTypeImage
  • PreviewTypeImageSvg
  • PreviewTypeGeo
  • PreviewTypeGeo3dTiles
  • PreviewTypeGeoMvt
  • PreviewTypeModel3d
  • PreviewTypeCSV
  • PreviewTypeUnknown

Plus edge cases for nil and unrecognized types.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all preview types from the asset package are covered in the tests

# Find all preview type constants in the asset package
echo "Preview types defined in asset package:"
rg -A 1 "PreviewType[A-Z][a-zA-Z0-9]+" server/pkg/asset

# Compare with test coverage
echo -e "\nPreview types tested in TestToPreviewType:"
rg "PreviewType[A-Z][a-zA-Z0-9]+" server/pkg/integrationapi/asset_test.go

Length of output: 13747

server/pkg/integrationapi/condition_test.go (2)

1-11: LGTM! Clean import organization.

The imports are well-organized with standard library packages separated from third-party imports.


353-708: LGTM! Comprehensive test coverage.

The TestConditionInto function provides excellent coverage:

  • Tests all condition types
  • Handles complex nested conditions (AND/OR)
  • Includes edge cases (nil, empty conditions)
  • Uses clear test case names

Comment on lines 35 to 41
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := NewProject(p1)
assert.Equal(t, tt.want, result)
})
}
}
Copy link

@coderabbitai coderabbitai bot Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix incorrect test parameter and consider parallel execution

There's a bug in the test execution where p1 is used instead of tt.p. Also, consider enabling parallel test execution.

 for _, tt := range tests {
     t.Run(tt.name, func(t *testing.T) {
+        t.Parallel()
-        result := NewProject(p1)
+        result := NewProject(tt.p)
         assert.Equal(t, tt.want, result)
     })
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := NewProject(p1)
assert.Equal(t, tt.want, result)
})
}
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
result := NewProject(tt.p)
assert.Equal(t, tt.want, result)
})
}
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasonkarel, thank you for addressing this issue!

(_/)
(^‿^)
(")_(")


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

server/pkg/integrationapi/project_test.go Show resolved Hide resolved
Content: lo.ToPtr("test"),
CreatedAt: lo.ToPtr(cIntegration.CreatedAt()),
Id: cIntegration.ID().Ref(),
AuthorType: lo.ToPtr(Integrtaion),
Copy link

@coderabbitai coderabbitai bot Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix typo in AuthorType value

There's a typo in the integration author type value: Integrtaion should be Integration.

-				AuthorType: lo.ToPtr(Integrtaion),
+				AuthorType: lo.ToPtr(Integration),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AuthorType: lo.ToPtr(Integrtaion),
AuthorType: lo.ToPtr(Integration),

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will fix the typo issue later as it will change the non unit testing code. the task in here is the unit testing code

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasonkarel, understood. If you'd like, I can open a GitHub issue to track this typo fix for later.

Comment on lines 138 to 142
if (err != nil) == tt.expectError {
fmt.Printf("Error is not matched")
}
})
Copy link

@coderabbitai coderabbitai bot Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix incorrect error assertion

The current error assertion logic is incorrect and only prints a message instead of failing the test.

Apply this fix:

-			if (err != nil) == tt.expectError {
-				fmt.Printf("Error is not matched")
-			}
+			if tt.expectError {
+				assert.Error(t, err, "Expected an error but got none")
+			} else {
+				assert.NoError(t, err, "Expected no error but got: %v", err)
+			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (err != nil) == tt.expectError {
fmt.Printf("Error is not matched")
}
})
if tt.expectError {
assert.Error(t, err, "Expected an error but got none")
} else {
assert.NoError(t, err, "Expected no error but got: %v", err)
}
})

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasonkarel plz fix this one

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

server/pkg/integrationapi/value_test.go Outdated Show resolved Hide resolved
server/pkg/integrationapi/condition_test.go Outdated Show resolved Hide resolved
Copy link
Contributor

@yk-eukarya yk-eukarya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the parallel test whenever possible

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

🧹 Outside diff range and nitpick comments (2)
server/pkg/integrationapi/asset_test.go (2)

58-119: Consider adding more edge cases to strengthen test coverage

The table-driven test implementation looks good and follows Go best practices. Consider adding these additional test cases to strengthen coverage:

  • Partial nil cases (nil asset with valid file or vice versa)
  • Empty string URL
  • Zero-value time
  • Invalid/empty IDs

114-116: Consider standardizing assertion methods

For consistency, consider standardizing the assertion methods across all tests. Currently, the file mixes:

  • reflect.DeepEqual with manual error messages
  • assert.Equal
  • assert.Nil

Consider using assert package consistently across all tests for better readability and consistent error messages.

Also applies to: 163-165, 232-233

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1be6979 and 7e739a0.

📒 Files selected for processing (3)
  • server/pkg/asset/upload_builder_test.go (1 hunks)
  • server/pkg/integrationapi/asset_test.go (2 hunks)
  • server/pkg/integrationapi/condition_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/pkg/asset/upload_builder_test.go
  • server/pkg/integrationapi/condition_test.go
🔇 Additional comments (3)
server/pkg/integrationapi/asset_test.go (3)

54-56: LGTM: Good addition of nil case test

The addition of the nil input test case improves edge case coverage.


133-136: Use defined constants for status values

As mentioned in the previous review, please use the defined constants for status values instead of string literals.

Also applies to: 138-141, 143-146, 148-151


170-234: LGTM: Comprehensive preview type testing

Excellent implementation with:

  • Complete coverage of all preview types
  • Good handling of edge cases (nil, unknown, unrecognized)
  • Clear test case organization
  • Proper use of parallel test execution

@jasonkarel jasonkarel force-pushed the chore-increase-package-ut-coverage branch from ace4825 to b8bc793 Compare November 18, 2024 10:38
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 and nitpick comments (6)
server/pkg/integrationapi/asset_test.go (2)

58-119: Consider adding more test cases for better coverage.

While the current implementation is good, consider adding these test cases:

  1. Empty strings for name/path
  2. Zero values for size
  3. Invalid URL formats
  4. Partial nil cases (nil asset with valid file or vice versa)

Also, consider using assert.Equal instead of reflect.DeepEqual for better error messages and consistency with other tests in the file.

Example additional test cases:

 tests := []struct {
   // ... existing fields
 }{
   // ... existing test cases
+  {
+    name: "empty strings",
+    a:    a,
+    f:    asset.NewFile().Name("").Path("").ContentType("").Size(0).Build(),
+    url:  "",
+    all:  true,
+    want: &Asset{
+      // ... expected values for empty strings
+    },
+  },
+  {
+    name: "nil asset with valid file",
+    a:    nil,
+    f:    f1,
+    url:  "www.",
+    all:  true,
+    want: nil,
+  },
 }

121-168: Consider using assert.Equal for consistency.

The test implementation is comprehensive and well-structured. However, for consistency with other tests in the file (like TestToPreviewType), consider using assert.Equal instead of reflect.DeepEqual.

-			if !reflect.DeepEqual(result, tt.expected) {
-				t.Errorf("ToAssetArchiveExtractionStatus() expected %v, got %v", tt.expected, result)
-			}
+			assert.Equal(t, tt.expected, result)
server/pkg/asset/file_test.go (4)

32-37: LGTM! Consider testing additional nil cases.

Good addition of nil object tests to prevent null pointer dereferences. The tests verify that all getter methods handle nil gracefully.

Consider adding nil tests for other methods like SetName(), AppendChild(), and IsDir() for complete coverage.


71-101: LGTM! Fix typo in test case name.

Good refactoring to table-driven tests. The test cases effectively cover both success and nil scenarios.

Fix the typo in the test case name:

-			name:  "file object is empyy",
+			name:  "file object is empty",

228-255: LGTM! Consider additional edge cases.

Good refactoring to table-driven tests with proper nil handling.

Consider adding test cases for:

  • Invalid UUID format
  • Empty path in file object
  • Special characters in path

257-300: LGTM! Consider adding mutation verification.

Well-structured test with good coverage of both success and nil cases.

Consider adding a test case that verifies modifications to the cloned object don't affect the original:

t.Run("verify deep copy", func(t *testing.T) {
    original := &File{name: "test", children: []*File{{name: "child"}}}
    clone := original.Clone()
    clone.name = "modified"
    clone.children[0].name = "modified_child"
    
    assert.Equal(t, "test", original.name)
    assert.Equal(t, "child", original.children[0].name)
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ace4825 and 9c03f38.

📒 Files selected for processing (12)
  • server/pkg/asset/asset_test.go (2 hunks)
  • server/pkg/asset/builder_test.go (4 hunks)
  • server/pkg/asset/file_test.go (4 hunks)
  • server/pkg/asset/preview_type_test.go (3 hunks)
  • server/pkg/asset/status_test.go (1 hunks)
  • server/pkg/asset/upload_builder_test.go (1 hunks)
  • server/pkg/asset/upload_test.go (1 hunks)
  • server/pkg/integrationapi/asset_test.go (2 hunks)
  • server/pkg/integrationapi/comment_test.go (1 hunks)
  • server/pkg/integrationapi/condition_test.go (1 hunks)
  • server/pkg/integrationapi/item_export_test.go (1 hunks)
  • server/pkg/integrationapi/project_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (10)
  • server/pkg/asset/asset_test.go
  • server/pkg/asset/builder_test.go
  • server/pkg/asset/preview_type_test.go
  • server/pkg/asset/status_test.go
  • server/pkg/asset/upload_builder_test.go
  • server/pkg/asset/upload_test.go
  • server/pkg/integrationapi/comment_test.go
  • server/pkg/integrationapi/condition_test.go
  • server/pkg/integrationapi/item_export_test.go
  • server/pkg/integrationapi/project_test.go
🔇 Additional comments (2)
server/pkg/integrationapi/asset_test.go (2)

54-55: LGTM: Good addition of nil input test case.

The added test case improves coverage by verifying the behavior with nil input.


170-234: LGTM: Well-implemented comprehensive test coverage.

The test is well-structured with:

  • Comprehensive coverage of all preview types
  • Proper handling of edge cases (nil, unknown types)
  • Good use of parallel test execution
  • Consistent assertion style

server/pkg/asset/file_test.go Outdated Show resolved Hide resolved
@jasonkarel jasonkarel changed the title chore: Increase domain package unit test coverage (asset and integrationapi) chore(server): Increase domain package unit test coverage (asset and integrationapi) Nov 20, 2024
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

🧹 Outside diff range and nitpick comments (5)
server/pkg/asset/preview_type_test.go (1)

324-327: Simplify the test implementation for better readability.

The test uses an unnecessarily complex IIFE (Immediately Invoked Function Expression). Consider simplifying it for better readability while maintaining the same test coverage.

-func TestPreviewType_Prev(t *testing.T) {
-	t.Parallel()
-	assert.Equal(t, func() *PreviewType { pt := PreviewType("image"); return &pt }(), PreviewTypeImage.Ref())
-}
+func TestPreviewType_Prev(t *testing.T) {
+	t.Parallel()
+	expected := PreviewType("image")
+	assert.Equal(t, &expected, PreviewTypeImage.Ref())
+}
server/pkg/integrationapi/asset_test.go (1)

57-117: Consider adding more test cases for better coverage

While the current test cases cover basic success and nil scenarios, consider adding these cases to improve coverage:

  • Asset without file
  • File without asset
  • Empty URL
  • Different preview types
  • Different content types

Example additional test cases:

 tests := []struct {
   // ... existing fields
 }{
   // ... existing test cases
+  {
+    name: "asset without file",
+    a:    a,
+    f:    nil,
+    url:  "www.",
+    all:  true,
+    want: &Asset{
+      Id:        a.ID(),
+      Url:       "www.",
+      CreatedAt: timeNow,
+      TotalSize: lo.ToPtr(float32(100)),
+      ProjectId: pid,
+    },
+  },
+  {
+    name: "empty url",
+    a:    a,
+    f:    f1,
+    url:  "",
+    all:  true,
+    want: &Asset{
+      // ... expected fields with empty URL
+    },
+  },
 }
server/pkg/asset/file_test.go (3)

70-99: Fix typo in test name

The refactoring to table-driven tests is excellent and improves test maintainability. However, there's a typo in the test name "empyy" which should be "empty".

-			name:  "file object is empyy",
+			name:  "file object is empty",

254-296: Consider adding mutation verification test

The test implementation is well-structured and covers both success and nil cases. Consider adding a test case that verifies the independence of the cloned object by mutating the original and ensuring the clone remains unchanged.

Example test case to add:

{
    name: "verify independent clone",
    file: &File{
        name: "test",
        children: []*File{{name: "child"}},
    },
    verify: func(t *testing.T, original, cloned *File) {
        original.name = "modified"
        original.children[0].name = "modified_child"
        assert.Equal(t, "test", cloned.name)
        assert.Equal(t, "child", cloned.children[0].name)
    },
},

298-310: Consider expanding test cases using table-driven tests

While the current test case is valid, consider refactoring to a table-driven test to include additional cases such as:

  • nil file object
  • empty files array
  • nested file structures
  • files with special characters in paths

Example structure:

tests := []struct {
    name  string
    file  *File
    want  []string
}{
    {
        name: "success with single file",
        file: &File{
            name: "hello.zip",
            files: []*File{{path: "/hello/c.txt"}},
        },
        want: []string{"/hello/c.txt"},
    },
    {
        name: "nil file object",
        file: nil,
        want: nil,
    },
    {
        name: "empty files array",
        file: &File{files: []*File{}},
        want: []string{},
    },
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9c03f38 and e86d83e.

📒 Files selected for processing (7)
  • server/pkg/asset/file_test.go (3 hunks)
  • server/pkg/asset/preview_type_test.go (3 hunks)
  • server/pkg/asset/upload_test.go (1 hunks)
  • server/pkg/integrationapi/asset_test.go (2 hunks)
  • server/pkg/integrationapi/comment_test.go (1 hunks)
  • server/pkg/integrationapi/item_export_test.go (1 hunks)
  • server/pkg/integrationapi/project_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • server/pkg/asset/upload_test.go
  • server/pkg/integrationapi/comment_test.go
  • server/pkg/integrationapi/item_export_test.go
  • server/pkg/integrationapi/project_test.go
🔇 Additional comments (7)
server/pkg/asset/preview_type_test.go (1)

281-284: LGTM! Good addition of edge case testing.

The test case for empty extension handling improves coverage of boundary conditions.

server/pkg/integrationapi/asset_test.go (4)

53-54: LGTM: Good addition of nil input test case

The addition of the nil input test case improves edge case coverage.


131-149: Use defined constants for status values

As suggested in the previous review, use the defined constants for status values instead of string literals.


166-230: LGTM: Well-structured and comprehensive preview type tests

The test cases are well-organized and provide comprehensive coverage of:

  • All preview types
  • Nil input handling
  • Unrecognized type handling

Line range hint 1-230: LGTM: Well-structured test file with good practices

The test file demonstrates several good practices:

  • Consistent use of table-driven tests
  • Parallel test execution
  • Clear test case naming
  • Good mix of happy path and edge cases

This contributes well to the PR objective of increasing test coverage.

server/pkg/asset/file_test.go (2)

30-36: Great addition of nil object handling tests!

The addition of nil object tests improves the robustness of the test suite by verifying that the File methods handle nil receivers gracefully, returning appropriate zero values.


226-252: Well-structured table-driven tests!

The refactoring improves test maintainability and readability. Good addition of the nil case and proper use of parallel test execution.

@jasonkarel jasonkarel merged commit cfd04a4 into main Nov 29, 2024
21 checks passed
@jasonkarel jasonkarel deleted the chore-increase-package-ut-coverage branch November 29, 2024 09:08
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