From 6c2234b0c2c822466d5c8072b2e974878ffd2e39 Mon Sep 17 00:00:00 2001 From: sliveryou Date: Sat, 27 Jan 2024 20:03:17 +0800 Subject: [PATCH] feat: update .golangci.yaml and optimize the project --- .golangci.yaml | 164 +++++++++++++++++--- README.md | 39 +++-- cipher/aes/aescbc.go | 103 ++++++------ cipher/aes/aescbc_test.go | 158 +++++-------------- cipher/cipher.go | 45 +++--- cipher/pkcs/pkcs5_test.go | 6 +- cipher/pkcs/pkcs7_test.go | 6 +- convert/convert.go | 8 +- convert/convert_test.go | 29 ++-- filex/filex_test.go | 35 +++-- id-generator/encoding/base58/base58_test.go | 20 +-- id-generator/encoding/base62/base62_test.go | 20 +-- id-generator/snowflake/snowflake.go | 5 +- id-generator/snowflake/snowflake_test.go | 44 +++--- id-generator/uuid/uuid_test.go | 7 +- mathx/mathx.go | 9 +- mathx/mathx_test.go | 48 +++--- randx/randx_test.go | 3 + slicex/extract.go | 40 ++--- slicex/extract_test.go | 40 ++--- timex/timex.go | 9 +- timex/timex_test.go | 8 +- validator/bankcard.go | 16 +- validator/corpaccount.go | 2 +- validator/idcard.go | 14 +- validator/idcard_test.go | 17 +- validator/uscc.go | 2 +- validator/validator.go | 25 +-- validator/validator_test.go | 22 ++- 29 files changed, 496 insertions(+), 448 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 8b1c1db..687b519 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,17 +1,15 @@ run: + go: '1.16' concurrency: 4 timeout: 5m tests: true + skip-dirs: + - id-generator/uuid/satori linters-settings: - gosimple: - go: "1.16" - # https://staticcheck.io/docs/options#checks - checks: [ "all" ] - staticcheck: - go: "1.16" - # https://staticcheck.io/docs/options#checks - checks: [ "all", "-SA1019", "-SA5008" ] + errcheck: + # https://github.com/kisielk/errcheck#errcheck + ignore: fmt:.*,os:.* goconst: # https://github.com/jgautheron/goconst#usage ignore-tests: true @@ -20,36 +18,86 @@ linters-settings: gocritic: # https://go-critic.github.io/overview#checks-overview disabled-checks: - - appendAssign - ifElseChain gofumpt: - lang-version: "1.16" # https://github.com/mvdan/gofumpt#gofumpt extra-rules: true + gosimple: + # https://staticcheck.io/docs/options#checks + checks: [ "all" ] revive: ignore-generated-header: true severity: warning # https://github.com/mgechev/revive#available-rules rules: - name: context-keys-type + - name: time-equal - name: time-naming - name: var-declaration - name: unexported-return - name: errorf - - name: blank-imports - name: context-as-argument - # - name: dot-imports + - name: dot-imports - name: error-return - name: error-strings - name: error-naming - # - name: exported + - name: exported - name: if-return - name: increment-decrement - # - name: var-naming - # - name: package-comments + - name: var-naming + arguments: + - [ "ID" ] # allow list - name: range - name: receiver-naming - name: indent-error-flow + - name: argument-limit + - name: file-header + - name: empty-block + - name: superfluous-else + - name: confusing-naming + - name: get-return + - name: modifies-parameter + - name: confusing-results + # - name: deep-exit + - name: unused-parameter + - name: unreachable-code + # - name: add-constant + - name: unnecessary-stmt + - name: struct-tag + - name: modifies-value-receiver + - name: constant-logical-expr + - name: bool-literal-in-expr + - name: redefines-builtin-id + - name: function-result-limit + - name: imports-blacklist + - name: range-val-in-closure + - name: range-val-address + - name: waitgroup-by-value + - name: atomic + - name: empty-lines + - name: call-to-gc + - name: duplicated-imports + - name: import-shadowing + - name: string-of-int + - name: string-format + - name: early-return + - name: unconditional-recursion + - name: identical-branches + - name: defer + - name: unexported-naming + - name: nested-structs + - name: useless-break + - name: banned-characters + - name: optimize-operands-order + # - name: use-any + - name: datarace + - name: comment-spacings + - name: redundant-import-alias + - name: import-alias-naming + - name: enforce-map-style + staticcheck: + # https://staticcheck.io/docs/options#checks + checks: [ "all" ] stylecheck: # https://staticcheck.io/docs/options#checks checks: [ "all", "-ST1000", "-ST1003" ] @@ -57,20 +105,94 @@ linters-settings: linters: disable-all: true enable: - - gosimple - - govet - - ineffassign - - staticcheck - # - structcheck - - typecheck + - asasalint + - asciicheck + - bidichk + - bodyclose + - containedctx + - contextcheck + - decorder + - dogsled + - dupl + - dupword + - durationcheck + - errcheck + - errchkjson + - errname + - errorlint + - execinquery + # - exhaustive + - exportloopref + - forcetypeassert + - ginkgolinter + - gocheckcompilerdirectives + - gochecksumtype - goconst - gocritic + - gocyclo + # - godot + - godox + - gofmt - gofumpt + - goheader + - goimports + # - gomnd + - gomoddirectives + - gomodguard + - goprintffuncname + - gosimple + - govet + - grouper + - importas + - inamedparam + - ineffassign + - interfacebloat + - ireturn + - loggercheck + - maintidx + - makezero + - mirror + - misspell + - musttag + - nakedret + - nilerr + - nilnil + - noctx + - nolintlint + - nosprintfhostport + - perfsprint + - prealloc + - predeclared + - promlinter + - protogetter + - reassign - revive + - rowserrcheck + - sloglint + - sqlclosecheck + - staticcheck - stylecheck + - tenv + - testableexamples + - testifylint + - thelper + - tparallel + - typecheck - unconvert + - unparam + - unused + - usestdlibvars + - wastedassign + - whitespace + # - wrapcheck + - zerologlint issues: exclude-use-default: false max-issues-per-linter: 0 max-same-issues: 0 + exclude-rules: + - path: _test.go + linters: + - dupl + - unparam diff --git a/README.md b/README.md index 5d4e61d..8145dce 100644 --- a/README.md +++ b/README.md @@ -30,25 +30,30 @@ import ( "github.com/sliveryou/go-tool/cipher" ) -type Cipher - func MustNewAesCbc(key, iv string) Cipher - func NewAesCbc(key, iv string) (Cipher, error) +var _ Cipher = (*aes.Cbc)(nil) + +func MustNewAesCbc(key, iv string) *aes.Cbc +func NewAesCbc(key, iv string) (*aes.Cbc, error) +type Cipher interface { + Encrypt(src []byte) ([]byte, error) + Decrypt(src []byte) ([]byte, error) +} // aes import ( "github.com/sliveryou/go-tool/cipher/aes" ) -func AesCbcDecrypt(key, iv, src []byte) ([]byte, error) -func AesCbcDecryptBase64(key, iv []byte, msg string) ([]byte, error) -func AesCbcDecryptHex(key, iv []byte, msg string) ([]byte, error) -func AesCbcEncrypt(key, iv, src []byte) ([]byte, error) -func AesCbcEncryptBase64(key, iv, src []byte) (string, error) -func AesCbcEncryptHex(key, iv, src []byte) (string, error) -type AesCbc - func NewAesCbc(key, iv []byte) (*AesCbc, error) - func (a *AesCbc) Decrypt(src []byte) ([]byte, error) - func (a *AesCbc) Encrypt(src []byte) ([]byte, error) +func CbcDecrypt(key, iv, src []byte) ([]byte, error) +func CbcDecryptBase64(key, iv []byte, msg string) ([]byte, error) +func CbcDecryptHex(key, iv []byte, msg string) ([]byte, error) +func CbcEncrypt(key, iv, src []byte) ([]byte, error) +func CbcEncryptBase64(key, iv, src []byte) (string, error) +func CbcEncryptHex(key, iv, src []byte) (string, error) +type Cbc + func NewCbc(key, iv []byte) (*Cbc, error) + func (c *Cbc) Decrypt(src []byte) ([]byte, error) + func (c *Cbc) Encrypt(src []byte) ([]byte, error) // pkcs import ( @@ -80,8 +85,8 @@ func DecToBin(dec int64) string func DecToHex(dec int64) string func Float64ToBytes(f float64) []byte func HexDecodeBytes(h string) []byte -func HexToBin(hex string) string -func HexToDec(hex string) int64 +func HexToBin(h string) string +func HexToDec(h string) int64 func HexsDecodeBytes(hs []byte) []byte func Int64ToBytes(i int64) []byte func RunesToBytes(runes []rune) []byte @@ -270,8 +275,8 @@ func ContainFloat64(slice []float64, value float64, places ...int) (index int) func ContainInt(slice []int, value int) (index int) func ContainInt32(slice []int32, value int32) (index int) func ContainInt64(slice []int64, value int64) (index int) -func ContainString(slice []string, value string) (index int) func ContainRune(slice []rune, value rune) (index int) +func ContainString(slice []string, value string) (index int) func Count(slice interface{}) map[interface{}]int func CountBool(slice []bool) map[bool]int func CountFloat(slice []float64) map[float64]int @@ -440,7 +445,7 @@ func UnixMillisecond(t time.Time, location ...*time.Location) int64 func UnixNanosecond(t time.Time, location ...*time.Location) int64 func UnixSecond(t time.Time, location ...*time.Location) int64 func UnixToTime(timestamp int64, location ...*time.Location) time.Time -func UnixTodayRange(location ...*time.Location) (int64, int64) +func UnixTodayRange(location ...*time.Location) (start, end int64) ``` ### validator diff --git a/cipher/aes/aescbc.go b/cipher/aes/aescbc.go index 934a925..10e229a 100644 --- a/cipher/aes/aescbc.go +++ b/cipher/aes/aescbc.go @@ -13,18 +13,18 @@ import ( // There aescbc add pkcs7Padding to be same as php's aescbc const ( - // AesCbc128KeyLen key len: 16 - AesCbc128KeyLen = 16 - // AesCbc192KeyLen key len: 24 - AesCbc192KeyLen = 24 - // AesCbc256KeyLen key len: 32 - AesCbc256KeyLen = 32 + // Cbc128KeyLen key len: 16 + Cbc128KeyLen = 16 + // Cbc192KeyLen key len: 24 + Cbc192KeyLen = 24 + // Cbc256KeyLen key len: 32 + Cbc256KeyLen = 32 // IvLen iv len: 16 IvLen = 16 ) -// AesCbc the base aes cbc structure -type AesCbc struct { +// Cbc the base aes cbc structure +type Cbc struct { key []byte iv []byte block cipher.Block @@ -36,16 +36,15 @@ type AesCbc struct { // decrypter cipher.BlockMode } -// NewAesCbc new aes cbc cipher +// NewCbc new aes cbc cipher // aescbc support key len 16 24 32 match aescbc-128 aescbc-192 aescbc-256 // iv len must be 16 -func NewAesCbc(key, iv []byte) (*AesCbc, error) { +func NewCbc(key, iv []byte) (*Cbc, error) { k := len(key) switch k { default: return nil, fmt.Errorf("key len must be 16,24,32 your key is %d", k) - case AesCbc128KeyLen, AesCbc192KeyLen, AesCbc256KeyLen: - break + case Cbc128KeyLen, Cbc192KeyLen, Cbc256KeyLen: } if len(iv) != IvLen { @@ -57,7 +56,7 @@ func NewAesCbc(key, iv []byte) (*AesCbc, error) { return nil, err } - return &AesCbc{ + return &Cbc{ key: key, iv: iv, block: block, @@ -65,17 +64,19 @@ func NewAesCbc(key, iv []byte) (*AesCbc, error) { } // Encrypt the aes cbc encrypt method -func (a *AesCbc) Encrypt(src []byte) ([]byte, error) { - return a.encrypt(src) -} +func (c *Cbc) Encrypt(src []byte) ([]byte, error) { + paddingText := pkcs.PKCS7Padding(src, aes.BlockSize) -// Decrypt the aes cbc decrypt method -func (a *AesCbc) Decrypt(src []byte) ([]byte, error) { - return a.decrypt(src) + encrypter := cipher.NewCBCEncrypter(c.block, c.iv) + cipherText := make([]byte, len(paddingText)) + encrypter.CryptBlocks(cipherText, paddingText) + + return cipherText, nil } -func (a *AesCbc) decrypt(src []byte) ([]byte, error) { - decrypter := cipher.NewCBCDecrypter(a.block, a.iv) +// Decrypt the aes cbc decrypt method +func (c *Cbc) Decrypt(src []byte) ([]byte, error) { + decrypter := cipher.NewCBCDecrypter(c.block, c.iv) plainText := make([]byte, len(src)) decrypter.CryptBlocks(plainText, src) @@ -83,46 +84,36 @@ func (a *AesCbc) decrypt(src []byte) ([]byte, error) { return pkcs.PKCS7Trimming(plainText) } -func (a *AesCbc) encrypt(src []byte) ([]byte, error) { - paddingText := pkcs.PKCS7Padding(src, aes.BlockSize) - - encrypter := cipher.NewCBCEncrypter(a.block, a.iv) - cipherText := make([]byte, len(paddingText)) - encrypter.CryptBlocks(cipherText, paddingText) - - return cipherText, nil -} - // The follow functions are used for easy to call test -// or diffirent key to cipher +// or different key to cipher -// AesCbcEncrypt the aes cbc encrypt method -func AesCbcEncrypt(key, iv, src []byte) ([]byte, error) { - a, err := NewAesCbc(key, iv) +// CbcEncrypt the aes cbc encrypt method +func CbcEncrypt(key, iv, src []byte) ([]byte, error) { + a, err := NewCbc(key, iv) if err != nil { return nil, err } - return a.encrypt(src) + return a.Encrypt(src) } -// AesCbcDecrypt the ase cbc decrypt method -func AesCbcDecrypt(key, iv, src []byte) ([]byte, error) { - a, err := NewAesCbc(key, iv) +// CbcDecrypt the ase cbc decrypt method +func CbcDecrypt(key, iv, src []byte) ([]byte, error) { + a, err := NewCbc(key, iv) if err != nil { return nil, err } - return a.decrypt(src) + return a.Decrypt(src) } -// AesCbcEncryptHex return hex result -func AesCbcEncryptHex(key, iv, src []byte) (string, error) { - a, err := NewAesCbc(key, iv) +// CbcEncryptHex return hex result +func CbcEncryptHex(key, iv, src []byte) (string, error) { + a, err := NewCbc(key, iv) if err != nil { return "", err } - dst, err := a.encrypt(src) + dst, err := a.Encrypt(src) if err != nil { return "", err } @@ -130,9 +121,9 @@ func AesCbcEncryptHex(key, iv, src []byte) (string, error) { return hex.EncodeToString(dst), nil } -// AesCbcDecryptHex decrypt hex msg -func AesCbcDecryptHex(key, iv []byte, msg string) ([]byte, error) { - a, err := NewAesCbc(key, iv) +// CbcDecryptHex decrypt hex msg +func CbcDecryptHex(key, iv []byte, msg string) ([]byte, error) { + a, err := NewCbc(key, iv) if err != nil { return nil, err } @@ -142,16 +133,16 @@ func AesCbcDecryptHex(key, iv []byte, msg string) ([]byte, error) { return nil, err } - return a.decrypt(data) + return a.Decrypt(data) } -// AesCbcEncryptBase64 return base64 result -func AesCbcEncryptBase64(key, iv, src []byte) (string, error) { - a, err := NewAesCbc(key, iv) +// CbcEncryptBase64 return base64 result +func CbcEncryptBase64(key, iv, src []byte) (string, error) { + a, err := NewCbc(key, iv) if err != nil { return "", err } - dst, err := a.encrypt(src) + dst, err := a.Encrypt(src) if err != nil { return "", err } @@ -159,9 +150,9 @@ func AesCbcEncryptBase64(key, iv, src []byte) (string, error) { return base64.StdEncoding.EncodeToString(dst), nil } -// AesCbcDecryptBase64 decrypt base64 msg -func AesCbcDecryptBase64(key, iv []byte, msg string) ([]byte, error) { - a, err := NewAesCbc(key, iv) +// CbcDecryptBase64 decrypt base64 msg +func CbcDecryptBase64(key, iv []byte, msg string) ([]byte, error) { + a, err := NewCbc(key, iv) if err != nil { return nil, err } @@ -170,5 +161,5 @@ func AesCbcDecryptBase64(key, iv []byte, msg string) ([]byte, error) { return nil, err } - return a.decrypt(data) + return a.Decrypt(data) } diff --git a/cipher/aes/aescbc_test.go b/cipher/aes/aescbc_test.go index 7629894..ffa2f8e 100644 --- a/cipher/aes/aescbc_test.go +++ b/cipher/aes/aescbc_test.go @@ -48,14 +48,14 @@ var ( ) var ( - aescbc128, _ = NewAesCbc([]byte(commonKey128), []byte(commonIV)) - aescbc192, _ = NewAesCbc([]byte(commonKey192), []byte(commonIV)) - aescbc256, _ = NewAesCbc([]byte(commonKey256), []byte(commonIV)) + aescbc128, _ = NewCbc([]byte(commonKey128), []byte(commonIV)) + aescbc192, _ = NewCbc([]byte(commonKey192), []byte(commonIV)) + aescbc256, _ = NewCbc([]byte(commonKey256), []byte(commonIV)) ) -func TestAesCbc_Decrypt(t *testing.T) { +func TestCbc_Decrypt(t *testing.T) { type fields struct { - a *AesCbc + a *Cbc } type args struct { in []byte @@ -109,9 +109,9 @@ func TestAesCbc_Decrypt(t *testing.T) { } } -func TestAesCbc_Encrypt(t *testing.T) { +func TestCbc_Encrypt(t *testing.T) { type fields struct { - a *AesCbc + a *Cbc } type args struct { in []byte @@ -165,83 +165,7 @@ func TestAesCbc_Encrypt(t *testing.T) { } } -func TestAesCbc_decrypt(t *testing.T) { - type fields struct { - a *AesCbc - } - type args struct { - in []byte - } - tests := []struct { - name string - fields fields - args args - want []byte - wantErr bool - }{ - { - name: "TestAesCbc_decrypt-256", - fields: fields{a: aescbc256}, - args: args{ - in: commonEncrypted256, - }, - want: []byte(commonSrc), - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := tt.fields.a.decrypt(tt.args.in) - if (err != nil) != tt.wantErr { - t.Errorf("decrypt() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("decrypt() got = %v, want %v", got, tt.want) - } - }) - } -} - -func TestAesCbc_encrypt(t *testing.T) { - type fields struct { - a *AesCbc - } - type args struct { - in []byte - } - tests := []struct { - name string - fields fields - args args - want []byte - wantErr bool - }{ - { - name: "TestAesCbc_encrypt-256", - fields: fields{a: aescbc256}, - args: args{ - in: []byte(commonSrc), - }, - want: commonEncrypted256, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := tt.fields.a.encrypt(tt.args.in) - if (err != nil) != tt.wantErr { - t.Errorf("encrypt() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("encrypt() got = %v, want %v", got, tt.want) - } - }) - } -} - -func TestNewAesCbc(t *testing.T) { +func TestNewCbc(t *testing.T) { type args struct { key []byte iv []byte @@ -249,7 +173,7 @@ func TestNewAesCbc(t *testing.T) { tests := []struct { name string args args - want *AesCbc + want *Cbc wantErr bool }{ { @@ -282,16 +206,16 @@ func TestNewAesCbc(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, err := NewAesCbc(tt.args.key, tt.args.iv) + _, err := NewCbc(tt.args.key, tt.args.iv) if (err != nil) != tt.wantErr { - t.Errorf("NewAesCbc() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("NewCbc() error = %v, wantErr %v", err, tt.wantErr) return } }) } } -func TestAesCbcDecrypt(t *testing.T) { +func TestCbcDecrypt(t *testing.T) { type args struct { key []byte iv []byte @@ -336,19 +260,19 @@ func TestAesCbcDecrypt(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AesCbcDecrypt(tt.args.key, tt.args.iv, tt.args.src) + got, err := CbcDecrypt(tt.args.key, tt.args.iv, tt.args.src) if (err != nil) != tt.wantErr { - t.Errorf("AesCbcDecrypt() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("CbcDecrypt() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", got, tt.want) + t.Errorf("CbcDecrypt() got = %v, want %v", got, tt.want) } }) } } -func TestAesCbcDecryptBase64(t *testing.T) { +func TestCbcDecryptBase64(t *testing.T) { type args struct { key []byte iv []byte @@ -393,19 +317,19 @@ func TestAesCbcDecryptBase64(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AesCbcDecryptBase64(tt.args.key, tt.args.iv, tt.args.msg) + got, err := CbcDecryptBase64(tt.args.key, tt.args.iv, tt.args.msg) if (err != nil) != tt.wantErr { - t.Errorf("AesCbcDecryptBase64() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("CbcDecryptBase64() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("AesCbcDecryptBase64() got = %v, want %v", got, tt.want) + t.Errorf("CbcDecryptBase64() got = %v, want %v", got, tt.want) } }) } } -func TestAesCbcDecryptHex(t *testing.T) { +func TestCbcDecryptHex(t *testing.T) { type args struct { key []byte iv []byte @@ -450,19 +374,19 @@ func TestAesCbcDecryptHex(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AesCbcDecryptHex(tt.args.key, tt.args.iv, tt.args.msg) + got, err := CbcDecryptHex(tt.args.key, tt.args.iv, tt.args.msg) if (err != nil) != tt.wantErr { - t.Errorf("AesCbcDecryptHex() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("CbcDecryptHex() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("AesCbcDecryptHex() got = %v, want %v", got, tt.want) + t.Errorf("CbcDecryptHex() got = %v, want %v", got, tt.want) } }) } } -func TestAesCbcEncrypt(t *testing.T) { +func TestCbcEncrypt(t *testing.T) { type args struct { key []byte iv []byte @@ -507,19 +431,19 @@ func TestAesCbcEncrypt(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AesCbcEncrypt(tt.args.key, tt.args.iv, tt.args.src) + got, err := CbcEncrypt(tt.args.key, tt.args.iv, tt.args.src) if (err != nil) != tt.wantErr { - t.Errorf("AesCbcEncrypt() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("CbcEncrypt() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("AesCbcEncrypt() got = %v, want %v", got, tt.want) + t.Errorf("CbcEncrypt() got = %v, want %v", got, tt.want) } }) } } -func TestAesCbcEncryptBase64(t *testing.T) { +func TestCbcEncryptBase64(t *testing.T) { type args struct { key []byte iv []byte @@ -564,19 +488,19 @@ func TestAesCbcEncryptBase64(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AesCbcEncryptBase64(tt.args.key, tt.args.iv, tt.args.src) + got, err := CbcEncryptBase64(tt.args.key, tt.args.iv, tt.args.src) if (err != nil) != tt.wantErr { - t.Errorf("AesCbcEncryptBase64() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("CbcEncryptBase64() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { - t.Errorf("AesCbcEncryptBase64() got = %v, want %v", got, tt.want) + t.Errorf("CbcEncryptBase64() got = %v, want %v", got, tt.want) } }) } } -func TestAesCbcEncryptHex(t *testing.T) { +func TestCbcEncryptHex(t *testing.T) { type args struct { key []byte iv []byte @@ -621,13 +545,13 @@ func TestAesCbcEncryptHex(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AesCbcEncryptHex(tt.args.key, tt.args.iv, tt.args.src) + got, err := CbcEncryptHex(tt.args.key, tt.args.iv, tt.args.src) if (err != nil) != tt.wantErr { - t.Errorf("AesCbcEncryptHex() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("CbcEncryptHex() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { - t.Errorf("AesCbcEncryptHex() got = %v, want %v", got, tt.want) + t.Errorf("CbcEncryptHex() got = %v, want %v", got, tt.want) } }) } @@ -644,7 +568,7 @@ func TestConcurrentAccess(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(en1, commonEncrypted256) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", en1, commonEncrypted256) + t.Errorf("CbcDecrypt() got = %v, want %v", en1, commonEncrypted256) } } w.Done() @@ -658,7 +582,7 @@ func TestConcurrentAccess(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(en1, commonEncrypted256) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", en1, commonEncrypted256) + t.Errorf("CbcDecrypt() got = %v, want %v", en1, commonEncrypted256) } } w.Done() @@ -672,7 +596,7 @@ func TestConcurrentAccess(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(en1, commonEncrypted256_2) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", en1, commonEncrypted256_2) + t.Errorf("CbcDecrypt() got = %v, want %v", en1, commonEncrypted256_2) } } w.Done() @@ -686,7 +610,7 @@ func TestConcurrentAccess(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(en1, []byte(commonSrc)) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", en1, commonSrc) + t.Errorf("CbcDecrypt() got = %v, want %v", en1, commonSrc) } } w.Done() @@ -700,7 +624,7 @@ func TestConcurrentAccess(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(en1, []byte(commonSrc)) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", en1, commonSrc) + t.Errorf("CbcDecrypt() got = %v, want %v", en1, commonSrc) } } w.Done() @@ -714,7 +638,7 @@ func TestConcurrentAccess(t *testing.T) { t.Error(err) } if !reflect.DeepEqual(en1, []byte(commonSrc2)) { - t.Errorf("AesCbcDecrypt() got = %v, want %v", en1, commonSrc2) + t.Errorf("CbcDecrypt() got = %v, want %v", en1, commonSrc2) } } w.Done() diff --git a/cipher/cipher.go b/cipher/cipher.go index cf8fcba..c3a9330 100644 --- a/cipher/cipher.go +++ b/cipher/cipher.go @@ -1,15 +1,13 @@ package cipher -// The interface is used for usual cipher +// The interface is used for usual cipher // Now it support aescbc // Plan to support aesecb rsa import ( "github.com/sliveryou/go-tool/cipher/aes" ) -// If you want convert encrypted content to appoint format -// You can use convertUtil gitlab.33.cn\util\go-kit\convert package -// Such as hex convertUtil.BytesEncodeHex(bytes) +var _ Cipher = (*aes.Cbc)(nil) // The cipher will deal with some diffirent between php/nodejs cipher // Such as aescbc add pkcs7Padding to be same as php's aescbc @@ -24,32 +22,33 @@ type Cipher interface { // The follow is a aescbc demo -// import cipherUtil "gitlab.33.cn/utils/go-kit/cipher" -// cipher, err := cipherUtil.NewAesCbc(key, iv) -// if err != nil { -// //deal error -// } -// //encrypt -// dst, err := cipher.Encrypt(src) -// if err != nil { -// //deal error -// } +// import "github.com/sliveryou/go-tool/cipher" // -// //decrypt -// dst, err := cipher.Decrypt(dst) -// if err != nil { -// //deal error -// } +// cr, err := cipher.NewCbc(key, iv) +// if err != nil { +// // deal error +// } +// // encrypt +// dst, err := cr.Encrypt(src) +// if err != nil { +// // deal error +// } +// +// // decrypt +// dst, err := cr.Decrypt(dst) +// if err != nil { +// // deal error +// } // NewAesCbc support aescbc-128 aescbc-192 aescbc-256 // match key len 16 24 32 -func NewAesCbc(key, iv string) (Cipher, error) { - return aes.NewAesCbc([]byte(key), []byte(iv)) +func NewAesCbc(key, iv string) (*aes.Cbc, error) { + return aes.NewCbc([]byte(key), []byte(iv)) } // MustNewAesCbc NewAesCbc err will panic , be careful -func MustNewAesCbc(key, iv string) Cipher { - c, err := aes.NewAesCbc([]byte(key), []byte(iv)) +func MustNewAesCbc(key, iv string) *aes.Cbc { + c, err := aes.NewCbc([]byte(key), []byte(iv)) if err != nil { panic(err) } diff --git a/cipher/pkcs/pkcs5_test.go b/cipher/pkcs/pkcs5_test.go index 1647ef2..9b3afdd 100644 --- a/cipher/pkcs/pkcs5_test.go +++ b/cipher/pkcs/pkcs5_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -var encrypt_8 = []byte{97, 115, 100, 102, 4, 4, 4, 4} +var encrypt8 = []byte{97, 115, 100, 102, 4, 4, 4, 4} func TestPKCS5Padding(t *testing.T) { type args struct { @@ -21,7 +21,7 @@ func TestPKCS5Padding(t *testing.T) { args: args{ cipherText: cipherText, }, - want: encrypt_8, + want: encrypt8, }, } for _, tt := range tests { @@ -46,7 +46,7 @@ func TestPKCS5Trimming(t *testing.T) { { name: "", args: args{ - encrypt: encrypt_8, + encrypt: encrypt8, }, want: cipherText, wantErr: false, diff --git a/cipher/pkcs/pkcs7_test.go b/cipher/pkcs/pkcs7_test.go index cad9ffc..d127d13 100644 --- a/cipher/pkcs/pkcs7_test.go +++ b/cipher/pkcs/pkcs7_test.go @@ -7,7 +7,7 @@ import ( var ( cipherText = []byte("asdf") - encrypt_16 = []byte{ + encrypt16 = []byte{ 97, 115, 100, 102, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, } @@ -29,7 +29,7 @@ func TestPKCS7Padding(t *testing.T) { cipherText: cipherText, blockSize: 16, }, - want: encrypt_16, + want: encrypt16, }, } for _, tt := range tests { @@ -54,7 +54,7 @@ func TestPKCS7Trimming(t *testing.T) { { name: "", args: args{ - encrypt: encrypt_16, + encrypt: encrypt16, }, want: cipherText, wantErr: false, diff --git a/convert/convert.go b/convert/convert.go index 85759d0..ea91227 100644 --- a/convert/convert.go +++ b/convert/convert.go @@ -369,8 +369,8 @@ func BinToDec(bin string) int64 { } // HexToBin returns the binary string result converted by hexadecimal string hex. -func HexToBin(hex string) string { - i, _ := strconv.ParseInt(strings.TrimPrefix(hex, "0x"), 16, 64) +func HexToBin(h string) string { + i, _ := strconv.ParseInt(strings.TrimPrefix(h, "0x"), 16, 64) return strconv.FormatInt(i, 2) } @@ -386,7 +386,7 @@ func DecToHex(dec int64) string { } // HexToDec returns the decimal int64 result converted by hexadecimal string hex. -func HexToDec(hex string) int64 { - dec, _ := strconv.ParseInt(strings.TrimPrefix(hex, "0x"), 16, 64) +func HexToDec(h string) int64 { + dec, _ := strconv.ParseInt(strings.TrimPrefix(h, "0x"), 16, 64) return dec } diff --git a/convert/convert_test.go b/convert/convert_test.go index ce24119..71b4c77 100644 --- a/convert/convert_test.go +++ b/convert/convert_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestToString(t *testing.T) { @@ -341,7 +342,7 @@ func TestToFloat(t *testing.T) { for _, c := range cases { get := ToFloat(c.src) - assert.Equal(t, c.expect, get) + assert.InDelta(t, c.expect, get, 0.001) } } @@ -379,7 +380,7 @@ func TestToFloat32(t *testing.T) { for _, c := range cases { get := ToFloat32(c.src) - assert.Equal(t, c.expect, get) + assert.InDelta(t, c.expect, get, 0.001) } } @@ -417,7 +418,7 @@ func TestToFloat64(t *testing.T) { for _, c := range cases { get := ToFloat64(c.src) - assert.Equal(t, c.expect, get) + assert.InDelta(t, c.expect, get, 0.001) } } @@ -474,7 +475,7 @@ func TestFloat64BytesConversion(t *testing.T) { for _, c := range cases { get := Float64ToBytes(c.src) - assert.Equal(t, c.src, BytesToFloat64(get)) + assert.InDelta(t, c.src, BytesToFloat64(get), 0.001) t.Log(get) } } @@ -588,23 +589,27 @@ func TestJsonUnmarshal(t *testing.T) { d := json.NewDecoder(strings.NewReader(s)) d.UseNumber() err := d.Decode(&m1) - assert.NoError(t, err) + require.NoError(t, err) - a := m1["a"].(map[string]interface{}) - b := a["b"].(map[string]interface{}) + a, ok := m1["a"].(map[string]interface{}) + assert.True(t, ok) + b, ok := a["b"].(map[string]interface{}) + assert.True(t, ok) assert.Equal(t, "764197655051251712", ToString(b["ids"])) assert.Equal(t, int64(764197655051251712), ToInt64(b["ids"])) - assert.Equal(t, float64(764197655051251700), ToFloat64(b["ids"])) + assert.InDelta(t, float64(764197655051251700), ToFloat64(b["ids"]), 0.001) m2 := make(map[string]interface{}) err = json.Unmarshal([]byte(s), &m2) - assert.NoError(t, err) + require.NoError(t, err) - a = m2["a"].(map[string]interface{}) - b = a["b"].(map[string]interface{}) + a, ok = m2["a"].(map[string]interface{}) + assert.True(t, ok) + b, ok = a["b"].(map[string]interface{}) + assert.True(t, ok) assert.Equal(t, "764197655051251700", ToString(b["ids"])) assert.Equal(t, int64(764197655051251712), ToInt64(b["ids"])) - assert.Equal(t, float64(764197655051251700), ToFloat64(b["ids"])) + assert.InDelta(t, float64(764197655051251700), ToFloat64(b["ids"]), 0.001) } diff --git a/filex/filex_test.go b/filex/filex_test.go index 67c18fb..7c0679d 100644 --- a/filex/filex_test.go +++ b/filex/filex_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/sliveryou/go-tool/mathx" ) @@ -76,86 +77,86 @@ func TestDirSize(t *testing.T) { func TestHash(t *testing.T) { hashStr, err := Hash("./testdata/test.txt", md5.New()) - assert.NoError(t, err) + require.NoError(t, err) t.Log(hashStr) md5Str, err := MD5("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log(md5Str) sha1Str, err := SHA1("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log(sha1Str) sha256, err := SHA256("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log(sha256) sha512, err := SHA512("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log(sha512) } func TestRead(t *testing.T) { content, err := Read("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log("\n" + string(content)) content, err = Read("./testdata/test.md") - assert.NoError(t, err) + require.NoError(t, err) t.Log("\n" + string(content)) } func TestReadToSlice(t *testing.T) { slice, err := ReadToSlice("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log(slice) } func TestWrite(t *testing.T) { data := []byte("Hello, world!") err := Write("./testdata/testdir/testfile.txt", data) - assert.NoError(t, err) + require.NoError(t, err) } func TestAppend(t *testing.T) { data := []byte("\nHello, world!") err := Append("./testdata/testdir/testfile.txt", data) - assert.NoError(t, err) + require.NoError(t, err) } func TestCopy(t *testing.T) { err := Copy("./testdata/test.md", "./testdata/testdir/test.md") - assert.NoError(t, err) + require.NoError(t, err) } func TestRename(t *testing.T) { err := Rename("./testdata/testdir/testfile.txt", "./testdata/testdir/file.txt") - assert.NoError(t, err) + require.NoError(t, err) } func TestRemove(t *testing.T) { err := Remove("./testdata/testdir/file.txt") - assert.NoError(t, err) + require.NoError(t, err) } func TestMkdir(t *testing.T) { err := Mkdir("./testdata/testdir") - assert.NoError(t, err) + require.NoError(t, err) } func TestDeldir(t *testing.T) { err := Deldir("./testdata/testdir") - assert.NoError(t, err) + require.NoError(t, err) } func TestAbsPath(t *testing.T) { absPath, err := AbsPath("./testdata/test.png") - assert.NoError(t, err) + require.NoError(t, err) t.Log(absPath) absPath, err = AbsPath("./testdata/test.txt") - assert.NoError(t, err) + require.NoError(t, err) t.Log(absPath) } diff --git a/id-generator/encoding/base58/base58_test.go b/id-generator/encoding/base58/base58_test.go index 241614f..3aad49b 100644 --- a/id-generator/encoding/base58/base58_test.go +++ b/id-generator/encoding/base58/base58_test.go @@ -4,10 +4,12 @@ import ( "fmt" "math" "math/rand" + "strconv" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStdSource(t *testing.T) { @@ -29,11 +31,11 @@ func TestMustNewEncoder(t *testing.T) { func TestNewEncoder(t *testing.T) { enc, err := NewEncoder("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, enc) _, err = NewEncoder("test") - assert.EqualError(t, err, "base58: encoding source is not 58-bytes long") + require.EqualError(t, err, "base58: encoding source is not 58-bytes long") } func TestStdEncoding_Encode(t *testing.T) { @@ -64,9 +66,8 @@ func TestStdEncoding_Decode(t *testing.T) { for k, v := range cases { d, err := StdEncoding.Decode(v) - if assert.Nil(t, err) { - assert.Equal(t, k, d) - } + require.NoError(t, err) + assert.Equal(t, k, d) } } @@ -104,9 +105,8 @@ func TestEncoder_Decode(t *testing.T) { for k, v := range cases { d, err := enc.Decode(v) - if assert.Nil(t, err) { - assert.Equal(t, k, d) - } + require.NoError(t, err) + assert.Equal(t, k, d) } } @@ -114,6 +114,7 @@ func BenchmarkEncoder_Encode(b *testing.B) { s := rand.New(rand.NewSource(time.Now().UnixNano())) enc := MustNewEncoder(StdSource()) benchFunc := func(b *testing.B, id int64) { + b.Helper() for i := 0; i < b.N; i++ { enc.Encode(id) } @@ -121,7 +122,7 @@ func BenchmarkEncoder_Encode(b *testing.B) { for i := 0; i < 5; i++ { id := s.Int63() - b.Run(fmt.Sprintf("%d", id), func(b *testing.B) { + b.Run(strconv.FormatInt(id, 10), func(b *testing.B) { benchFunc(b, id) }) } @@ -131,6 +132,7 @@ func BenchmarkEncoder_Decode(b *testing.B) { s := rand.New(rand.NewSource(time.Now().UnixNano())) enc := MustNewEncoder(StdSource()) benchFunc := func(b *testing.B, id int64, idStr string) { + b.Helper() for i := 0; i < b.N; i++ { _, _ = enc.Decode(idStr) } diff --git a/id-generator/encoding/base62/base62_test.go b/id-generator/encoding/base62/base62_test.go index ca45364..c5534ae 100644 --- a/id-generator/encoding/base62/base62_test.go +++ b/id-generator/encoding/base62/base62_test.go @@ -4,10 +4,12 @@ import ( "fmt" "math" "math/rand" + "strconv" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStdSource(t *testing.T) { @@ -29,11 +31,11 @@ func TestMustNewEncoder(t *testing.T) { func TestNewEncoder(t *testing.T) { enc, err := NewEncoder("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, enc) _, err = NewEncoder("test") - assert.EqualError(t, err, "base62: encoding source is not 62-bytes long") + require.EqualError(t, err, "base62: encoding source is not 62-bytes long") } func TestStdEncoding_Encode(t *testing.T) { @@ -64,9 +66,8 @@ func TestStdEncoding_Decode(t *testing.T) { for k, v := range cases { d, err := StdEncoding.Decode(v) - if assert.Nil(t, err) { - assert.Equal(t, k, d) - } + require.NoError(t, err) + assert.Equal(t, k, d) } } @@ -104,9 +105,8 @@ func TestEncoder_Decode(t *testing.T) { for k, v := range cases { d, err := enc.Decode(v) - if assert.Nil(t, err) { - assert.Equal(t, k, d) - } + require.NoError(t, err) + assert.Equal(t, k, d) } } @@ -114,6 +114,7 @@ func BenchmarkEncoder_Encode(b *testing.B) { s := rand.New(rand.NewSource(time.Now().UnixNano())) enc := MustNewEncoder(StdSource()) benchFunc := func(b *testing.B, id int64) { + b.Helper() for i := 0; i < b.N; i++ { enc.Encode(id) } @@ -121,7 +122,7 @@ func BenchmarkEncoder_Encode(b *testing.B) { for i := 0; i < 5; i++ { id := s.Int63() - b.Run(fmt.Sprintf("%d", id), func(b *testing.B) { + b.Run(strconv.FormatInt(id, 10), func(b *testing.B) { benchFunc(b, id) }) } @@ -131,6 +132,7 @@ func BenchmarkEncoder_Decode(b *testing.B) { s := rand.New(rand.NewSource(time.Now().UnixNano())) enc := MustNewEncoder(StdSource()) benchFunc := func(b *testing.B, id int64, idStr string) { + b.Helper() for i := 0; i < b.N; i++ { _, _ = enc.Decode(idStr) } diff --git a/id-generator/snowflake/snowflake.go b/id-generator/snowflake/snowflake.go index d867aa4..511d3a4 100644 --- a/id-generator/snowflake/snowflake.go +++ b/id-generator/snowflake/snowflake.go @@ -124,11 +124,10 @@ func (s *Snowflake) NextId() (int64, error) { } else { s.sequenceId = (s.sequenceId + 1) & sequenceMax if s.sequenceId == 0 { - if s.elapsedTime-current <= s.tolerateMillis { - s.elapsedTime = s.waitNextElapsedTime(current) - } else { + if s.elapsedTime-current > s.tolerateMillis { return 0, ErrClockBackward } + s.elapsedTime = s.waitNextElapsedTime(current) } } diff --git a/id-generator/snowflake/snowflake_test.go b/id-generator/snowflake/snowflake_test.go index bee82d8..33c80ee 100644 --- a/id-generator/snowflake/snowflake_test.go +++ b/id-generator/snowflake/snowflake_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/sliveryou/go-tool/id-generator/encoding/base58" "github.com/sliveryou/go-tool/id-generator/encoding/base62" @@ -15,38 +16,38 @@ func TestNewSnowflake(t *testing.T) { _, err := NewSnowflake(&Config{ MaxTolerateMillis: -1, }) - assert.EqualError(t, err, "invalid max tolerate millis") + require.EqualError(t, err, "invalid max tolerate millis") _, err = NewSnowflake(&Config{ NodeId: func() (int64, error) { return -1, nil }, }) - assert.EqualError(t, err, "invalid node id") + require.EqualError(t, err, "invalid node id") _, err = NewSnowflake(&Config{ StartTime: time.Now().Add(time.Minute), }) - assert.EqualError(t, err, "invalid start time") + require.EqualError(t, err, "invalid start time") _, err = NewSnowflake(&Config{ LastGenerateTime: func() (time.Time, error) { return time.Now().Add(time.Minute), nil }, }) - assert.EqualError(t, err, "invalid last generate time") + require.EqualError(t, err, "invalid last generate time") s, err := NewSnowflake(&Config{ NodeId: NodeId(1), MaxTolerateMillis: 10, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, s) } func TestSnowflake_NextId(t *testing.T) { snowflake, err := NewSnowflake(&Config{NodeId: NodeId(1), MaxTolerateMillis: 10}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, snowflake) c := make(chan int64) @@ -57,9 +58,8 @@ func TestSnowflake_NextId(t *testing.T) { go func() { defer wg.Done() id, err := snowflake.NextId() - if assert.Nil(t, err) { - c <- id - } + require.NoError(t, err) + c <- id }() } @@ -83,15 +83,15 @@ func TestSnowflake_NextId(t *testing.T) { func TestSnowflake_NextId_MultiNodes(t *testing.T) { snowflake1, err := NewSnowflake(&Config{NodeId: NodeId(1), MaxTolerateMillis: 10}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, snowflake1) snowflake2, err := NewSnowflake(&Config{NodeId: NodeId(2), MaxTolerateMillis: 10}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, snowflake2) snowflake3, err := NewSnowflake(&Config{NodeId: NodeId(3), MaxTolerateMillis: 10}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, snowflake3) c := make(chan int64) @@ -101,9 +101,8 @@ func TestSnowflake_NextId_MultiNodes(t *testing.T) { nextIdFunc := func(s *Snowflake) { defer wg.Done() id, err := s.NextId() - if assert.Nil(t, err) { - c <- id - } + require.NoError(t, err) + c <- id } for i := 0; i < 50; i++ { @@ -132,7 +131,7 @@ func TestSnowflake_NextId_MultiNodes(t *testing.T) { func TestParse(t *testing.T) { snowflake, err := NewSnowflake(&Config{NodeId: NodeId(1), MaxTolerateMillis: 10}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, snowflake) wg := sync.WaitGroup{} @@ -142,13 +141,12 @@ func TestParse(t *testing.T) { go func() { defer wg.Done() id, err := snowflake.NextId() - if assert.Nil(t, err) { - t.Logf("id:%v parse:%v base58:%v base62:%v", - id, Parse(id), - base58.StdEncoding.Encode(id), - base62.StdEncoding.Encode(id), - ) - } + require.NoError(t, err) + t.Logf("id:%v parse:%v base58:%v base62:%v", + id, Parse(id), + base58.StdEncoding.Encode(id), + base62.StdEncoding.Encode(id), + ) }() } diff --git a/id-generator/uuid/uuid_test.go b/id-generator/uuid/uuid_test.go index 6fc3d1c..8f09aea 100644 --- a/id-generator/uuid/uuid_test.go +++ b/id-generator/uuid/uuid_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNextV1(t *testing.T) { @@ -57,15 +58,15 @@ func TestDecompose(t *testing.T) { expect := "936dbe97-ec4e-4ded-b459-ef676b566485" u1, err := Parse("936dbe97-ec4e-4ded-b459-ef676b566485") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expect, u1.String()) u2, err := Parse("936dbe97ec4e4dedb459ef676b566485") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expect, u2.String()) _, err = Parse("err uuid") - assert.Error(t, err) + require.Error(t, err) } func BenchmarkNextV1(b *testing.B) { diff --git a/mathx/mathx.go b/mathx/mathx.go index 4993f35..37df718 100644 --- a/mathx/mathx.go +++ b/mathx/mathx.go @@ -560,12 +560,11 @@ func SizeFormat(size float64, places int, separator ...string) string { } index := 0 for { - if size >= 1024 { - size /= 1024 - index++ - } else { + if size < 1024 { break } + size /= 1024 + index++ } if index >= len(sizeUnits) { index = len(sizeUnits) - 1 @@ -581,7 +580,7 @@ func NumberFormat(num float64, places int, separator ...string) string { isNegative = true } roundStr := RoundToString(num, places) - prefix, suffix := "", "" + var prefix, suffix string if places > 0 { splits := strings.Split(roundStr, ".") prefix = splits[0] diff --git a/mathx/mathx_test.go b/mathx/mathx_test.go index 6775048..192a4a7 100644 --- a/mathx/mathx_test.go +++ b/mathx/mathx_test.go @@ -7,8 +7,8 @@ import ( ) func TestRound(t *testing.T) { - assert.Equal(t, 123.46, Round(123.45678, 2)) - assert.Equal(t, 123.456, RoundBank(123.4565, 3)) + assert.InEpsilon(t, 123.46, Round(123.45678, 2), 0.01) + assert.InEpsilon(t, 123.456, RoundBank(123.4565, 3), 0.001) assert.Equal(t, "123.46", RoundToString(123.45678, 2)) assert.Equal(t, "123.456", RoundBankToString(123.4565, 3)) } @@ -91,51 +91,51 @@ func TestRand(t *testing.T) { } func TestMax(t *testing.T) { - assert.Equal(t, 10.1, Max(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4)) + assert.InEpsilon(t, 10.1, Max(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4), 0.001) assert.Equal(t, 9, MaxInt(1, 3, 9, 7, 5)) assert.Equal(t, int64(9), MaxInt64(1, 3, 9, 7, 5)) - assert.Equal(t, 10.1, MaxFloat(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4)) - assert.Equal(t, 10.1, MaxFloat64(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4)) + assert.InEpsilon(t, 10.1, MaxFloat(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4), 0.001) + assert.InEpsilon(t, 10.1, MaxFloat64(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4), 0.001) } func TestMin(t *testing.T) { - assert.Equal(t, 0.0, Min(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4)) + assert.InDelta(t, 0.0, Min(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4), 0.001) assert.Equal(t, 1, MinInt(1, 3, 9, 7, 5)) assert.Equal(t, int64(1), MinInt64(1, 3, 9, 7, 5)) - assert.Equal(t, 0.0, MinFloat(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4)) - assert.Equal(t, 0.0, MinFloat64(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4)) + assert.InDelta(t, 0.0, MinFloat(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4), 0.001) + assert.InDelta(t, 0.0, MinFloat64(1, 5.0, 2.0, 3.5, 8, 0, 10.1, 7, 4), 0.001) } func TestSum(t *testing.T) { - assert.Equal(t, 16.5, Sum(1.1, 2.2, 3.3, 4.4, 5.5)) + assert.InDelta(t, 16.5, Sum(1.1, 2.2, 3.3, 4.4, 5.5), 0.001) assert.Equal(t, 15, SumInt(1, 2, 3, 4, 5)) assert.Equal(t, int64(15), SumInt64(1, 2, 3, 4, 5)) - assert.Equal(t, 16.5, SumFloat(1.1, 2.2, 3.3, 4.4, 5.5)) - assert.Equal(t, 16.5, SumFloat64(1.1, 2.2, 3.3, 4.4, 5.5)) + assert.InDelta(t, 16.5, SumFloat(1.1, 2.2, 3.3, 4.4, 5.5), 0.001) + assert.InDelta(t, 16.5, SumFloat64(1.1, 2.2, 3.3, 4.4, 5.5), 0.001) } func TestAverage(t *testing.T) { - assert.Equal(t, 3.3, Average(1.1, 2.2, 3.3, 4.4, 5.5)) - assert.Equal(t, 3.0, AverageInt(1, 2, 3, 4, 5)) - assert.Equal(t, 3.0, AverageInt64(1, 2, 3, 4, 5)) - assert.Equal(t, 3.3, AverageFloat(1.1, 2.2, 3.3, 4.4, 5.5)) - assert.Equal(t, 3.3, AverageFloat64(1.1, 2.2, 3.3, 4.4, 5.5)) + assert.InDelta(t, 3.3, Average(1.1, 2.2, 3.3, 4.4, 5.5), 0.001) + assert.InDelta(t, 3.0, AverageInt(1, 2, 3, 4, 5), 0.001) + assert.InDelta(t, 3.0, AverageInt64(1, 2, 3, 4, 5), 0.001) + assert.InDelta(t, 3.3, AverageFloat(1.1, 2.2, 3.3, 4.4, 5.5), 0.001) + assert.InDelta(t, 3.3, AverageFloat64(1.1, 2.2, 3.3, 4.4, 5.5), 0.001) } func TestAbs(t *testing.T) { - assert.Equal(t, 100, AbsInt(-100)) + assert.InDelta(t, 100, AbsInt(-100), 0.001) assert.Equal(t, int64(100), AbsInt64(-100)) - assert.Equal(t, 123.456, AbsFloat(-123.456)) - assert.Equal(t, 123.456, AbsFloat64(-123.456)) - assert.Equal(t, 0.0, AbsFloat64(0)) + assert.InDelta(t, 123.456, AbsFloat(-123.456), 0.001) + assert.InDelta(t, 123.456, AbsFloat64(-123.456), 0.001) + assert.InDelta(t, 0.0, AbsFloat64(0), 0.001) } func TestPercent(t *testing.T) { - assert.Equal(t, 15.0, Percent(15, 100)) + assert.InDelta(t, 15.0, Percent(15, 100), 0.001) assert.Greater(t, Percent("10", "98"), 10.2) - assert.Equal(t, 12.34, Percent(12.34, "100")) - assert.Equal(t, 0.0, Percent(123, "abcd")) - assert.Equal(t, 0.0, Percent(0, "123")) + assert.InDelta(t, 12.34, Percent(12.34, "100"), 0.001) + assert.InDelta(t, 0.0, Percent(123, "abcd"), 0.001) + assert.InDelta(t, 0.0, Percent(0, "123"), 0.001) } func TestSizeFormat(t *testing.T) { diff --git a/randx/randx_test.go b/randx/randx_test.go index e752a7f..5de0980 100644 --- a/randx/randx_test.go +++ b/randx/randx_test.go @@ -99,6 +99,7 @@ func TestNewWithSource(t *testing.T) { func BenchmarkNewString(b *testing.B) { benchFunc := func(b *testing.B, length int) { + b.Helper() for i := 0; i < b.N; i++ { NewString(length) } @@ -114,6 +115,7 @@ func BenchmarkNewString(b *testing.B) { func BenchmarkNewNumber(b *testing.B) { benchFunc := func(b *testing.B, length int) { + b.Helper() for i := 0; i < b.N; i++ { NewNumber(length) } @@ -129,6 +131,7 @@ func BenchmarkNewNumber(b *testing.B) { func BenchmarkNewWithSource(b *testing.B) { benchFunc := func(b *testing.B, length int, source string) { + b.Helper() for i := 0; i < b.N; i++ { NewWithSource(length, source) } diff --git a/slicex/extract.go b/slicex/extract.go index 1a53e25..37e6485 100644 --- a/slicex/extract.go +++ b/slicex/extract.go @@ -31,11 +31,10 @@ func Extract(slice interface{}, num int) []interface{} { } result := make([]interface{}, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = value.Index(v).Interface() - } else { + if i >= num { break } + result[i] = value.Index(v).Interface() } return result default: @@ -58,11 +57,10 @@ func ExtractStrings(slice []string, num int) []string { } result := make([]string, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } @@ -82,11 +80,10 @@ func ExtractBools(slice []bool, num int) []bool { } result := make([]bool, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } @@ -106,11 +103,10 @@ func ExtractInts(slice []int, num int) []int { } result := make([]int, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } @@ -130,11 +126,10 @@ func ExtractInt64s(slice []int64, num int) []int64 { } result := make([]int64, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } @@ -154,11 +149,10 @@ func ExtractInt32s(slice []int32, num int) []int32 { } result := make([]int32, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } @@ -184,11 +178,10 @@ func ExtractFloat64s(slice []float64, num int) []float64 { } result := make([]float64, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } @@ -208,11 +201,10 @@ func ExtractFloat32s(slice []float32, num int) []float32 { } result := make([]float32, num) for i, v := range rand.Perm(length) { - if i < num { - result[i] = slice[v] - } else { + if i >= num { break } + result[i] = slice[v] } return result } diff --git a/slicex/extract_test.go b/slicex/extract_test.go index 346b2b6..5d9c03a 100644 --- a/slicex/extract_test.go +++ b/slicex/extract_test.go @@ -15,14 +15,14 @@ func TestExtract(t *testing.T) { }) arr1 := []string{"sliveryou", "sliver", "you", "a", "b", "c", "d"} - assert.Equal(t, 3, len(Extract(arr1, 3))) - assert.Equal(t, 7, len(Extract(arr1, 10))) + assert.Len(t, Extract(arr1, 3), 3) + assert.Len(t, Extract(arr1, 10), 7) assert.Empty(t, Extract(arr1, 0)) assert.Empty(t, Extract(nil, 0)) arr2 := []int{5, 6, 7, 8, 9, 10, 11} - assert.Equal(t, 3, len(Extract(arr2, 3))) - assert.Equal(t, 7, len(Extract(arr2, 10))) + assert.Len(t, Extract(arr2, 3), 3) + assert.Len(t, Extract(arr2, 10), 7) assert.Empty(t, Extract(arr2, 0)) assert.Empty(t, Extract(nil, 10)) } @@ -30,8 +30,8 @@ func TestExtract(t *testing.T) { func TestExtractStrings(t *testing.T) { arr := []string{"sliveryou", "sliver", "you", "a", "b", "c", "d"} - assert.Equal(t, 3, len(ExtractStrings(arr, 3))) - assert.Equal(t, 7, len(ExtractStrings(arr, 10))) + assert.Len(t, ExtractStrings(arr, 3), 3) + assert.Len(t, ExtractStrings(arr, 10), 7) assert.Empty(t, ExtractStrings(arr, 0)) assert.Empty(t, ExtractStrings([]string{}, 10)) assert.Empty(t, ExtractStrings(nil, 10)) @@ -40,8 +40,8 @@ func TestExtractStrings(t *testing.T) { func TestExtractBools(t *testing.T) { arr := []bool{true, false, true, true, true, false, false} - assert.Equal(t, 3, len(ExtractBools(arr, 3))) - assert.Equal(t, 7, len(ExtractBools(arr, 10))) + assert.Len(t, ExtractBools(arr, 3), 3) + assert.Len(t, ExtractBools(arr, 10), 7) assert.Empty(t, ExtractBools(arr, 0)) assert.Empty(t, ExtractBools([]bool{}, 10)) assert.Empty(t, ExtractBools(nil, 10)) @@ -50,8 +50,8 @@ func TestExtractBools(t *testing.T) { func TestExtractInts(t *testing.T) { arr := []int{5, 6, 7, 8, 9, 10, 11} - assert.Equal(t, 3, len(ExtractInts(arr, 3))) - assert.Equal(t, 7, len(ExtractInts(arr, 10))) + assert.Len(t, ExtractInts(arr, 3), 3) + assert.Len(t, ExtractInts(arr, 10), 7) assert.Empty(t, ExtractInts(arr, 0)) assert.Empty(t, ExtractInts([]int{}, 10)) assert.Empty(t, ExtractInts(nil, 10)) @@ -60,8 +60,8 @@ func TestExtractInts(t *testing.T) { func TestExtractInt64s(t *testing.T) { arr := []int64{5, 6, 7, 8, 9, 10, 11} - assert.Equal(t, 3, len(ExtractInt64s(arr, 3))) - assert.Equal(t, 7, len(ExtractInt64s(arr, 10))) + assert.Len(t, ExtractInt64s(arr, 3), 3) + assert.Len(t, ExtractInt64s(arr, 10), 7) assert.Empty(t, ExtractInt64s(arr, 0)) assert.Empty(t, ExtractInt64s([]int64{}, 10)) assert.Empty(t, ExtractInt64s(nil, 10)) @@ -70,8 +70,8 @@ func TestExtractInt64s(t *testing.T) { func TestExtractInt32s(t *testing.T) { arr := []int32{5, 6, 7, 8, 9, 10, 11} - assert.Equal(t, 3, len(ExtractInt32s(arr, 3))) - assert.Equal(t, 7, len(ExtractInt32s(arr, 10))) + assert.Len(t, ExtractInt32s(arr, 3), 3) + assert.Len(t, ExtractInt32s(arr, 10), 7) assert.Empty(t, ExtractInt32s(arr, 0)) assert.Empty(t, ExtractInt32s([]int32{}, 10)) assert.Empty(t, ExtractInt32s(nil, 10)) @@ -80,8 +80,8 @@ func TestExtractInt32s(t *testing.T) { func TestExtractFloats(t *testing.T) { arr := []float64{5.5, 6.6, 7.7, 8.8, 9.9, 10.10, 11.11} - assert.Equal(t, 3, len(ExtractFloats(arr, 3))) - assert.Equal(t, 7, len(ExtractFloats(arr, 10))) + assert.Len(t, ExtractFloats(arr, 3), 3) + assert.Len(t, ExtractFloats(arr, 10), 7) assert.Empty(t, ExtractFloats(arr, 0)) assert.Empty(t, ExtractFloats([]float64{}, 10)) assert.Empty(t, ExtractFloats(nil, 10)) @@ -90,8 +90,8 @@ func TestExtractFloats(t *testing.T) { func TestExtractFloat64s(t *testing.T) { arr := []float64{5.5, 6.6, 7.7, 8.8, 9.9, 10.10, 11.11} - assert.Equal(t, 3, len(ExtractFloat64s(arr, 3))) - assert.Equal(t, 7, len(ExtractFloat64s(arr, 10))) + assert.Len(t, ExtractFloat64s(arr, 3), 3) + assert.Len(t, ExtractFloat64s(arr, 10), 7) assert.Empty(t, ExtractFloat64s(arr, 0)) assert.Empty(t, ExtractFloat64s([]float64{}, 10)) assert.Empty(t, ExtractFloat64s(nil, 10)) @@ -100,8 +100,8 @@ func TestExtractFloat64s(t *testing.T) { func TestExtractFloat32s(t *testing.T) { arr := []float32{5.5, 6.6, 7.7, 8.8, 9.9, 10.10, 11.11} - assert.Equal(t, 3, len(ExtractFloat32s(arr, 3))) - assert.Equal(t, 7, len(ExtractFloat32s(arr, 10))) + assert.Len(t, ExtractFloat32s(arr, 3), 3) + assert.Len(t, ExtractFloat32s(arr, 10), 7) assert.Empty(t, ExtractFloat32s(arr, 0)) assert.Empty(t, ExtractFloat32s([]float32{}, 10)) assert.Empty(t, ExtractFloat32s(nil, 10)) diff --git a/timex/timex.go b/timex/timex.go index b346c6a..e036483 100644 --- a/timex/timex.go +++ b/timex/timex.go @@ -14,7 +14,8 @@ var ( shanghai = Location("Asia/Shanghai") // Shanghai *time.Location ) -// Location returns *time.Location by location name. +// Location returns *time.Location by location name, +// if an err occurred, the location will be time.Local. func Location(name string) *time.Location { loc, err := time.LoadLocation(name) if err != nil { @@ -273,11 +274,11 @@ func StringToUnix(str, layout string, location ...*time.Location) int64 { } // UnixTodayRange returns today start unix second timestamp and today end unix second timestamp. -func UnixTodayRange(location ...*time.Location) (int64, int64) { +func UnixTodayRange(location ...*time.Location) (start, end int64) { loc := getLocation(location...) year, month, day := time.Now().In(loc).Date() - start := time.Date(year, month, day, 0, 0, 0, 0, loc).Unix() - end := time.Date(year, month, day, 23, 59, 59, 0, loc).Unix() + start = time.Date(year, month, day, 0, 0, 0, 0, loc).Unix() + end = time.Date(year, month, day, 23, 59, 59, 0, loc).Unix() return start, end } diff --git a/timex/timex_test.go b/timex/timex_test.go index 69deaff..63b45ef 100644 --- a/timex/timex_test.go +++ b/timex/timex_test.go @@ -6,12 +6,13 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLocation(t *testing.T) { assertion := assert.New(t) - assertion.Panics(func() { + assertion.NotPanics(func() { Location("ErrLocationName") }) assertion.NotPanics(func() { @@ -162,8 +163,9 @@ func TestStringToTime(t *testing.T) { for _, c := range cases { get, err := StringToTime(c.str, c.layout) if c.wantErr { - assert.EqualError(t, err, "timex: str does not match layout") - } else if assert.NoError(t, err) { + require.EqualError(t, err, "timex: str does not match layout") + } else { + require.NoError(t, err) assert.Equal(t, c.expect, get.String()) } } diff --git a/validator/bankcard.go b/validator/bankcard.go index 7a177b4..d38ecd6 100644 --- a/validator/bankcard.go +++ b/validator/bankcard.go @@ -35,7 +35,7 @@ func NewBankCard(bankcard string) BankCard { // IsValid checks the bank card is valid. func (bc BankCard) IsValid() bool { bcStr := strings.ToUpper(string(bc)) - if !bankcardRegex.Match([]byte(bcStr)) { + if !bankcardRegex.MatchString(bcStr) { return false } @@ -43,15 +43,15 @@ func (bc BankCard) IsValid() bool { length := len(bcStr) for index := length - 1; index >= 0; index-- { - if value, err := strconv.Atoi(string(bcStr[index])); err == nil { - if (length-index)%2 == 0 { - sum += valueDoubleSumMap[value] - } else { - sum += value - } - } else { + value, err := strconv.Atoi(string(bcStr[index])) + if err != nil { return false } + if (length-index)%2 == 0 { + sum += valueDoubleSumMap[value] + } else { + sum += value + } } return sum%10 == 0 diff --git a/validator/corpaccount.go b/validator/corpaccount.go index 0da5f7b..f47bde6 100644 --- a/validator/corpaccount.go +++ b/validator/corpaccount.go @@ -15,5 +15,5 @@ func NewCorpAccount(corpaccount string) CorpAccount { // IsValid checks the corp account is valid. func (ca CorpAccount) IsValid() bool { caStr := strings.ToUpper(string(ca)) - return corpaccountRegex.Match([]byte(caStr)) + return corpaccountRegex.MatchString(caStr) } diff --git a/validator/idcard.go b/validator/idcard.go index 262634d..200639c 100644 --- a/validator/idcard.go +++ b/validator/idcard.go @@ -63,7 +63,7 @@ func NewIdCard(idcard string) IdCard { // IsValid checks the id card is valid. func (ic IdCard) IsValid() bool { icStr := strings.ToUpper(string(ic)) - if !idcardRegex.Match([]byte(icStr)) { + if !idcardRegex.MatchString(icStr) { return false } @@ -71,14 +71,14 @@ func (ic IdCard) IsValid() bool { checkCode := icStr[17] for index := range icStr[:17] { - if a, err := strconv.Atoi(string(icStr[index])); err == nil { - // 计算加权因子 - w := idCardIndexWeightMap[index] - // 计算加权和 - sum += a * w - } else { + a, err := strconv.Atoi(string(icStr[index])) + if err != nil { return false } + // 计算加权因子 + w := idCardIndexWeightMap[index] + // 计算加权和 + sum += a * w } // fmt.Println(string(modCheckCodeMap[sum%11]), string(checkCode)) diff --git a/validator/idcard_test.go b/validator/idcard_test.go index e40ac25..da71ba7 100644 --- a/validator/idcard_test.go +++ b/validator/idcard_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIdCard_IsValid(t *testing.T) { @@ -37,9 +38,9 @@ func TestIdCard_GetBirthday(t *testing.T) { get := NewIdCard(c.idcard) birthday, err := get.GetBirthday() if c.expectErr { - assert.EqualError(t, err, "validator: invalid idcard") + require.EqualError(t, err, "validator: invalid idcard") } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.expectBirthday, birthday.Format("2006-01-02")) } } @@ -60,9 +61,9 @@ func TestIdCard_GetGender(t *testing.T) { get := NewIdCard(c.idcard) gender, err := get.GetGender() if c.expectErr { - assert.EqualError(t, err, "validator: invalid idcard") + require.EqualError(t, err, "validator: invalid idcard") } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.expectGender, gender) } } @@ -83,9 +84,9 @@ func TestIdCard_IsMale(t *testing.T) { get := NewIdCard(c.idcard) isMale, err := get.IsMale() if c.expectErr { - assert.EqualError(t, err, "validator: invalid idcard") + require.EqualError(t, err, "validator: invalid idcard") } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.expectMale, isMale) } } @@ -106,9 +107,9 @@ func TestIdCard_IsFemale(t *testing.T) { get := NewIdCard(c.idcard) isFemale, err := get.IsFemale() if c.expectErr { - assert.EqualError(t, err, "validator: invalid idcard") + require.EqualError(t, err, "validator: invalid idcard") } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.expectFemale, isFemale) } } diff --git a/validator/uscc.go b/validator/uscc.go index 9bd0a62..86fbc78 100644 --- a/validator/uscc.go +++ b/validator/uscc.go @@ -78,7 +78,7 @@ func NewUSCC(uscc string) USCC { // IsValid checks the uscc is valid. func (uscc USCC) IsValid() bool { usccStr := strings.ToUpper(string(uscc)) - if !usccRegex.Match([]byte(usccStr)) { + if !usccRegex.MatchString(usccStr) { return false } diff --git a/validator/validator.go b/validator/validator.go index 5c11d15..9db2d46 100644 --- a/validator/validator.go +++ b/validator/validator.go @@ -178,13 +178,18 @@ func VerifyVarWithValue(field, other interface{}, tag string) error { // convertErr converts err to validation error. func convertErr(err error) error { if err != nil { - var ves validateErrors - var e *validator.InvalidValidationError - if errors.As(err, &e) { + var ( + ves validateErrors + ive *validator.InvalidValidationError + ve validator.ValidationErrors + ) + if errors.As(err, &ive) { return ves } - for _, err := range err.(validator.ValidationErrors) { - ves = append(ves, err.Translate(ti)) + if errors.As(err, &ve) { + for _, err := range ve { + ves = append(ves, err.Translate(ti)) + } } return ves @@ -225,27 +230,27 @@ func translationFunc(key string) validator.TranslationFunc { } } -// idcard id card validator. +// idcard represents the id card validator. func idcard(fl validator.FieldLevel) bool { return NewIdCard(fl.Field().String()).IsValid() } -// bankcard bank card validator. +// bankcard represents the bank card validator. func bankcard(fl validator.FieldLevel) bool { return NewBankCard(fl.Field().String()).IsValid() } -// uscc uscc validator. +// uscc represents the uscc validator. func uscc(fl validator.FieldLevel) bool { return NewUSCC(fl.Field().String()).IsValid() } -// corpaccount corp account validator. +// corpaccount represents the corp account validator. func corpaccount(fl validator.FieldLevel) bool { return NewCorpAccount(fl.Field().String()).IsValid() } -// httpmethod http method validator. +// httpmethod represents the http method validator. func httpmethod(fl validator.FieldLevel) bool { _, ok := httpMethodMap[strings.ToUpper(fl.Field().String())] return ok diff --git a/validator/validator_test.go b/validator/validator_test.go index 136e367..5c838dc 100644 --- a/validator/validator_test.go +++ b/validator/validator_test.go @@ -3,7 +3,7 @@ package validator import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestVerify(t *testing.T) { @@ -44,22 +44,18 @@ func TestVerify(t *testing.T) { } err := Verify(&user) - if assert.Error(t, err) { - t.Log(err, ParseErr(err)) - } + require.Error(t, err) + t.Log(err, ParseErr(err)) err = Verify([]*User{&user}) - if assert.Error(t, err) { - t.Log(err, ParseErr(err)) - } + require.Error(t, err) + t.Log(err, ParseErr(err)) err = VerifyVar("sliveryouqq.com", "email") - if assert.Error(t, err) { - t.Log(err, ParseErr(err)) - } + require.Error(t, err) + t.Log(err, ParseErr(err)) err = VerifyVarWithValue("abcd", "abce", "eqcsfield") - if assert.Error(t, err) { - t.Log(err, ParseErr(err)) - } + require.Error(t, err) + t.Log(err, ParseErr(err)) }