Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cbor): Add support for CBOR encoding #94

Merged
merged 5 commits into from
Oct 20, 2024

Conversation

imsk17
Copy link
Contributor

@imsk17 imsk17 commented Oct 5, 2024

Required for implementation of 3156

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced functions for encoding and decoding CBOR data in the utils package, enhancing data handling capabilities.
  • Tests

    • Added new tests for verifying the functionality of CBOR encoding and decoding processes, ensuring reliability and correctness.

@imsk17 imsk17 requested a review from a team as a code owner October 5, 2024 18:21
@imsk17 imsk17 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team October 5, 2024 18:21
Copy link

coderabbitai bot commented Oct 5, 2024

Walkthrough

The changes introduce two new function types in the utils package for CBOR encoding and decoding: CBORMarshal for encoding data into CBOR format and CBORUnmarshal for decoding CBOR data back into variables. Additionally, several new test functions are added to cbor_test.go to validate these functionalities, ensuring that various scenarios, including empty and uninitialized structures, are properly handled during encoding and decoding.

Changes

File Change Summary
cbor.go Added type CBORMarshal func(v any) ([]byte, error) and CBORUnmarshal func(data []byte, v any) error in package utils.
cbor_test.go Added test functions: Test_DefaultCBOREncoder(t *testing.T), Test_DefaultCBORDecoder(t *testing.T), Test_DefaultCBOREncoderWithEmptyString(t *testing.T), Test_DefaultCBORDecoderWithEmptyString(t *testing.T), Test_DefaultCBOREncoderWithUnitializedStruct(t *testing.T), and Test_DefaultCBORDecoderWithUnitializedStruct(t *testing.T) for testing encoding and decoding.

Poem

In the land of code where rabbits play,
New functions hop in, brightening the day.
CBOR's magic, both encode and decode,
With tests to ensure they follow the road.
Let's celebrate this leap, so grand,
In the world of bytes, we take a stand! 🐇✨


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 or @coderabbitai title 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

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

🧹 Outside diff range and nitpick comments (2)
cbor.go (2)

3-4: LGTM with a minor suggestion for the comment.

The CBORMarshal type definition looks good. It's well-designed to handle various input types and provides appropriate return values for the encoded data and potential errors.

Consider expanding the comment slightly to provide more context:

-// CBORMarshal returns the CBOR encoding of v.
+// CBORMarshal is a function type that returns the CBOR encoding of v.
+// It can be used to define custom CBOR marshaling functions.

1-9: Good start on CBOR functionality, consider next steps.

The introduction of CBORMarshal and CBORUnmarshal types provides a solid foundation for CBOR functionality in the utils package. These type definitions offer a clear interface for encoding and decoding CBOR data.

To complete the CBOR implementation, consider the following next steps:

  1. Implement the actual CBOR encoding and decoding logic, possibly in separate files.
  2. Provide concrete implementations of these function types, perhaps as package-level variables or functions that return these types.
  3. Add unit tests to ensure the correctness of the CBOR operations.
  4. Consider adding examples in the package documentation to demonstrate usage.

These steps will help fully realize the CBOR functionality outlined in the PR objectives.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cefa447 and e6222bb.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (2)
  • cbor.go (1 hunks)
  • cbor_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint
cbor_test.go

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)

🔇 Additional comments (4)
cbor_test.go (4)

3-9: LGTM: Imports are appropriate and concise.

The import statements are well-structured and include all necessary packages for CBOR operations, testing, and hex encoding. The use of the github.com/fxamacker/cbor/v2 package for CBOR operations is a good choice.


11-26: LGTM: Well-structured CBOR encoding test.

The Test_DefaultCBOREncoder function is well-implemented:

  1. It uses parallel testing for efficiency.
  2. The CBORMarshal type alias allows for easy mocking or replacement of the encoding function.
  3. The test case covers a basic scenario with a simple structure.

Good job on following testing best practices!

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


28-40: LGTM: Well-structured CBOR decoding test.

The Test_DefaultCBORDecoder function is well-implemented:

  1. It uses parallel testing for efficiency.
  2. The CBORUnmarshal type alias allows for easy mocking or replacement of the decoding function.
  3. The test case covers a basic scenario and uses the same hex string as in the encoder test, ensuring consistency.

Excellent job on maintaining consistency with the encoder test and following testing best practices!

🧰 Tools
🪛 golangci-lint

34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


15-17: Verify the existence of sampleStructure type.

The test uses a sampleStructure type, which is not defined in this file. Please ensure that this type is defined in another file within the same package or consider adding its definition to this file for better readability and self-containment of the test.

✅ Verification successful

SampleStructure Type Exists in the Package

The sampleStructure type is defined in json_test.go within the same package, confirming its existence.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the definition of sampleStructure in the package

# Test: Search for the struct definition
ast-grep --lang go --pattern 'type sampleStructure struct { $$$  }'

# If not found as a struct, check if it's defined as a type alias
ast-grep --lang go --pattern 'type sampleStructure = $_'

Length of output: 258

cbor.go Outdated Show resolved Hide resolved
cbor_test.go Outdated Show resolved Hide resolved
@gaby
Copy link
Member

gaby commented Oct 5, 2024

@imsk17 This is the wrong repo? It should be https://github.com/gofiber/fiber

@gaby
Copy link
Member

gaby commented Oct 8, 2024

@imsk17 Closing this. The implementation is for gofiber/fiber like your previous PR. It just had the wrong target branch.

Please open the PR in https://github.com/gofiber/fiber

@gaby gaby closed this Oct 8, 2024
@gofiber gofiber deleted a comment from codecov bot Oct 8, 2024
@imsk17
Copy link
Contributor Author

imsk17 commented Oct 9, 2024

But that repo depends on utils, which is where I have to add the CBOR format first like all other formats.

@gaby gaby reopened this Oct 10, 2024
Copy link

codecov bot commented Oct 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.98%. Comparing base (cefa447) to head (edcc056).
Report is 10 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #94      +/-   ##
==========================================
- Coverage   92.48%   90.98%   -1.50%     
==========================================
  Files           9        9              
  Lines         399      488      +89     
==========================================
+ Hits          369      444      +75     
- Misses         17       31      +14     
  Partials       13       13              
Flag Coverage Δ
unittests 90.98% <ø> (-1.50%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@gaby
Copy link
Member

gaby commented Oct 10, 2024

But that repo depends on utils, which is where I have to add the CBOR format first like all other formats.

I see whatbyou mean, makes sense 💪 PR has been re-opened

@gaby
Copy link
Member

gaby commented Oct 10, 2024

@imsk17 Can you take a look at some of the lint failures and suggestions.

With the makefile you can run make lint locally

@gaby gaby changed the title feat(cbor): add cbor feat(cbor): Add support for CBOR encoding Oct 11, 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 (1)
cbor_test.go (1)

1-43: Overall assessment: Good foundation with room for enhancement.

The cbor_test.go file introduces well-structured tests for CBOR encoding and decoding functionality. The use of parallel testing and basic error handling are commendable. However, there are several areas for improvement:

  1. Expand test coverage with more diverse test cases, including edge cases and complex structures.
  2. Enhance error handling, particularly in the decoding test.
  3. Verify the definitions and imports of CBORMarshal, CBORUnmarshal, and sampleStructure types.

These enhancements will significantly improve the robustness and reliability of the CBOR functionality tests. Consider implementing the suggested changes and running the verification scripts to ensure all types are properly defined and imported.

Would you like assistance in implementing these improvements or generating additional test cases?

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e6222bb and 85e3dd9.

📒 Files selected for processing (1)
  • cbor_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint
cbor_test.go

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)

🔇 Additional comments (4)
cbor_test.go (4)

3-9: LGTM: Imports are appropriate and well-structured.

The imports include all necessary packages for testing, CBOR operations, and assertions. The use of github.com/fxamacker/cbor/v2 for CBOR operations and github.com/stretchr/testify/require for test assertions are good choices.


19-19: Verify type assertions for CBOR operations.

The static analysis tool reports cbor as undefined on lines 19 and 34. However, this appears to be a false positive as the cbor package is correctly imported. The type assertions CBORMarshal = cbor.Marshal and CBORUnmarshal = cbor.Unmarshal are likely correct, assuming CBORMarshal and CBORUnmarshal are defined elsewhere in the package.

To ensure the correctness of these type assertions, please run the following command:

If these types are not defined within the package, consider adding their definitions or adjusting the imports accordingly.

Also applies to: 34-34

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


28-43: LGTM: Well-structured test function with some improvement opportunities.

The Test_DefaultCBORDecoder function is well-structured and uses parallel testing, which is good for efficiency. However, there are a few points to consider:

  1. The test case covers a basic scenario. Consider adding more diverse test cases to ensure robust decoding.
  2. The error handling for hex decoding could be improved. Currently, the test fails silently if hex decoding fails.
  3. The CBORUnmarshal type assertion might be related to the static analysis hints about undefined cbor. Verify that this type is properly defined and imported.

Consider the following improvements:

  1. Add more test cases:
func Test_DefaultCBORDecoder(t *testing.T) {
    t.Parallel()

    testCases := []struct {
        name     string
        input    string
        expected sampleStructure
    }{
        {"basic", "a170696d706f7274616e745f737472696e676b48656c6c6f20576f726c64", sampleStructure{ImportantString: "Hello World"}},
        {"empty", "a170696d706f7274616e745f737472696e6760", sampleStructure{}},
        // Add more test cases here
    }

    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            var ss sampleStructure
            importantString, err := hex.DecodeString(tc.input)
            require.NoError(t, err, "Failed to decode hex string")

            err = cbor.Unmarshal(importantString, &ss)
            require.NoError(t, err)
            require.Equal(t, tc.expected, ss)
        })
    }
}
  1. Improve error handling:
- if err != nil {
-     t.Error("Failed to decode hex string")
- }
+ require.NoError(t, err, "Failed to decode hex string")

To verify the CBORUnmarshal type, run the following:

✅ Verification successful

CBORUnmarshal Type Verified

The CBORUnmarshal type is properly defined and correctly imported in the cbor_test.go file. No issues found regarding its definition or usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify CBORUnmarshal type

# Check for CBORUnmarshal type definition
rg --type go "type\s+CBORUnmarshal"

# Check for potential imports of this type
rg --type go "import\s+\([^)]*\bCBORUnmarshal\b[^)]*\)"

Length of output: 574

🧰 Tools
🪛 golangci-lint

34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


11-26: LGTM: Well-structured test function with room for improvement.

The Test_DefaultCBOREncoder function is well-structured and uses parallel testing, which is good for efficiency. However, there are a few points to consider:

  1. The test case covers a basic scenario. Consider adding more diverse test cases to ensure robust encoding.
  2. The sampleStructure is not defined in this file. Ensure it's properly imported or defined to avoid compilation issues.
  3. The CBORMarshal type assertion might be related to the static analysis hints about undefined cbor. Verify that this type is properly defined and imported.

Consider adding more test cases to cover edge cases and complex structures. For example:

func Test_DefaultCBOREncoder(t *testing.T) {
    t.Parallel()

    testCases := []struct {
        name     string
        input    interface{}
        expected string
    }{
        {"basic", &sampleStructure{ImportantString: "Hello World"}, "a170696d706f7274616e745f737472696e676b48656c6c6f20576f726c64"},
        {"empty", &sampleStructure{}, "a170696d706f7274616e745f737472696e6760"},
        // Add more test cases here
    }

    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            raw, err := cbor.Marshal(tc.input)
            require.NoError(t, err)
            require.Equal(t, tc.expected, hex.EncodeToString(raw))
        })
    }
}

To verify the CBORMarshal type and sampleStructure, run the following:

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)

@imsk17
Copy link
Contributor Author

imsk17 commented Oct 12, 2024

Done.

@gaby
Copy link
Member

gaby commented Oct 12, 2024

@coderabbitai full review

Copy link

coderabbitai bot commented Oct 12, 2024

✅ Actions performed

Full review triggered.

@gaby
Copy link
Member

gaby commented Oct 12, 2024

Done.

Awesome, I will review today

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 (3)
cbor_test.go (3)

11-26: LGTM: Well-structured basic test for CBOR encoding.

The test function is well-structured and covers a basic scenario for CBOR encoding. The use of parallel testing with t.Parallel() is good for test efficiency.

However, as mentioned in a previous review, consider adding more comprehensive test cases to cover:

  1. Edge cases (e.g., empty structures, null values, or very large data).
  2. More complex nested structures.
  3. Error handling scenarios.
  4. Benchmark tests for performance measurement.

Would you like assistance in generating these additional test cases to improve the test coverage?

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


28-43: LGTM with suggestions: Well-structured basic test for CBOR decoding.

The test function is well-structured and covers a basic scenario for CBOR decoding. The use of parallel testing with t.Parallel() is consistent with the encoder test.

Suggestions for improvement:

  1. Error handling: Consider using require.NoError(t, err) for hex decoding instead of t.Error(). This ensures the test fails immediately if the hex string is invalid.

  2. As mentioned for the encoder test, consider adding more comprehensive test cases to cover various scenarios and edge cases.

Here's a suggested improvement for error handling:

- if err != nil {
-   t.Error("Failed to decode hex string")
- }
+ require.NoError(t, err, "Failed to decode hex string")

Would you like assistance in generating additional test cases to improve the overall test coverage for both encoding and decoding?

🧰 Tools
🪛 golangci-lint

34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


1-43: Summary: Good foundation for CBOR testing with room for expansion.

Overall, this new test file provides a solid foundation for testing CBOR encoding and decoding functionality. The tests are well-structured, use parallel testing for efficiency, and cover basic scenarios.

To further improve the robustness of the CBOR implementation, consider:

  1. Expanding the test suite with more comprehensive cases as suggested earlier.
  2. Improving error handling in the decoder test.
  3. Adding benchmark tests to measure performance.

These enhancements would provide greater confidence in the CBOR implementation across various scenarios and use cases.

Would you like assistance in implementing these improvements? I can help draft additional test cases, improve error handling, or set up benchmark tests.

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 786f636 and 85e3dd9.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (2)
  • cbor.go (1 hunks)
  • cbor_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint
cbor_test.go

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)

🔇 Additional comments (3)
cbor.go (2)

3-4: LGTM: Well-defined CBORMarshal type

The CBORMarshal type is well-defined and follows Go conventions. It allows for encoding of various data types and provides appropriate error handling.


6-9: ⚠️ Potential issue

Define or clarify the InvalidUnmarshalError

The comment for CBORUnmarshal mentions returning an InvalidUnmarshalError, but this error type is not defined within the package. This issue was previously raised and is still valid.

Consider one of the following actions:

  1. Define the InvalidUnmarshalError type in this package.
  2. Update the comment to mention a more generic error type that is actually returned.
  3. If the error is defined in a different package that this one depends on, import that package and use the fully qualified error name in the comment.

Please clarify the intended error handling approach to ensure consistency between the documentation and the actual implementation.

cbor_test.go (1)

3-9: LGTM: Import statements are appropriate.

The import statements are well-structured and include all necessary packages for CBOR encoding/decoding and testing. The use of testify/require for assertions is a good practice for writing clean and descriptive tests.

cbor.go Outdated Show resolved Hide resolved
@imsk17
Copy link
Contributor Author

imsk17 commented Oct 13, 2024

Can we get this to merge?

Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

Overall looks good, just needs more tests. Unlike json/xml that are built into Golang, this relies on external packages so we should add a few more basic tests

@gaby
Copy link
Member

gaby commented Oct 18, 2024

@imsk17 Can you add the missing unit-tests? Thanks

@imsk17
Copy link
Contributor Author

imsk17 commented Oct 19, 2024

On it.

@imsk17
Copy link
Contributor Author

imsk17 commented Oct 19, 2024

Let me know of more test cases if these arent enough.

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 (3)
cbor_test.go (3)

62-77: LGTM with a minor suggestion: Well-structured test for empty string decoding

This test function is well-implemented. It correctly tests the CBOR decoding of an empty string, uses parallel execution for efficiency, and follows Go testing best practices with require assertions.

Consider replacing the manual error check for hex decoding with a require assertion for consistency:

-	if err != nil {
-		t.Error("Failed to decode hex string")
-	}
+	require.NoError(t, err, "Failed to decode hex string")
🧰 Tools
🪛 golangci-lint

68-68: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


94-109: LGTM with suggestions: Well-structured test for uninitialized struct decoding

This test function is well-implemented overall. It tests the CBOR decoding into an uninitialized struct, uses parallel execution for efficiency, and follows Go testing best practices with require assertions.

Consider the following improvements:

  1. Replace the manual error check for hex decoding with a require assertion for consistency:
-	if err != nil {
-		t.Error("Failed to decode hex string")
-	}
+	require.NoError(t, err, "Failed to decode hex string")
  1. The final assertion require.Equal(t, ss, ss) doesn't seem to be testing anything meaningful. Consider replacing it with a more specific assertion that checks the expected state of the decoded struct. For example:
-	require.Equal(t, ss, ss)
+	require.Equal(t, "", ss.ImportantString, "Expected ImportantString to be empty after decoding")

This change will make the test more robust and informative.

🧰 Tools
🪛 golangci-lint

100-100: undefined: cbor

(typecheck)


1-109: Overall good test coverage with room for expansion

The new test functions in this file are well-structured, use parallel execution for efficiency, and generally follow Go testing best practices. The addition of tests for empty strings and uninitialized structs improves the overall coverage of the CBOR encoding and decoding functionality.

To further enhance the test suite, consider adding the following test cases:

  1. Test with complex nested structures to ensure correct handling of hierarchical data.
  2. Test with various data types (e.g., integers, floats, booleans, arrays) to cover a wider range of CBOR encoding scenarios.
  3. Error handling tests with malformed input for decoding to ensure robustness.
  4. Benchmark tests to measure the performance of CBOR operations.

These additional test cases would provide a more comprehensive test suite and increase confidence in the CBOR implementation.

Would you like assistance in generating these additional test cases?

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


85-85: undefined: cbor

(typecheck)


100-100: undefined: cbor

(typecheck)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 75f24a9 and ee26b4f.

📒 Files selected for processing (1)
  • cbor_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint
cbor_test.go

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


85-85: undefined: cbor

(typecheck)


100-100: undefined: cbor

(typecheck)

🔇 Additional comments (2)
cbor_test.go (2)

45-60: LGTM: Well-structured test for empty string encoding

This test function is well-implemented. It correctly tests the CBOR encoding of a struct with an empty string, uses parallel execution for efficiency, and follows Go testing best practices with require assertions.

🧰 Tools
🪛 golangci-lint

53-53: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


79-92: LGTM: Well-structured test for uninitialized struct encoding

This test function is well-implemented. It correctly tests the CBOR encoding of an uninitialized struct, uses parallel execution for efficiency, and follows Go testing best practices with require assertions.

🧰 Tools
🪛 golangci-lint

85-85: undefined: cbor

(typecheck)

@gaby
Copy link
Member

gaby commented Oct 19, 2024

Let me know of more test cases if these arent enough.

Golangci-lint doesnt seem to like the comparison against the same variable

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 (5)
cbor_test.go (5)

11-26: Fix the 'cbor' undefined error and consider adding a comment.

The test function looks good overall. However, there's a static analysis error indicating that 'cbor' is undefined. This is likely a false positive due to the way the CBOR package is imported. To resolve this:

  1. Consider adding a blank import for the CBOR package if it's not directly used:

    import _ "github.com/fxamacker/cbor/v2"
  2. Add a comment explaining why the blank import is necessary if you implement the above solution.

Also, consider adding a brief comment explaining the purpose of the importantString hexadecimal value for better readability.

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


28-43: Fix the 'cbor' undefined error and improve error handling.

The test function is well-structured and tests the CBOR decoding correctly. However:

  1. The 'cbor' undefined error persists. This will be resolved by the solution proposed in the previous comment.

  2. The error handling for hex decoding can be improved:

- if err != nil {
-   t.Error("Failed to decode hex string")
- }
+ require.NoError(t, err, "Failed to decode hex string")

This change makes the test fail immediately if the hex decoding fails, providing more precise error information.

🧰 Tools
🪛 golangci-lint

34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


62-77: LGTM: Good test for empty string decoding. Consider improving error handling.

This test function correctly complements the empty string encoding test, ensuring that CBOR decoding handles empty strings properly.

To improve the code:

  1. The 'cbor' undefined error will be resolved by the solution proposed in the first comment.

  2. Consider improving the error handling for hex decoding, similar to the suggestion in the second test function:

- if err != nil {
-   t.Error("Failed to decode hex string")
- }
+ require.NoError(t, err, "Failed to decode hex string")
🧰 Tools
🪛 golangci-lint

68-68: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


79-92: LGTM: Good test for uninitialized struct. Consider adding a comment.

This test function correctly addresses the scenario of encoding an uninitialized struct, which is an excellent edge case to cover. To improve the code:

  1. The 'cbor' undefined error will be resolved by the solution proposed in the first comment.

  2. Consider adding a brief comment explaining the expected behavior when encoding an uninitialized struct. This would enhance the test's readability and purpose.

🧰 Tools
🪛 golangci-lint

85-85: undefined: cbor

(typecheck)


94-110: LGTM: Good test for uninitialized struct decoding. Consider some improvements.

This test function correctly complements the uninitialized struct encoding test, ensuring that CBOR decoding handles this edge case properly. To improve the code:

  1. The 'cbor' undefined error will be resolved by the solution proposed in the first comment.

  2. Improve the error handling for hex decoding:

- if err != nil {
-   t.Error("Failed to decode hex string")
- }
+ require.NoError(t, err, "Failed to decode hex string")
  1. Consider adding a brief comment explaining the expected behavior when decoding into an uninitialized struct.
🧰 Tools
🪛 golangci-lint

101-101: undefined: cbor

(typecheck)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ee26b4f and edcc056.

📒 Files selected for processing (1)
  • cbor_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint
cbor_test.go

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


85-85: undefined: cbor

(typecheck)


101-101: undefined: cbor

(typecheck)

🔇 Additional comments (3)
cbor_test.go (3)

3-9: LGTM: Import statements are correct and comprehensive.

The import statements include all necessary packages for CBOR operations, testing, and assertions. Good job on using the require package from testify for more concise test assertions.


45-60: LGTM: Good addition of empty string test case.

This test function correctly addresses the empty string scenario, which was suggested in the past review comments. It's a valuable addition to ensure the CBOR encoder handles edge cases properly.

The 'cbor' undefined error will be resolved by the solution proposed in the first comment.

🧰 Tools
🪛 golangci-lint

53-53: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


1-110: Overall, good initial test coverage with room for improvement.

The cbor_test.go file provides a solid foundation for testing CBOR encoding and decoding functionality. The tests cover basic scenarios, empty strings, and uninitialized structs, which is commendable.

Key points from the review:

  1. Address the 'cbor' undefined errors, likely with a blank import.
  2. Improve error handling in some test functions.
  3. Add explanatory comments for better readability.
  4. Consider expanding the test suite with additional cases for nested structures, bad input, large data, and various data types.

These improvements will enhance the robustness and reliability of the CBOR implementation. Great work on the initial implementation!

🧰 Tools
🪛 golangci-lint

19-19: undefined: cbor

(typecheck)


19-19: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


34-34: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


53-53: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


68-68: undefined: cbor

(typecheck)


85-85: undefined: cbor

(typecheck)


101-101: undefined: cbor

(typecheck)

cbor_test.go Show resolved Hide resolved
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

👍 LGTM

@gaby
Copy link
Member

gaby commented Oct 19, 2024

@imsk17 This will be merged once someone else in the team reviews it. Thanks! 💪

@ReneWerner87 ReneWerner87 merged commit d48ce7c into gofiber:master Oct 20, 2024
17 of 18 checks passed
@gaby
Copy link
Member

gaby commented Oct 20, 2024

@imsk17 CBOR support is now in the latest gofiber/utils release.

https://github.com/gofiber/utils/releases/tag/v2.0.0-beta.7

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.

3 participants