Antonboom / testifylint

The Golang linter that checks usage of github.com/stretchr/testify.
https://github.com/stretchr/testify
MIT License
101 stars 8 forks source link

len: simplify []bytes to string conversion to detected use cases #114

Open ccoVeille opened 5 months ago

ccoVeille commented 5 months ago

The following pattern could be reported

assert.Len(t, string(headContents), 40)

to use

assert.Len(t, headContents, 40)

I might be wrong, but I don't think there is a case where the length differs between the bytes and string.

This pattern is currently not detected, while it's pretty commonly used

https://github.com/search?q=language%3Ago+%22assert.Len%28t%2C+string%28%22&type=code&p=2

https://github.com/sean-ahn/user/blob/c662a9ecf73d2c467ee6d2ba4b6c8241c6ebbcaf/backend/crypto/scrypt_test.go#L41 https://github.com/fredrikekre/gitea/blob/c88f2e2acce8240ddd2161644ac37db5b6ec1337/modules/git/repo_compare_test.go#L120

⚠️ I don't think we should do it for a struct with a stringer

Antonboom commented 5 months ago

Looks like you are right

https://go.dev/ref/spec#Length_and_capacity

len(s)   string type   string length in bytes
         []T           slice length

I accept this proposal 👍

P.S. https://chatgpt.com/share/6b7bbc7a-498f-4ef5-ba0f-ff9ba1f773b0 P.P.S. It's strange that I didn't find a linter about this

ccoVeille commented 5 months ago

It's strange that I didn't find a linter about this

The only one I can think about is mirror

https://github.com/butuzov/mirror

I might open an issue on gosimple then anyway.

As you are right, it's pretty common https://github.com/search?q=+%22len%28string%28%22+language%3AGo+NOT+is%3Afork&type=code