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

test(types/address): add unit tests for the file types/address.go #20237

Merged
merged 15 commits into from
Jun 13, 2024

Conversation

EmilGeorgiev
Copy link
Contributor

@EmilGeorgiev EmilGeorgiev commented May 1, 2024

Description

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • [x ] included the correct type prefix in the PR title
  • [x ] confirmed ! in the type prefix if API or client breaking change
  • [ x] targeted the correct branch (see PR Targeting)
  • [ x] provided a link to the relevant issue or specification
  • [x ] reviewed "Files changed" and left comments if necessary
  • [x ] included the necessary unit and integration tests
  • [ x] added a changelog entry to CHANGELOG.md
  • [ x] updated the relevant documentation or specification, including comments for documenting Go code
  • [ x] confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features
    • Introduced fuzz testing for ensuring consistency in encoding and decoding account addresses using Bech32 and hexadecimal formats.
    • Added functions for formatting address types as strings and pointers.
    • Implemented functions for getting Bech32 prefixes for different address types.
  • Bug Fixes
    • Corrected naming inconsistencies in test functions to improve clarity and maintainability.
  • Tests
    • Added comprehensive tests for new and existing address functionalities to ensure robustness and reliability.
  • Chores
    • Updated the build script for improved testing coverage.

@EmilGeorgiev EmilGeorgiev requested a review from a team as a code owner May 1, 2024 12:48
Copy link
Contributor

coderabbitai bot commented May 1, 2024

Walkthrough

The changes encompass enhancing fuzz testing capabilities by adding a new native Go fuzzer, FuzzBech32AccAddrConsistencyYAML, for testing Bech32 address consistency with YAML inputs. This includes modifications in fuzz/oss-fuzz-build.sh and additions in various test files related to address handling.

Changes

File Path Changes Summary
fuzz/oss-fuzz-build.sh Added a call to compile_native_go_fuzzer with FuzzBech32AccAddrConsistencyYAML.
types/address_fuzz_test.go Introduces FuzzBech32AccAddrConsistencyYAML for encoding and decoding account addresses.
types/address_test.go - Added imports for fmt and unsafe.
- Added github.com/cosmos/cosmos-sdk/types/bech32 import.
- Introduced testMarshalYAML function.
- Added various test functions for address types.
- Functions for formatting addresses and getting Bech32 prefixes.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

Thanks for the PR! Lot of work to improve coverage! 💪
I have some preferences on standard Go table tests as I find them more readable but this is just me and not blocker.
I would like to ask you to simplify the address generation towards a simple cast on bytes and to not replicate the code that is tested in the tests. Just pin a concrete example address and output if possible

@@ -58,6 +63,13 @@ func (s *addressTestSuite) testMarshal(original, res interface{}, marshal func()
s.Require().Equal(original, res)
}

func (s *addressTestSuite) testMarshalYAML(original, res interface{}, marshal func() (interface{}, error), unmarshal func([]byte) error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

personal preference: the addressTestSuite does not setup any state. IMHO standard Go table tests are much better to read.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I agree with you. I think that the test suite has its place in the unit tests as all, however, in this case, it is useless because it doesn't maintain any state. I only used it for my tests because previous tests had already used the test suite and for consistency I decided to use it too. Here, table tests would be more appropriate. I can remove the test suite and implement table tests in a separate PR because the file is almost 1000 rows. What do you think about that?

@@ -58,6 +63,13 @@ func (s *addressTestSuite) testMarshal(original, res interface{}, marshal func()
s.Require().Equal(original, res)
}

func (s *addressTestSuite) testMarshalYAML(original, res interface{}, marshal func() (interface{}, error), unmarshal func([]byte) error) {
bz, err := marshal()
s.Require().Nil(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: here and others .NoError(err) gives a better failure output

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. I replace it in the all test file

types/address_test.go Show resolved Hide resolved
accAddress1, err := types.AccAddressFromBech32(address)
s.Require().NoError(err)

accAddress2 := types.MustAccAddressFromBech32(address)
Copy link
Contributor

Choose a reason for hiding this comment

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

why not use a valid and an invalid bech32 address string here instead of building it. You are covering the happy path only?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I test only the happy path. As I write in my previously comment I can refactor the tests file in a separate PR. I can replace testSuite with table tests and I will use valid and invalid bech32.

bech32PrefixAccAddr := types.GetConfig().GetBech32AccountAddrPrefix()
addr20byte := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
address := types.MustBech32ifyAddressBytes(bech32PrefixAccAddr, addr20byte)
accAddr := types.MustAccAddressFromBech32(address)
Copy link
Contributor

Choose a reason for hiding this comment

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

this whole block can be simplified by:

accAddr := types.AccAddress([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19})

The AccAddress is just bytes

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

}

func (s *addressTestSuite) TestFormatConsAddressWhenVerbIsDifferentFromSOrP() {
bech32PrefixAccAddr := types.GetConfig().GetBech32ConsensusAddrPrefix()
Copy link
Contributor

Choose a reason for hiding this comment

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

Here and a above: this is a lot of code. How about using a loop instead?

	myAddr := types.AccAddress([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19})
	exp := "000102030405060708090A0B0C0D0E0F10111213"
	spec := []string{"%v", "%#v"} //...
	for _, v := range spec {
		assert.Equal(t, exp, fmt.Sprintf(v, myAddr), v)
	}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done


ptrAddr := &accAddr
actual := fmt.Sprintf("%p", ptrAddr)
expected := uintptr(unsafe.Pointer(&accAddr))
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: expected should be the full string in this case

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

@@ -133,6 +145,45 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() {
s.Require().Equal(types.ErrEmptyHexAddress, err)
}

func (s *addressTestSuite) TestRandBech32AccAddrConsistencyYAML() {
Copy link
Contributor

Choose a reason for hiding this comment

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

I have some personal preference on table tests. But it is fine to do it differently.
For regression, some concrete byte examples would be better so that we have confidence that it is backwards compatible and nothing is broken. You would use fix AccAddresses and their yaml, hex and bech32 representation instead of random addresses.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I used random addresses with Go Fuzzer

pubBz := make([]byte, ed25519.PubKeySize)
pub := &ed25519.PubKey{Key: pubBz}

for i := 0; i < 1000; i++ {
Copy link
Contributor

Choose a reason for hiding this comment

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

Why 1000? With random addresses the Go Fuzzer may be more interesting to navigate the code tree for edge cases.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

@EmilGeorgiev
Copy link
Contributor Author

EmilGeorgiev commented May 10, 2024

@alpe thank you for your time and your comments.

Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

Thanks for the updates! I added some more nits for improvements but it is good to be merged if you don't have capacity. 👍

func testMarshalYAML(t *testing.T, original, res interface{}, marshal func() (interface{}, error), unmarshal func([]byte) error) {
bz, err := marshal()

assert.NoError(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: here and others: use require.NoError instead so that your test can stop early.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

s.Require().NotNil(err)

err = (*types.AccAddress)(nil).UnmarshalYAML([]byte("\"" + str + "\""))
s.Require().NotNil(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: here and others: prefer NoError for better output

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

bech32PrefixValAddr := types.GetConfig().GetBech32ValidatorAddrPrefix()
accAddress1 := types.AccAddress([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19})
accAddress2 := types.MustAccAddressFromBech32(accAddress1.String())
s.Require().Equal(accAddress1, accAddress2)
Copy link
Contributor

Choose a reason for hiding this comment

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

I would use the full bech32 string here to ensure that the decoding works. Otherwise you can not really know what encoding is used.

func (s *addressTestSuite) TestMustAccAddressFromBech32() {
	src := types.MustAccAddressFromBech32("cosmos1qqqsyqcyq5rqwzqfpg9scrgwpugpzysnrk363e")
	exp := types.AccAddress([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19})
	s.Assert().Equal(exp, src)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@aple now I remember why I did this. The prefix is always different randomly generated string. If I use "cosmos" as a prefix the test always fail when I run all the tests.

actual := fmt.Sprintf("%s", consAddr)

hrp := types.GetConfig().GetBech32ConsensusAddrPrefix()
expected, err := bech32.ConvertAndEncode(hrp, consAddr)
Copy link
Contributor

Choose a reason for hiding this comment

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

Why not use the string value here instead of converting. It helps with regression is much more readable to humans as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

@@ -133,6 +145,52 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() {
s.Require().Equal(types.ErrEmptyHexAddress, err)
}

func FuzzBech32AccAddrConsistencyYAML(f *testing.F) {
Copy link
Contributor

Choose a reason for hiding this comment

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

please move fuzzer tests to to a address_fuzz_test.go file. I always find it confusing to see them with others.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

@alpe
Copy link
Contributor

alpe commented May 14, 2024

argh, now the linter is complaining:

linting github.com/cosmos/cosmos-sdk [2024-05-14T04:09:40+00:00]
types/address_fuzz_test.go:6: File is not `gci`-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order (gci)
	
	"github.com/cosmos/cosmos-sdk/types"
types/address_fuzz_test.go:8: File is not `gci`-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order (gci)
	"github.com/stretchr/testify/require"
Error: types/address_test.go:653:9: string `000102030405060708090A0B0C0D0E0F10111213` has 3 occurrences, make it a constant (goconst)
	exp := "000102030405060708090A0B0C0D0E0F10111213"
	       ^
types/address_test.go:148: File is not `gofumpt`-ed with `-extra` (gofumpt)

types/address_test.go:595: File is not `gofumpt`-ed with `-extra` (gofumpt)

Error: types/address_test.go:64:6: test helper function should start from t.Helper() (thelper)
func testMarshalYAML(t *testing.T, original, res interface{}, marshal func() (interface{}, error), unmarshal func([]byte) error) {
     ^
make: *** [Makefile:416: lint] Error 1

You can check with make lint

res := &types.AccAddress{}

testMarshalYAML(t, &acc, res, acc.MarshalYAML, res.UnmarshalYAML)
testMarshalYAML(t, &acc, res, acc.MarshalYAML, res.UnmarshalYAML)
Copy link
Contributor

Choose a reason for hiding this comment

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

duplicate to L24

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 2c45c4e and 804e649.
Files selected for processing (1)
  • fuzz/oss-fuzz-build.sh (1 hunks)
Additional comments not posted (1)
fuzz/oss-fuzz-build.sh (1)

28-28: New fuzzing target added correctly.

The new fuzzing target FuzzBech32AccAddrConsistencyYAML has been added correctly and follows the same pattern as the existing targets.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Out of diff range and nitpick comments (9)
types/address_fuzz_test.go (1)

1-1: Package name should match the directory structure and convention.

Ensure the package name aligns with the directory structure and follows Go conventions. Typically, test files should be in the same package as the code they test.

types/address_test.go (8)

Line range hint 72-89: Consider adding comments to explain the purpose of each test case.

Adding comments will help other developers understand the intent behind each test case.

func (s *addressTestSuite) TestEmptyAddresses() {
    s.T().Parallel()
    // Test empty string representation
    s.Require().Equal((types.AccAddress{}).String(), "")
    s.Require().Equal((types.ValAddress{}).String(), "")
    s.Require().Equal((types.ConsAddress{}).String(), "")

    // Test empty Bech32 address conversion
    accAddr, err := types.AccAddressFromBech32("")
    s.Require().True(accAddr.Empty())
    s.Require().Error(err)

    valAddr, err := types.ValAddressFromBech32("")
    s.Require().True(valAddr.Empty())
    s.Require().Error(err)

    consAddr, err := types.ConsAddressFromBech32("")
    s.Require().True(consAddr.Empty())
    s.Require().Error(err)
}

Line range hint 111-146: Consider reducing the number of iterations for the loop to speed up the test.

Reducing the number of iterations can help speed up the test without compromising its effectiveness.

for i := 0; i < 100; i++ {
    // Test logic
}

Line range hint 159-187: Consider adding comments to explain the purpose of each test case.

Adding comments will help other developers understand the intent behind each test case.

func (s *addressTestSuite) TestAddrCache() {
    // Use a random key
    pubBz := make([]byte, ed25519.PubKeySize)
    pub := &ed25519.PubKey{Key: pubBz}
    _, err := rand.Read(pub.Key)
    s.Require().NoError(err)
    // Set SDK bech32 prefixes to 'osmo'
    prefix := "osmo"
    conf := types.GetConfig()
    conf.SetBech32PrefixForAccount(prefix, prefix+pubStr)
    conf.SetBech32PrefixForValidator(prefix+valoper, prefix+valoperpub)
    conf.SetBech32PrefixForConsensusNode(prefix+valcons, prefix+valconspub)

    acc := types.AccAddress(pub.Address())
    osmoAddrBech32 := acc.String()

    // Set SDK bech32 to 'cosmos'
    prefix = "cosmos"
    conf.SetBech32PrefixForAccount(prefix, prefix+pubStr)
    conf.SetBech32PrefixForValidator(prefix+valoper, prefix+valoperpub)
    conf.SetBech32PrefixForConsensusNode(prefix+valcons, prefix+valconspub)

    // We name this 'addrCosmos' to prove a point, but the bech32 address will still begin with 'osmo' due to the cache behavior.
    addrCosmos := types.AccAddress(pub.Address())
    cosmosAddrBech32 := addrCosmos.String()

    // The default behavior will retrieve the bech32 address from the cache, ignoring the bech32 prefix change.
    s.Require().Equal(osmoAddrBech32, cosmosAddrBech32)
    s.Require().True(strings.HasPrefix(osmoAddrBech32, "osmo"))
    s.Require().True(strings.HasPrefix(cosmosAddrBech32, "osmo"))
}

Line range hint 189-217: Consider adding comments to explain the purpose of each test case.

Adding comments will help other developers understand the intent behind each test case.

func (s *addressTestSuite) TestAddrCacheDisabled() {
    types.SetAddrCacheEnabled(false)

    // Use a random key
    pubBz := make([]byte, ed25519.PubKeySize)
    pub := &ed25519.PubKey{Key: pubBz}
    _, err := rand.Read(pub.Key)
    s.Require().NoError(err)
    // Set SDK bech32 prefixes to 'osmo'
    prefix := "osmo"
    conf := types.GetConfig()
    conf.SetBech32PrefixForAccount(prefix, prefix+pubStr)
    conf.SetBech32PrefixForValidator(prefix+valoper, prefix+valoperpub)
    conf.SetBech32PrefixForConsensusNode(prefix+valcons, prefix+valconspub)

    acc := types.AccAddress(pub.Address())
    osmoAddrBech32 := acc.String()

    // Set SDK bech32 to 'cosmos'
    prefix = "cosmos"
    conf.SetBech32PrefixForAccount(prefix, prefix+pubStr)
    conf.SetBech32PrefixForValidator(prefix+valoper, prefix+valoperpub)
    conf.SetBech32PrefixForConsensusNode(prefix+valcons, prefix+valconspub)

    addrCosmos := types.AccAddress(pub.Address())
    cosmosAddrBech32 := addrCosmos.String()

    // retrieve the bech32 address from the cache, respecting the bech32 prefix change.
    s.Require().NotEqual(osmoAddrBech32, cosmosAddrBech32)
    s.Require().True(strings.HasPrefix(osmoAddrBech32, "osmo"))
    s.Require().True(strings.HasPrefix(cosmosAddrBech32, "cosmos"))
}

Line range hint 219-268: Consider reducing the number of iterations for the loop to speed up the test.

Reducing the number of iterations can help speed up the test without compromising its effectiveness.

for i := 0; i < 100; i++ {
    // Test logic
}

Line range hint 270-308: Consider reducing the number of iterations for the loop to speed up the test.

Reducing the number of iterations can help speed up the test without compromising its effectiveness.

for i := 0; i < 100; i++ {
    // Test logic
}

Line range hint 348-391: Consider reducing the number of iterations for the loop to speed up the test.

Reducing the number of iterations can help speed up the test without compromising its effectiveness.

for length := 1; length < 5; length++ {
    for times := 1; times < 10; times++ {
        // Test logic
    }
}

Line range hint 393-406: Consider adding comments to explain the purpose of each test case.

Adding comments will help other developers understand the intent behind each test case.

func (s *addressTestSuite) TestAddressInterface() {
    pubBz := make([]byte, ed25519.PubKeySize)
    pub := &ed25519.PubKey{Key: pubBz}
    _, err := rand.Read(pub.Key)
    s.Require().NoError(err)
    addrs := []types.Address{
        types.ConsAddress(pub.Address()),
        types.ValAddress(pub.Address()),
        types.AccAddress(pub.Address()),
    }

    for _, addr := range addrs {
        switch addr := addr.(type) {
        case types.AccAddress:
            // Test account address
            _, err := types.AccAddressFromBech32(addr.String())
            s.Require().NoError(err)
        case types.ValAddress:
            // Test validator address
            _, err := types.ValAddressFromBech32(addr.String())
            s.Require().NoError(err)
        case types.ConsAddress:
            // Test consensus address
            _, err := types.ConsAddressFromBech32(addr.String())
            s.Require().NoError(err)
        default:
            s.T().Fail()
        }
    }
}
Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 804e649 and d5e53b4.
Files selected for processing (2)
  • types/address_fuzz_test.go (1 hunks)
  • types/address_test.go (8 hunks)
Additional Context Used
Path-based Instructions (2)
types/address_fuzz_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

types/address_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

Additional comments not posted (3)
types/address_fuzz_test.go (1)

21-37: Ensure proper error handling and validation for the input parameter.

Verify that the input parameter is valid and meets the expected format before proceeding with the test. This can help catch potential issues early.

f.Fuzz(func(t *testing.T, input []byte) {
    if len(input) == 0 {
        t.Skip("input is empty")
    }
    acc := types.AccAddress(input)
    res := &types.AccAddress{}

    testMarshalYAML(t, &acc, res, acc.MarshalYAML, res.UnmarshalYAML)

    str := acc.String()
    var err error
    *res, err = types.AccAddressFromBech32(str)
    require.NoError(t, err)
    require.Equal(t, acc, *res)

    str = hex.EncodeToString(acc)
    *res, err = types.AccAddressFromHexUnsafe(str)
    require.NoError(t, err)
    require.Equal(t, acc, *res)
})
types/address_test.go (2)

64-71: Good use of t.Helper() to mark the function as a test helper.

This helps in better error reporting by pointing to the actual test case that failed.


Line range hint 91-109: Consider adding error handling for the yaml.Marshal calls.

Adding error handling will ensure that any issues with marshaling are caught and reported.

func (s *addressTestSuite) TestYAMLMarshalers() {
    addr := secp256k1.GenPrivKey().PubKey().Address()

    acc := types.AccAddress(addr)
    val := types.ValAddress(addr)
    cons := types.ConsAddress(addr)

    got, err := yaml.Marshal(&acc)
    s.Require().NoError(err)
    s.Require().Equal(acc.String()+"\n", string(got))

    got, err = yaml.Marshal(&val)
    s.Require().NoError(err)
    s.Require().Equal(val.String()+"\n", string(got))

    got, err = yaml.Marshal(&cons)
    s.Require().NoError(err)
    s.Require().Equal(cons.String()+"\n", string(got))
}

Comment on lines +12 to +15
func FuzzBech32AccAddrConsistencyYAML(f *testing.F) {
if testing.Short() {
f.Skip("running in -short mode")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding a comment to explain the purpose of skipping the test in short mode.

Adding a comment will help other developers understand why the test is skipped in short mode.

if testing.Short() {
    // Skip this test in short mode to save time
    f.Skip("running in -short mode")
}

Comment on lines +148 to +157
func (s *addressTestSuite) TestUnmarshalYAMLWithInvalidInput() {
for _, str := range invalidStrs {
_, err := types.AccAddressFromHexUnsafe(str)
s.Require().Error(err)

_, err = types.AccAddressFromBech32(str)
s.Require().Error(err)

err = (*types.AccAddress)(nil).UnmarshalYAML([]byte("\"" + str + "\""))
s.Require().Error(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding comments to explain the purpose of each test case.

Adding comments will help other developers understand the intent behind each test case.

func (s *addressTestSuite) TestUnmarshalYAMLWithInvalidInput() {
    for _, str := range invalidStrs {
        // Test invalid hex input
        _, err := types.AccAddressFromHexUnsafe(str)
        s.Require().Error(err)

        // Test invalid Bech32 input
        _, err = types.AccAddressFromBech32(str)
        s.Require().Error(err)

        // Test invalid YAML input
        err = (*types.AccAddress)(nil).UnmarshalYAML([]byte("\"" + str + "\""))
        s.Require().Error(err)
    }

    // Test empty hex input
    _, err := types.AccAddressFromHexUnsafe("")
    s.Require().Equal(types.ErrEmptyHexAddress, err)
}

@EmilGeorgiev EmilGeorgiev changed the title tests(types/address): add unit tests for the file types/address.go test(types/address): add unit tests for the file types/address.go May 16, 2024
Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

LGTM!
Thanks for driving this forward and all the updates 🏄

@EmilGeorgiev
Copy link
Contributor Author

LGTM! Thanks for driving this forward and all the updates 🏄

I thank you too for your time.

@facundomedica facundomedica added this pull request to the merge queue Jun 13, 2024
Merged via the queue into cosmos:main with commit 748a939 Jun 13, 2024
63 of 64 checks passed
alpe added a commit that referenced this pull request Jun 17, 2024
* main:
  feat(tx): port simappv2 changes (#20648)
  build(deps): Bump github.com/spf13/cobra from 1.8.0 to 1.8.1 (#20682)
  chore(proto): fix comments (#20679)
  (serverv2/cometbft) Commands support both json and yaml output (#20670)
  fix(x/staking,x/auth):  regenerate mock to fix test (#20684)
  docs: ADR 074: Msg v2 (#20618)
  fix: nested multisig signatures using CLI (#20438)
  chore: fix spelling errors (#20674)
  fix: align Dockerfile for build-push-action (#20672)
  fix: avoid build fail when make localnet-build-env (#20671)
  build(deps): Bump bufbuild/buf-setup-action from 1.32.2 to 1.33.0 (#20669)
  chore: make function comment match function names (#20666)
  chore(consensus): add cometInfo to consensus  (#20615)
  chore: fix typos (#20662)
  fix: Properly parse json in the wait-tx command. (#20631)
  fix(sims): check before sending RotateConsPubKey (#20659)
  test(types/address): add unit tests for the file types/address.go  (#20237)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants