diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index d0bc2f6a..550d8d4e 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -25,7 +25,7 @@ jobs: uses: golangci/golangci-lint-action@v3 with: # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version - version: 'v1.54.2' + version: 'v1.57.2' # Optional: working directory, useful for monorepos # working-directory: somedir diff --git a/.golangci.yml b/.golangci.yml index cc8802d5..7d7fb8bf 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,7 +10,6 @@ linters: - govet - ineffassign - staticcheck - - typecheck - unused # disabled by default - asasalint @@ -19,6 +18,7 @@ linters: - bodyclose - containedctx - contextcheck + - copyloopvar - cyclop # - deadcode [deprecated] - decorder @@ -43,6 +43,7 @@ linters: - gocheckcompilerdirectives # - gochecknoglobals # globals are ok # - gochecknoinits # init() is ok + - gochecksumtype - gocognit - goconst - gocritic @@ -64,8 +65,10 @@ linters: - grouper # - ifshort [deprecated] - importas + - inamedparam - interfacebloat # - interfacer [deprecated] + - intrange # - ireturn # return interfaces are fine - lll # - loggercheck # not using these logs @@ -86,13 +89,17 @@ linters: # - nosnakecase [deprecated] - nosprintfhostport # - paralleltest # not making every test parallel + - perfsprint - prealloc - predeclared # - promlinter # not using prometheus + - protogetter - reassign - revive - rowserrcheck # - scopelint [deprecated] + - sloglint + - spancheck - sqlclosecheck # - structcheck [deprecated] - stylecheck @@ -100,6 +107,7 @@ linters: - tagliatelle - tenv # - testableexamples # no output comments are ok + - testifylint # - testpackage # _test packages are not preferred # - thelper # no need to clean up call stack for tests - tparallel @@ -183,3 +191,15 @@ issues: path: '(.+)_test\.go' linters: - forbidigo + # Does not apply for go 1.22 + - text: "G601: Implicit memory aliasing in for loop." + linters: + - gosec + # context is not needed, should be used in the wrapper function + - source: 'jhttp\.ReturnModelOr500\(func\(\) \(any, error\)' + linters: + - contextcheck + # context is not needed, should be used in the wrapper function + - source: 'rs\.runOr500\(r, func\(r \*http\.Request, tx db\.TxQs\) error' + linters: + - contextcheck diff --git a/db/pkg/db/source.go b/db/pkg/db/source.go index 584a7370..ab4a15ec 100644 --- a/db/pkg/db/source.go +++ b/db/pkg/db/source.go @@ -4,7 +4,7 @@ import ( "bufio" "context" "encoding/json" - "fmt" + "errors" "io/fs" "strings" "time" @@ -265,7 +265,7 @@ func (t TextTokenizer) TokenizedTexts(ctx context.Context, s, translation string // TokenizeTexts takes the texts and tokenizes them func (t TextTokenizer) TokenizeTexts(ctx context.Context, texts []text.Text) ([]TokenizedText, error) { if !t.Tokenizer.IsSetup() { - return nil, fmt.Errorf("TextTokenizer not set up") + return nil, errors.New("TextTokenizer not set up") } tokenizedTexts := make([]TokenizedText, len(texts)) diff --git a/db/pkg/db/source_test.go b/db/pkg/db/source_test.go index bbfea9f9..a873edbf 100644 --- a/db/pkg/db/source_test.go +++ b/db/pkg/db/source_test.go @@ -65,14 +65,14 @@ func setupParts(t *testing.T, part SourcePart, prePartListID string) []SourcePar parts := make([]SourcePart, 3) baseKey := storage.BaseKey(SourcesTable, PartsColumn, prePartListID) - for i := 0; i < len(parts); i++ { + for i := range len(parts) { parts[i] = part key := baseKey + ".PreParts[" + strconv.Itoa(i) + "].Image.txt" parts[i].Media = &SourcePartMedia{ImageKey: key} require.NoError(storageAPI.Store(key, bytes.NewReader([]byte("image"+strconv.Itoa(i))))) } - for i := 0; i < 1; i++ { + for i := range 1 { key := baseKey + ".PreParts[0].Audio.txt" parts[i].Media.AudioKey = key require.NoError(storageAPI.Store(key, bytes.NewReader([]byte("audio"+strconv.Itoa(i)+"!")))) diff --git a/db/pkg/seedkrdict/seed.go b/db/pkg/seedkrdict/seed.go index faa9d56d..4464170a 100644 --- a/db/pkg/seedkrdict/seed.go +++ b/db/pkg/seedkrdict/seed.go @@ -174,7 +174,7 @@ func (l *LexicalEntry) textVariants() (string, []string, error) { var err error if text == "" { - err = fmt.Errorf("LexicalEntry.writtenForm not found") + err = errors.New("LexicalEntry.writtenForm not found") } return text, variants, err } @@ -295,7 +295,7 @@ func (s *Sense) translation() (dictionary.Translation, error) { } return translation, nil } - return dictionary.Translation{}, fmt.Errorf("not found") + return dictionary.Translation{}, errors.New("not found") } // Equivalent represents the translation of the entry given a special language @@ -318,7 +318,7 @@ func (e *Equivalent) translation() (dictionary.Translation, error) { } } if !isEng { - return dictionary.Translation{}, fmt.Errorf("not found") + return dictionary.Translation{}, errors.New("not found") } text, explanation := "", "" @@ -333,10 +333,10 @@ func (e *Equivalent) translation() (dictionary.Translation, error) { var err error if text == "" { - err = fmt.Errorf("text is empty") + err = errors.New("text is empty") } if explanation == "" { - err = fmt.Errorf("explanation is empty") + err = errors.New("explanation is empty") } for k, v := range cleanTranslationMap { explanation = strings.ReplaceAll(explanation, k, v) diff --git a/db/pkg/seedkrdict/seed_test.go b/db/pkg/seedkrdict/seed_test.go index f68f5b01..9a0cf202 100644 --- a/db/pkg/seedkrdict/seed_test.go +++ b/db/pkg/seedkrdict/seed_test.go @@ -1,7 +1,7 @@ package seedkrdict import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -74,7 +74,7 @@ func TestIsNoTranslationsFoundError(t *testing.T) { require := require.New(t) t.Parallel() require.True(IsNoTranslationsFoundError(NoTranslationsFoundError{})) - require.False(IsNoTranslationsFoundError(fmt.Errorf("test error"))) + require.False(IsNoTranslationsFoundError(errors.New("test error"))) } func TestLexicalEntry_CreateParams(t *testing.T) { diff --git a/integrations/tokenizers/khaiii/pkg/khaiii/api.go b/integrations/tokenizers/khaiii/pkg/khaiii/api.go index f289d215..ea1b2421 100644 --- a/integrations/tokenizers/khaiii/pkg/khaiii/api.go +++ b/integrations/tokenizers/khaiii/pkg/khaiii/api.go @@ -25,6 +25,7 @@ typedef struct khaiii_word_t_ { import "C" import ( + "errors" "fmt" "unsafe" ) @@ -70,7 +71,7 @@ func (k *Khaiii) Version() string { // Open opens the training resource directory func (k *Khaiii) Open(rscDir string) error { if k.openHandle != 0 { - return fmt.Errorf("Khaiii.Open() is already open") + return errors.New("Khaiii.Open() is already open") } openHandle := open(rscDir, "{}") if openHandle == -1 { @@ -83,7 +84,7 @@ func (k *Khaiii) Open(rscDir string) error { // Analyze analyzes the input string func (k *Khaiii) Analyze(input string) ([]Word, error) { if k.openHandle <= 0 { - return nil, fmt.Errorf("Khaiii.Open() invalid for Analyze()") + return nil, errors.New("Khaiii.Open() invalid for Analyze()") } var err error diff --git a/pkg/api/pre_part_lists.go b/pkg/api/pre_part_lists.go index f55e5f1e..ba5e4c0b 100644 --- a/pkg/api/pre_part_lists.go +++ b/pkg/api/pre_part_lists.go @@ -1,6 +1,7 @@ package api import ( + "errors" "fmt" "net/http" @@ -85,7 +86,7 @@ func (rs Routes) PrePartListSign(r *http.Request, _ db.TxQs) (any, *jhttp.HTTPEr func (rs Routes) PrePartListGet(r *http.Request, _ db.TxQs) (any, *jhttp.HTTPError) { prePartListID := chi.URLParam(r, "id") if prePartListID == "" { - return nil, jhttp.Error(http.StatusNotFound, fmt.Errorf("id not found")) + return nil, jhttp.Error(http.StatusNotFound, errors.New("id not found")) } prePartList := db.PrePartListURL{} err := rs.Storage.DBStorage.SignGetTree(db.SourcesTable, db.PartsColumn, prePartListID, &prePartList) diff --git a/pkg/api/pre_part_lists_test.go b/pkg/api/pre_part_lists_test.go index 01089afa..d1376f6f 100644 --- a/pkg/api/pre_part_lists_test.go +++ b/pkg/api/pre_part_lists_test.go @@ -119,7 +119,7 @@ func TestRoutes_PrePartListGet(t *testing.T) { func setupPreParts(t *testing.T, id string) { baseKey := storage.BaseKey(db.SourcesTable, db.PartsColumn, id) - for i := 0; i < 2; i++ { + for i := range 2 { err := routes.Storage.Storer.Store(baseKey+".PreParts["+strconv.Itoa(i)+"].Image.txt", bytes.NewReader([]byte("image"+strconv.Itoa(i)))) require.NoError(t, err) } diff --git a/pkg/api/sources.go b/pkg/api/sources.go index a0997cf6..78117354 100644 --- a/pkg/api/sources.go +++ b/pkg/api/sources.go @@ -2,7 +2,7 @@ package api import ( "context" - "fmt" + "errors" "net/http" "strings" @@ -180,7 +180,7 @@ func (rs Routes) requestPartsToDBParts(ctx context.Context, reqParts []PartCreat parts = append(parts, sourcePart) } if len(parts) == 0 { - return nil, jhttp.Error(http.StatusUnprocessableEntity, fmt.Errorf("no parts found with text set")) + return nil, jhttp.Error(http.StatusUnprocessableEntity, errors.New("no parts found with text set")) } return parts, nil } diff --git a/pkg/api/sources_test.go b/pkg/api/sources_test.go index 3088f39c..ef6907c9 100644 --- a/pkg/api/sources_test.go +++ b/pkg/api/sources_test.go @@ -2,7 +2,7 @@ package api import ( "bytes" - "fmt" + "errors" "net/http" "strconv" "strings" @@ -168,7 +168,7 @@ func TestRoutes_SourceDestroy(t *testing.T) { } _, err := txQs.SourceGet(txQs.Ctx(), created.ID) - require.Equal(fmt.Errorf("sql: no rows in result set"), err) + require.Equal(errors.New("sql: no rows in result set"), err) }) } } @@ -185,7 +185,7 @@ func setupSourceCreateMediaWithInfo(t *testing.T, prePartListID string) { func setupSourceCreateMedia(t *testing.T, prePartListID string) { baseKey := storage.BaseKey(db.SourcesTable, db.PartsColumn, prePartListID) - for i := 0; i < 3; i++ { + for i := range 3 { err := routes.Storage.Storer.Store(baseKey+".PreParts["+strconv.Itoa(i)+"].Image.txt", bytes.NewReader([]byte("image"+strconv.Itoa(i)))) require.NoError(t, err) } @@ -206,11 +206,11 @@ func sourceCreateRequestParts(t *testing.T, caseName, testName string, partCount case "51_parts": partsLen := 51 parts = make([]PartCreateMultiRequestPart, partsLen) - for i := 0; i < partsLen; i++ { + for i := range partsLen { parts[i] = PartCreateMultiRequestPart{} } default: - for i := 0; i < partCount; i++ { + for i := range partCount { parts[i] = sourceCreateRequestPartFromFile(t, testName, caseName+strconv.Itoa(i)+".txt") } } diff --git a/pkg/dictionary/koreanbasic/koreanbasic_test.go b/pkg/dictionary/koreanbasic/koreanbasic_test.go index 7344515c..5ee76f8b 100644 --- a/pkg/dictionary/koreanbasic/koreanbasic_test.go +++ b/pkg/dictionary/koreanbasic/koreanbasic_test.go @@ -80,7 +80,7 @@ func TestPartOfSpeechToAPIIntMatch(t *testing.T) { func TestMergePosMap(t *testing.T) { require := require.New(t) - require.Equal(lang.PartOfSpeechCount, len(mergePosMap)) + require.Len(mergePosMap, lang.PartOfSpeechCount) uniquePosMapValues := map[lang.PartOfSpeech]bool{} for _, v := range partOfSpeechMap { diff --git a/pkg/dictionary/krdict/krdict_test.go b/pkg/dictionary/krdict/krdict_test.go index 9e1812a4..5d3e1c37 100644 --- a/pkg/dictionary/krdict/krdict_test.go +++ b/pkg/dictionary/krdict/krdict_test.go @@ -30,7 +30,7 @@ func TestKrDict_Search(t *testing.T) { func TestMergePosMap(t *testing.T) { require := require.New(t) - require.Equal(lang.PartOfSpeechCount, len(mergePosMap)) + require.Len(mergePosMap, lang.PartOfSpeechCount) posMap := seedkrdict.PartOfSpeechMap() uniquePosMapValues := map[lang.PartOfSpeech]bool{} diff --git a/pkg/extractor/extractor_test.go b/pkg/extractor/extractor_test.go index 8b2246df..8d76bb7c 100644 --- a/pkg/extractor/extractor_test.go +++ b/pkg/extractor/extractor_test.go @@ -2,7 +2,7 @@ package extractor_test import ( "encoding/json" - "fmt" + "errors" "io" "os" "path" @@ -45,8 +45,8 @@ func TestExtractor_Extract(t *testing.T) { err error }{ {name: "basic", s: extractortest.VerifyString}, - {name: "skip_extract", s: extractortest.SkipExtractString, err: fmt.Errorf("no filenames that match extensions extracted: .jpg, .png")}, - {name: "no_verify", s: "fail", err: fmt.Errorf("string does not match factory source: fail")}, + {name: "skip_extract", s: extractortest.SkipExtractString, err: errors.New("no filenames that match extensions extracted: .jpg, .png")}, + {name: "no_verify", s: "fail", err: errors.New("string does not match factory source: fail")}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/extractor/extractortest/extractortest.go b/pkg/extractor/extractortest/extractortest.go index e75e37af..aac3ead0 100644 --- a/pkg/extractor/extractortest/extractortest.go +++ b/pkg/extractor/extractortest/extractortest.go @@ -2,7 +2,7 @@ package extractortest import ( - "fmt" + "errors" "os" "path/filepath" @@ -56,7 +56,7 @@ func (t Source) ExtractToDir(cacheDir string) error { return err } if len(items) != 0 { - return fmt.Errorf("extracting to non-empty cacheDir") + return errors.New("extracting to non-empty cacheDir") } return filepath.Walk(t.fixturePath, func(path string, info os.FileInfo, err error) error { if err != nil { diff --git a/pkg/extractor/instagram/instagram.go b/pkg/extractor/instagram/instagram.go index 25829c6f..07d2d949 100644 --- a/pkg/extractor/instagram/instagram.go +++ b/pkg/extractor/instagram/instagram.go @@ -3,6 +3,7 @@ package instagram import ( "encoding/json" + "errors" "fmt" "net/url" "os" @@ -99,7 +100,7 @@ func numberPadFilenames(cacheDir string) error { for _, filename := range filenames { parts := strings.Split(filename, "_") if len(parts) < 2 { - return fmt.Errorf("file found with no underscore") + return errors.New("file found with no underscore") } numberPart := strings.Split(parts[len(parts)-1], ".")[0] number, err := strconv.Atoi(numberPart) diff --git a/pkg/extractor/instagram/instagram_test.go b/pkg/extractor/instagram/instagram_test.go index 293b03b3..b4c87dcf 100644 --- a/pkg/extractor/instagram/instagram_test.go +++ b/pkg/extractor/instagram/instagram_test.go @@ -1,7 +1,7 @@ package instagram import ( - "fmt" + "errors" "os" "path" "path/filepath" @@ -84,7 +84,7 @@ func TestPost_ExtractToDir(t *testing.T) { url string err error }{ - {name: "broken", url: "https://waka.com", err: fmt.Errorf("url is not verified for instagram: https://waka.com")}, + {name: "broken", url: "https://waka.com", err: errors.New("url is not verified for instagram: https://waka.com")}, {name: "fake", url: testURL}, } for _, tc := range testCases { diff --git a/pkg/firm/error.go b/pkg/firm/error.go index 33eaa0d8..0793f163 100644 --- a/pkg/firm/error.go +++ b/pkg/firm/error.go @@ -100,7 +100,7 @@ type ErrorKey string // RootTypeName returns the type name of the key func (e ErrorKey) RootTypeName() string { suffix := string(e) - for i := 0; i < 2; i++ { + for range 2 { index := strings.Index(suffix, keySeparator) if index == -1 { return "" diff --git a/pkg/firm/registry_test.go b/pkg/firm/registry_test.go index ac8967ab..34fe4f9f 100644 --- a/pkg/firm/registry_test.go +++ b/pkg/firm/registry_test.go @@ -1,7 +1,7 @@ package firm import ( - "fmt" + "errors" "reflect" "strings" "testing" @@ -48,7 +48,7 @@ func TestRegistry_RegisterType(t *testing.T) { require.Equal(typeToValidator, registry.typeToValidator) require.Equal(map[reflect.Type][]*[]Rule{}, registry.unregisteredTypeRefs) - require.Equal(fmt.Errorf("RegisterType() with type firm.registryParent already exists"), + require.Equal(errors.New("RegisterType() with type firm.registryParent already exists"), registry.RegisterType(NewDefinition[registryParent]().ValidatesTopLevel(presentRule{}))) } diff --git a/pkg/firm/rule/attr.go b/pkg/firm/rule/attr.go index c1bd65a5..b2a492bb 100644 --- a/pkg/firm/rule/attr.go +++ b/pkg/firm/rule/attr.go @@ -48,8 +48,7 @@ func (a Attr) errorMap(original firm.ErrorMap) firm.ErrorMap { } errorMap := firm.ErrorMap{} - for k, v := range original { - err := v + for k, err := range original { if err.TemplateFields == nil { err.TemplateFields = map[string]string{} } diff --git a/pkg/firm/rule/attr_test.go b/pkg/firm/rule/attr_test.go index 9ba882f0..d92a3d7c 100644 --- a/pkg/firm/rule/attr_test.go +++ b/pkg/firm/rule/attr_test.go @@ -33,8 +33,7 @@ func TestAttr_ValidateValue(t *testing.T) { attribute = attr.Len{} } var expected firm.ErrorMap - for k, v := range tc.errorMap { - err := v + for k, err := range tc.errorMap { if err.TemplateFields == nil { err.TemplateFields = map[string]string{} } diff --git a/pkg/firm/rule/not.go b/pkg/firm/rule/not.go index 610b4359..7e260593 100644 --- a/pkg/firm/rule/not.go +++ b/pkg/firm/rule/not.go @@ -28,8 +28,7 @@ func (n Not) ErrorMap() firm.ErrorMap { } errorMap := firm.ErrorMap{} - for k, v := range original { - err := v + for k, err := range original { err.Template += "--Not" errorMap["Not"+k] = err } diff --git a/pkg/firm/rule/not_test.go b/pkg/firm/rule/not_test.go index a43e56b9..3099b969 100644 --- a/pkg/firm/rule/not_test.go +++ b/pkg/firm/rule/not_test.go @@ -28,8 +28,7 @@ func TestNot_ValidateValue(t *testing.T) { require := require.New(t) var expected firm.ErrorMap - for k, v := range tc.errorMap { - err := v + for k, err := range tc.errorMap { if expected == nil { expected = firm.ErrorMap{} } diff --git a/pkg/firm/validator.go b/pkg/firm/validator.go index 1af916af..428d1922 100644 --- a/pkg/firm/validator.go +++ b/pkg/firm/validator.go @@ -1,6 +1,7 @@ package firm import ( + "errors" "fmt" "reflect" "strconv" @@ -21,7 +22,7 @@ func NewStruct[T any](ruleMap RuleMap) (Struct[T], error) { // NewStructAny returns a new StructAny func NewStructAny(typ reflect.Type, ruleMap RuleMap) (StructAny, error) { if typ == nil { - return StructAny{}, fmt.Errorf("type, nil, is not a Struct") + return StructAny{}, errors.New("type, nil, is not a Struct") } if typ.Kind() != reflect.Struct { return StructAny{}, fmt.Errorf("type, %v, is not a Struct", typ.String()) @@ -40,9 +41,8 @@ func NewStructAny(typ reflect.Type, ruleMap RuleMap) (StructAny, error) { } rm := map[string]*[]Rule{} - for k, v := range ruleMap { - rules := v - rm[k] = &rules + for k, rules := range ruleMap { + rm[k] = &rules //nolint:exportloopref // want to pass the pointer } return StructAny{typ: typ, ruleMap: rm}, nil } @@ -109,7 +109,7 @@ func NewSlice[T []U, U any](elementRules ...Rule) (Slice[T, U], error) { // NewSliceAny returns the Slice validator without generics func NewSliceAny(typ reflect.Type, elementRules ...Rule) (SliceAny, error) { if typ == nil { - return SliceAny{}, fmt.Errorf("type, nil, is not a Slice or Array") + return SliceAny{}, errors.New("type, nil, is not a Slice or Array") } kind := typ.Kind() if kind != reflect.Slice && kind != reflect.Array { @@ -147,7 +147,7 @@ func (s SliceAny) ValidateValue(value reflect.Value) ErrorMap { return validateV // ValidateMerge validates the data value, also doing a merge with the errorMap (assumes TypeCheck is called) func (s SliceAny) ValidateMerge(value reflect.Value, key string, errorMap ErrorMap) { - for i := 0; i < value.Len(); i++ { + for i := range value.Len() { // no control over types, so indirect v := indirect(value.Index(i)) validateMerge(v, joinKeys(key, "["+strconv.Itoa(i)+"]"), errorMap, s.elementRules) @@ -177,7 +177,7 @@ func NewValue[T any](rules ...Rule) (Value[T], error) { // NewValueAny returns a ValueAny func NewValueAny(typ reflect.Type, rules ...Rule) (ValueAny, error) { if typ == nil { - return ValueAny{}, fmt.Errorf("type is nil, not recommended") + return ValueAny{}, errors.New("type is nil, not recommended") } if typ.Kind() == reflect.Pointer { return ValueAny{}, fmt.Errorf("type, %v, is a Pointer, not recommended", typ.String()) diff --git a/pkg/firm/validator_pkg_test.go b/pkg/firm/validator_pkg_test.go index 6b8ed89c..2dddaf5c 100644 --- a/pkg/firm/validator_pkg_test.go +++ b/pkg/firm/validator_pkg_test.go @@ -49,7 +49,7 @@ func TestNewStructPkg(t *testing.T) { validator, err := firm.NewStruct[nonExport](tc.ruleMap) require.NoError(err) - require.True(validator.ValidateAny(notEmpty) == nil) + require.Nil(validator.ValidateAny(notEmpty)) require.Equal(tc.failErr, validator.ValidateAny(nonExport{})) }) } diff --git a/pkg/firm/validator_test.go b/pkg/firm/validator_test.go index 16bb03e7..c06abb69 100644 --- a/pkg/firm/validator_test.go +++ b/pkg/firm/validator_test.go @@ -1,6 +1,7 @@ package firm import ( + "errors" "fmt" "reflect" "testing" @@ -469,9 +470,9 @@ func TestNewStructAny(t *testing.T) { }{ {name: "normal", data: Child{}, ruleMap: RuleMap{"Validates": {presentRule{}}}}, {name: "non_exported_field", data: Child{}, ruleMap: RuleMap{"private": {presentRule{}}}}, - {name: "nil_type", data: nil, err: fmt.Errorf("type, nil, is not a Struct")}, - {name: "pointer", data: &Child{}, err: fmt.Errorf("type, *firm.Child, is not a Struct")}, - {name: "non_matching_field", data: Child{}, ruleMap: RuleMap{"No": {presentRule{}}}, err: fmt.Errorf("field, No, not found in type: firm.Child")}, + {name: "nil_type", data: nil, err: errors.New("type, nil, is not a Struct")}, + {name: "pointer", data: &Child{}, err: errors.New("type, *firm.Child, is not a Struct")}, + {name: "non_matching_field", data: Child{}, ruleMap: RuleMap{"No": {presentRule{}}}, err: errors.New("field, No, not found in type: firm.Child")}, {name: "no_matching_rule", data: Child{}, ruleMap: RuleMap{"Validates": {noMatchingRule}}, err: fmt.Errorf("field, Validates, in firm.Child: %w", noMatchingRule.TypeCheck(reflect.TypeOf("")))}, } @@ -605,9 +606,9 @@ func TestNewSliceAny(t *testing.T) { err error }{ {name: "normal", data: []Child{}, rules: []Rule{presentRule{}}}, - {name: "nil_type", data: nil, err: fmt.Errorf("type, nil, is not a Slice or Array")}, - {name: "pointer", data: &[]Child{}, err: fmt.Errorf("type, *[]firm.Child, is not a Slice or Array")}, - {name: "not_slice", data: Child{}, err: fmt.Errorf("type, firm.Child, is not a Slice or Array")}, + {name: "nil_type", data: nil, err: errors.New("type, nil, is not a Slice or Array")}, + {name: "pointer", data: &[]Child{}, err: errors.New("type, *[]firm.Child, is not a Slice or Array")}, + {name: "not_slice", data: Child{}, err: errors.New("type, firm.Child, is not a Slice or Array")}, {name: "no_matching_rule", data: []Child{}, rules: []Rule{noMatchingRule}, err: fmt.Errorf("element type: %w", noMatchingRule.TypeCheck(reflect.TypeOf(Child{})))}, } @@ -701,8 +702,8 @@ func TestNewValueAny(t *testing.T) { err error }{ {name: "normal", data: i, rules: []Rule{intRule}}, - {name: "int_pointer", data: &i, err: fmt.Errorf("type, *int, is a Pointer, not recommended")}, - {name: "nil_type", data: nil, err: fmt.Errorf("type is nil, not recommended")}, + {name: "int_pointer", data: &i, err: errors.New("type, *int, is a Pointer, not recommended")}, + {name: "nil_type", data: nil, err: errors.New("type is nil, not recommended")}, {name: "not_int", data: []int{}, rules: []Rule{intRule}, err: intRule.TypeCheck(reflect.TypeOf([]int{}))}, } for _, tc := range tcs { @@ -844,7 +845,6 @@ func TestRuleValidator_ValidateAll(t *testing.T) { {name: "zero", data: 0, err: presentRuleError("")}, } for _, tc := range tcs { - tc := tc t.Run(tc.name, func(t *testing.T) { testValidateAll(t, validator, tc.data, tc.err, presentRuleKey) testValidateAll(t, validator, &tc.data, nil) diff --git a/pkg/lang/lang_test.go b/pkg/lang/lang_test.go index 9678ed3f..d9d79fb5 100644 --- a/pkg/lang/lang_test.go +++ b/pkg/lang/lang_test.go @@ -1,7 +1,7 @@ package lang import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -23,18 +23,17 @@ func TestToCommonLevel(t *testing.T) { require.Equal(CommonLevelCommon, commonLevel) commonLevel, err = ToCommonLevel(-1) - require.Equal(fmt.Errorf("common level not within range 0 to 3: -1"), err) + require.Equal(errors.New("common level not within range 0 to 3: -1"), err) require.Equal(CommonLevelUnique, commonLevel) commonLevel, err = ToCommonLevel(4) - require.Equal(fmt.Errorf("common level not within range 0 to 3: 4"), err) + require.Equal(errors.New("common level not within range 0 to 3: 4"), err) require.Equal(CommonLevelUnique, commonLevel) } func TestPartOfSpeechTypes(t *testing.T) { require := require.New(t) - got := PartOfSpeechTypes() - require.Equal(PartOfSpeechCount, len(got)) + require.Len(PartOfSpeechTypes(), PartOfSpeechCount) } func TestToPartOfSpeech(t *testing.T) { @@ -49,6 +48,6 @@ func TestToPartOfSpeech(t *testing.T) { require.Equal(PartOfSpeechEmpty, pos) pos, err = ToPartOfSpeech("NOT A POS") - require.Equal(fmt.Errorf("pos not matching lang.PartOfSpeech: NOT A POS"), err) + require.Equal(errors.New("pos not matching lang.PartOfSpeech: NOT A POS"), err) require.Equal(PartOfSpeechEmpty, pos) } diff --git a/pkg/storage/db_storage_test.go b/pkg/storage/db_storage_test.go index 96ea7e8b..cafc9217 100644 --- a/pkg/storage/db_storage_test.go +++ b/pkg/storage/db_storage_test.go @@ -1,7 +1,7 @@ package storage import ( - "fmt" + "errors" "io/fs" "os" "path" @@ -100,7 +100,7 @@ func TestDBStorage_SignPutTree(t *testing.T) { Message: "srcTree empty slice or array given at sources/parts/123e4567-e89b-12d3-a456-426614174000/parts.PreParts"}}, {name: "invalid", req: PrePartListSignRequest{PreParts: []PrePartSignRequest{{ImageExt: ".waka"}}}, err: InvalidInputError{Message: "invalid extension, .waka, at sources/parts/123e4567-e89b-12d3-a456-426614174000/parts.PreParts[0].Image"}}, - {name: "no_pointer", err: fmt.Errorf("storage.PrePartListSignResponse is not a pointer")}, + {name: "no_pointer", err: errors.New("storage.PrePartListSignResponse is not a pointer")}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { @@ -158,7 +158,7 @@ func TestDBStorage_PutTree(t *testing.T) { err: InvalidInputError{Message: "srcTree empty slice or array given at sources/parts/123e4567-e89b-12d3-a456-426614174000/parts.PreParts"}}, {name: "invalid", err: InvalidInputError{Message: "invalid extension, .txt, at sources/parts/123e4567-e89b-12d3-a456-426614174000/parts.PreParts[0].Image"}}, - {name: "no_pointer", err: fmt.Errorf("storage.PrePartListKeyTree is not a pointer")}, + {name: "no_pointer", err: errors.New("storage.PrePartListKeyTree is not a pointer")}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { @@ -195,7 +195,7 @@ func fileTreeParts(t *testing.T, caseName, testName string, partCount int) []Pre case "empty_parts": parts = []PrePartFileTree{} default: - for i := 0; i < partCount; i++ { + for i := range partCount { parts[i] = fileTreePartsFromFile(t, testName, caseName+strconv.Itoa(i)) } } @@ -274,8 +274,8 @@ func TestDBStorage_SignGetTree(t *testing.T) { err error }{ {name: "basic", signedTree: &prePartList}, - {name: "non_pointer", signedTree: prePartList, err: fmt.Errorf("storage.PrePartList is not a pointer")}, - {name: "nil", signedTree: nil, err: fmt.Errorf("passed nil as settable obj")}, + {name: "non_pointer", signedTree: prePartList, err: errors.New("storage.PrePartList is not a pointer")}, + {name: "nil", signedTree: nil, err: errors.New("passed nil as settable obj")}, {name: "bad_id", signedTree: &prePartList, id: "bad_id", err: NotFoundError{ID: "bad_id", IDPath: "sources/parts/bad_id"}}, } for _, tc := range testCases { @@ -313,7 +313,7 @@ func TestDBStorage_SignGetTreeFromKeyTree(t *testing.T) { fixture.CompareReadOrUpdateJSON(t, testName, signedTree) err = newTestDBStorage().SignGetTreeFromKeyTree(media, signedTree) - require.Equal(fmt.Errorf("signedTree, storage.SourcePartMediaResponse, is not a pointer"), err) + require.Equal(errors.New("signedTree, storage.SourcePartMediaResponse, is not a pointer"), err) } func TestDBStorage_KeyTreeFromSignGetTree(t *testing.T) { @@ -329,5 +329,5 @@ func TestDBStorage_KeyTreeFromSignGetTree(t *testing.T) { fixture.CompareReadOrUpdateJSON(t, testName, media) err = newTestDBStorage().KeyTreeFromSignGetTree(signedTree, media) - require.Equal(fmt.Errorf("keyTree, storage.SourcePartMedia, is not a pointer"), err) + require.Equal(errors.New("keyTree, storage.SourcePartMedia, is not a pointer"), err) } diff --git a/pkg/storage/errors_test.go b/pkg/storage/errors_test.go index f318a5bd..1b9aed0a 100644 --- a/pkg/storage/errors_test.go +++ b/pkg/storage/errors_test.go @@ -1,7 +1,7 @@ package storage import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -10,11 +10,11 @@ import ( func TestIsNotFoundError(t *testing.T) { require := require.New(t) require.True(IsNotFoundError(NotFoundError{})) - require.False(IsNotFoundError(fmt.Errorf("test error"))) + require.False(IsNotFoundError(errors.New("test error"))) } func TestIsInvalidInputError(t *testing.T) { require := require.New(t) require.True(IsInvalidInputError(InvalidInputError{})) - require.False(IsInvalidInputError(fmt.Errorf("test error"))) + require.False(IsInvalidInputError(errors.New("test error"))) } diff --git a/pkg/storage/localstore/localstore.go b/pkg/storage/localstore/localstore.go index a5281903..868d7be8 100644 --- a/pkg/storage/localstore/localstore.go +++ b/pkg/storage/localstore/localstore.go @@ -57,7 +57,7 @@ func (a API) SignPut(key string) (storage.PreSignedHTTPRequest, error) { func (a API) SignGet(key string) (string, error) { p := a.keyPath(key) if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) { - return "", fmt.Errorf("file does not exist") + return "", errors.New("file does not exist") } return a.keyURL(key), nil } @@ -191,7 +191,7 @@ func (a AESEncryptor) Decrypt(ciphertext string) (string, error) { return "", err } if len(cipherDecoded) < aes.BlockSize { - return "", fmt.Errorf("ciphertext too short") + return "", errors.New("ciphertext too short") } iv := cipherDecoded[:aes.BlockSize] diff --git a/pkg/storage/localstore/localstore_test.go b/pkg/storage/localstore/localstore_test.go index 3a8f4b83..f5789bc5 100644 --- a/pkg/storage/localstore/localstore_test.go +++ b/pkg/storage/localstore/localstore_test.go @@ -3,7 +3,7 @@ package localstore import ( "bytes" "encoding/hex" - "fmt" + "errors" "io" "net/url" "os" @@ -65,7 +65,7 @@ func TestAPI_SignGet(t *testing.T) { api := newAPIWithT(t) u, err := api.SignGet(key) - require.Equal(fmt.Errorf("file does not exist"), err) + require.Equal(errors.New("file does not exist"), err) require.Empty(u) require.NoError(api.Store(key, bytes.NewReader([]byte("test_me")))) @@ -106,7 +106,7 @@ func TestAPI_ListKeys(t *testing.T) { api := newAPIWithT(t) keys, err := api.ListKeys(prefix) require.NoError(err) - require.Len(keys, 0) + require.Empty(keys) key1 := path.Join(prefix, testKeyFile) key2 := path.Join(prefix, "again_me.txt") diff --git a/pkg/storage/tree.go b/pkg/storage/tree.go index f25ca817..4d06ae56 100644 --- a/pkg/storage/tree.go +++ b/pkg/storage/tree.go @@ -1,6 +1,7 @@ package storage import ( + "errors" "fmt" "io/fs" "path" @@ -132,7 +133,7 @@ func putTreeSlice(nameToValidExts SignPutNameToValidExts, srcTree, destTree refl } destTree.Set(reflect.MakeSlice(destTree.Type(), srcTree.Len(), srcTree.Len())) - for i := 0; i < srcTree.Len(); i++ { + for i := range srcTree.Len() { if err := treeFunc(nameToValidExts, srcTree.Index(i), destTree.Index(i), current+"["+strconv.Itoa(i)+"]"); err != nil { return err } @@ -148,9 +149,9 @@ func putTreeStruct(nameToValidExts SignPutNameToValidExts, srcTree, destTree ref if !destTree.IsValid() || destTree.Kind() != reflect.Struct { return fmt.Errorf("destTree not valid Struct at %v", current) } - for i := 0; i < srcTree.NumField(); i++ { + for i := range srcTree.NumField() { shortName := srcTree.Type().Field(i).Name - requestName := shortName + requestName := shortName //nolint:copyloopvar // an actual working copy if strings.HasSuffix(shortName, srcSuffix) { shortName = shortName[:len(shortName)-len(srcSuffix)] requestName = shortName + destSuffix @@ -353,7 +354,7 @@ func mapTreeFromValue(current reflect.Value, fieldSuffix string) (any, error) { return current.String(), nil case reflect.Slice, reflect.Array: treeObjSlice := make([]any, current.Len()) - for i := 0; i < current.Len(); i++ { + for i := range current.Len() { value, err := mapTreeFromValue(current.Index(i), fieldSuffix) if err != nil { return nil, err @@ -363,7 +364,7 @@ func mapTreeFromValue(current reflect.Value, fieldSuffix string) (any, error) { return treeObjSlice, nil case reflect.Struct: treeObjMap := map[string]any{} - for i := 0; i < current.NumField(); i++ { + for i := range current.NumField() { fieldType := current.Type().Field(i) if !fieldType.IsExported() { continue @@ -469,7 +470,7 @@ const IDFieldName = "ID" func setID(id string, obj any) (reflect.Value, error) { value := reflect.ValueOf(obj) if !value.IsValid() { - return reflect.Value{}, fmt.Errorf("passed nil as settable obj") + return reflect.Value{}, errors.New("passed nil as settable obj") } if value.Kind() != reflect.Pointer { return reflect.Value{}, fmt.Errorf("%v is not a pointer", value.Type().String()) diff --git a/pkg/storage/tree_test.go b/pkg/storage/tree_test.go index f92ed5e1..25abf985 100644 --- a/pkg/storage/tree_test.go +++ b/pkg/storage/tree_test.go @@ -2,6 +2,7 @@ package storage import ( "encoding/json" + "errors" "fmt" "path" "reflect" @@ -88,16 +89,16 @@ func TestTreeFromKeys(t *testing.T) { {name: "complex", keys: complexKeys}, {name: "string_vs_struct", keys: stringVSStructKeys, err: fmt.Errorf("at key: column_name.Key1.jpg, %w", - fmt.Errorf("unmatched types string and map[string]interface {} at: Key1"))}, + errors.New("unmatched types string and map[string]interface {} at: Key1"))}, {name: "string_vs_alpha_struct", keys: stringVSAlphaStructKeys, err: fmt.Errorf("at key: column_name.Key1.zipToAlphaEndToJpg.jpg, %w", - fmt.Errorf("expected Map at: zipToAlphaEndToJpg"))}, + errors.New("expected Map at: zipToAlphaEndToJpg"))}, {name: "string_vs_array", keys: stringVSArrayKeys, err: fmt.Errorf("at key: column_name.Key1[0].jpg, %w", - fmt.Errorf("expected Slice at: 0"))}, + errors.New("expected Slice at: 0"))}, {name: "array_vs_struct", keys: arrayVsStructKeys, err: fmt.Errorf("at key: column_name.Key1[0].jpg, %w", - fmt.Errorf("expected Slice at: 0"))}, + errors.New("expected Slice at: 0"))}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/text/subs_test.go b/pkg/text/subs_test.go index b687d8cf..3d0366b6 100644 --- a/pkg/text/subs_test.go +++ b/pkg/text/subs_test.go @@ -27,7 +27,7 @@ func TestParseSubtitles(t *testing.T) { fixture.JoinTestData(testName, tc.name+"_source.vtt"), fixture.JoinTestData(testName, tc.name+"_translation.vtt"), ) - require.Nil(err) + require.NoError(err) bytes := fixture.JSON(t, texts) if tc.name == "match" { diff --git a/pkg/text/text.go b/pkg/text/text.go index 1ac051d9..fc57486d 100644 --- a/pkg/text/text.go +++ b/pkg/text/text.go @@ -2,6 +2,7 @@ package text import ( + "errors" "fmt" "regexp" "strings" @@ -110,8 +111,8 @@ const ( Unknown ) -var errExtraTextLine = fmt.Errorf("there are more text lines than translation lines") -var errExtraTranslationLine = fmt.Errorf("there are more translation lines than text lines") +var errExtraTextLine = errors.New("there are more text lines than translation lines") +var errExtraTranslationLine = errors.New("there are more translation lines than text lines") // Texts returns an array of Text from the given string func (p Parser) Texts(s, translation string) ([]Text, error) { @@ -243,7 +244,7 @@ func splitClean(s string) []string { func CleanSpeaker(texts []Text) []Text { cleanedTexts := make([]Text, len(texts)) for i, t := range texts { - dup := t + dup := t //nolint:copyloopvar // want a dupe dup.Text = CleanSpeakerString(t.Text) dup.Translation = CleanSpeakerString(t.Translation) cleanedTexts[i] = dup diff --git a/pkg/text/text_test.go b/pkg/text/text_test.go index fcdf9dad..996106ed 100644 --- a/pkg/text/text_test.go +++ b/pkg/text/text_test.go @@ -1,7 +1,7 @@ package text import ( - "fmt" + "errors" "strings" "testing" @@ -13,7 +13,7 @@ import ( func TestLanguagesMatch(t *testing.T) { require := require.New(t) - require.Equal(int(Zulu)+1, len(lingua.AllLanguages())) + require.Len(lingua.AllLanguages(), int(Zulu)+1) require.Equal(int(Unknown), int(lingua.Unknown)) } @@ -34,7 +34,7 @@ func TestParser_Texts(t *testing.T) { {name: "split_extra_text", err: errExtraTextLine}, {name: "split_extra_translation", err: errExtraTranslationLine}, {name: "split_1_line_extra_translation", err: errExtraTranslationLine}, - {name: "weave_extra_translation", err: fmt.Errorf("translation exists for two consecutive non-empty lines at 7: my extra line")}, + {name: "weave_extra_translation", err: errors.New("translation exists for two consecutive non-empty lines at 7: my extra line")}, } parser := NewParser(Korean, English) diff --git a/pkg/tokenizer/server/server.go b/pkg/tokenizer/server/server.go index b8557c85..be45f059 100644 --- a/pkg/tokenizer/server/server.go +++ b/pkg/tokenizer/server/server.go @@ -207,7 +207,7 @@ func (s *CmdTokenizerServer) StopAndWait() error { time.Sleep(sleepTime) } if s.isRunning { - return fmt.Errorf("CmdServer running after timeout Stop()") + return errors.New("CmdServer running after timeout Stop()") } return nil } @@ -215,7 +215,7 @@ func (s *CmdTokenizerServer) StopAndWait() error { // ForceStop forces the server to stop via kill func (s *CmdTokenizerServer) ForceStop() error { if s.isRunning { - return fmt.Errorf("will not ForceStop() while IsRunning()") + return errors.New("will not ForceStop() while IsRunning()") } s.cancel() return nil diff --git a/pkg/tokenizer/server/serverimpl/serverimpl.go b/pkg/tokenizer/server/serverimpl/serverimpl.go index 1079b0fa..7af0f2aa 100644 --- a/pkg/tokenizer/server/serverimpl/serverimpl.go +++ b/pkg/tokenizer/server/serverimpl/serverimpl.go @@ -5,6 +5,7 @@ import ( "bufio" "context" "encoding/json" + "errors" "flag" "fmt" "io" @@ -156,7 +157,7 @@ func handleHealthzFunc(w http.ResponseWriter, r *http.Request) { func (s *ServerImpl) handleTokenize(r *http.Request) (any, *jhttp.HTTPError) { if r.Method != http.MethodPost { - return nil, jhttp.Error(http.StatusMethodNotAllowed, fmt.Errorf("405 Method Not Allowed")) + return nil, jhttp.Error(http.StatusMethodNotAllowed, errors.New("405 Method Not Allowed")) } req := &server.TokenizeRequest{} diff --git a/pkg/util/chiutil/chiutil.go b/pkg/util/chiutil/chiutil.go index dd46fbd1..2420303f 100644 --- a/pkg/util/chiutil/chiutil.go +++ b/pkg/util/chiutil/chiutil.go @@ -2,7 +2,7 @@ package chiutil import ( - "fmt" + "errors" "net/http" "strconv" @@ -13,7 +13,7 @@ import ( func ParamID(r *http.Request, key string) (int64, error) { param := chi.URLParam(r, key) if param == "" { - return 0, fmt.Errorf(key + " not found") + return 0, errors.New(key + " not found") } id, err := strconv.ParseInt(param, 10, 64) if err != nil { diff --git a/pkg/util/httptyped/httptyped.go b/pkg/util/httptyped/httptyped.go index 9bf3f785..ce146319 100644 --- a/pkg/util/httptyped/httptyped.go +++ b/pkg/util/httptyped/httptyped.go @@ -2,6 +2,7 @@ package httptyped import ( + "errors" "fmt" "reflect" "unicode" @@ -122,7 +123,7 @@ func structureMap(typ reflect.Type, m map[string]map[string]string, handledTypeM m[typ.String()] = currentTypeMap handledTypeMap[typ] = true - for i := 0; i < typ.NumField(); i++ { + for i := range typ.NumField() { field := typ.Field(i) if unicode.IsLower([]rune(field.Name)[0]) { continue @@ -148,7 +149,7 @@ type Preparable interface { PrepareSerialize() } -var errModelNil = fmt.Errorf("httptyped model is nil") +var errModelNil = errors.New("httptyped model is nil") // PrepareModel checks if the type exists and prepares the model for serializing func PrepareModel(model any) error { @@ -165,7 +166,7 @@ func PrepareModel(model any) error { } val := reflect.ValueOf(model) if val.Kind() == reflect.Slice || val.Kind() == reflect.Array { - for i := 0; i < val.Len(); i++ { + for i := range val.Len() { elem := val.Index(i).Interface() preparable, ok := elem.(Preparable) if !ok { diff --git a/pkg/util/httptyped/httptyped_test.go b/pkg/util/httptyped/httptyped_test.go index 47e26eaa..50725074 100644 --- a/pkg/util/httptyped/httptyped_test.go +++ b/pkg/util/httptyped/httptyped_test.go @@ -2,7 +2,7 @@ package httptyped import ( "encoding/json" - "fmt" + "errors" "path" "reflect" "testing" @@ -160,7 +160,7 @@ func TestPrepareModel(t *testing.T) { testName := "TestPrepareModel" DefaultRegistry.RegisterType(testObj{}) DefaultRegistry.RegisterType(WithSerializedParent{}) - notRegisteredErr := fmt.Errorf("httptyped.invalidTestObj is not registered to httptyped") + notRegisteredErr := errors.New("httptyped.invalidTestObj is not registered to httptyped") testCases := []struct { name string diff --git a/pkg/util/jhttp/jhttp_test.go b/pkg/util/jhttp/jhttp_test.go index 2e3869ec..4ec988a2 100644 --- a/pkg/util/jhttp/jhttp_test.go +++ b/pkg/util/jhttp/jhttp_test.go @@ -3,6 +3,7 @@ package jhttp import ( "bytes" "context" + "errors" "fmt" "net/http" "net/http/httptest" @@ -51,7 +52,7 @@ func TestRequestWrap(t *testing.T) { expectedBody string }{ {name: "normal", val: "123", status: http.StatusOK, expectedBody: "123"}, - {name: "err", status: http.StatusUnprocessableEntity, err: fmt.Errorf("unprocessible"), + {name: "err", status: http.StatusUnprocessableEntity, err: errors.New("unprocessible"), expectedBody: "{\"error\":\"unprocessible\",\"code\":422,\"status_text\":\"Unprocessable Entity\"}\n"}, } for _, tc := range testCases { @@ -78,7 +79,7 @@ func TestRespondJSONWrap(t *testing.T) { var testErr error handlerFunc := ResponseWrap(func(r *http.Request) (any, *HTTPError) { if r.Method != http.MethodGet { - return nil, Error(http.StatusInternalServerError, fmt.Errorf("not a GET")) + return nil, Error(http.StatusInternalServerError, errors.New("not a GET")) } if testStatus != http.StatusOK { return nil, Error(testStatus, testErr) @@ -97,7 +98,7 @@ func TestRespondJSONWrap(t *testing.T) { {name: "normal", val: "123", status: http.StatusOK, expectedBody: "{\"val\":\"123\"}\n"}, {name: "post", method: http.MethodPost, status: http.StatusInternalServerError, expectedBody: "{\"error\":\"not a GET\",\"code\":500,\"status_text\":\"Internal Server Error\"}\n"}, - {name: "err", status: http.StatusUnprocessableEntity, err: fmt.Errorf("unprocessible"), + {name: "err", status: http.StatusUnprocessableEntity, err: errors.New("unprocessible"), expectedBody: "{\"error\":\"unprocessible\",\"code\":422,\"status_text\":\"Unprocessable Entity\"}\n"}, } for _, tc := range testCases { @@ -118,14 +119,14 @@ func TestRespondError(t *testing.T) { require := require.New(t) resp := httptest.NewRecorder() - httpError := Error(http.StatusInternalServerError, fmt.Errorf("my error")) + httpError := Error(http.StatusInternalServerError, errors.New("my error")) RespondError(resp, httpError) require.Equal(httpError.Code, resp.Code) require.Equal("{\"error\":\"my error\",\"code\":500,\"status_text\":\"Internal Server Error\"}\n", resp.Body.String()) - require.Equal(resp.Header().Get("Content-Type"), JSONContentType) - require.Equal(resp.Header().Get("X-Content-Type-Options"), "nosniff") + require.Equal(JSONContentType, resp.Header().Get("Content-Type")) + require.Equal("nosniff", resp.Header().Get("X-Content-Type-Options")) } func TestRespondJSON(t *testing.T) { @@ -137,7 +138,7 @@ func TestRespondJSON(t *testing.T) { require.Equal(http.StatusOK, resp.Code) require.Equal("{\"val\":\"my test\"}\n", resp.Body.String()) - require.Equal(resp.Header().Get("Content-Type"), JSONContentType) + require.Equal(JSONContentType, resp.Header().Get("Content-Type")) } func TestExtractJSON(t *testing.T) { @@ -179,7 +180,7 @@ func TestExtractJSON(t *testing.T) { } func TestReturnModelOr500(t *testing.T) { - httpErr := &HTTPError{Code: http.StatusInternalServerError, Cause: fmt.Errorf("waka")} + httpErr := &HTTPError{Code: http.StatusInternalServerError, Cause: errors.New("waka")} testCases := []struct { name string model any diff --git a/pkg/util/jhttp/reqtx/reqtx_test.go b/pkg/util/jhttp/reqtx/reqtx_test.go index 948d602b..05f5be47 100644 --- a/pkg/util/jhttp/reqtx/reqtx_test.go +++ b/pkg/util/jhttp/reqtx/reqtx_test.go @@ -2,7 +2,7 @@ package reqtx import ( "context" - "fmt" + "errors" "net/http" "net/http/httptest" "testing" @@ -22,7 +22,7 @@ type txn struct { func (t *txn) Finalize() error { if t.mode == finalizeErrorMode { - return fmt.Errorf("test: finalizeErrorMode") + return errors.New("test: finalizeErrorMode") } t.finalizeCount++ @@ -42,7 +42,7 @@ type pool struct{ txn *txn } func (p *pool) GetTx(r *http.Request, mode txMode) (Tx, error) { if mode != okMode && mode != finalizeErrorMode { - return nil, fmt.Errorf("test: !okMode") + return nil, errors.New("test: !okMode") } if p.txn == nil { p.txn = &txn{ctx: r.Context(), mode: mode} @@ -76,7 +76,7 @@ func TestTxMode(t *testing.T) { }{ {name: "normal", expectedMode: 1}, {name: "nil", mode: nil}, - {name: "string", mode: "fail", err: jhttp.Error(http.StatusInternalServerError, fmt.Errorf("cast to reqtx.txMode fail"))}, + {name: "string", mode: "fail", err: jhttp.Error(http.StatusInternalServerError, errors.New("cast to reqtx.txMode fail"))}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { @@ -113,12 +113,12 @@ func TestIntegrator_ResponseWrap(t *testing.T) { errFinalizeErrorCount int }{ {name: "normal"}, - {name: "req_error", reqErr: jhttp.Error(http.StatusBadRequest, fmt.Errorf("test_induced"))}, - {name: "bad_mode", mode: -9, err: jhttp.Error(http.StatusInternalServerError, fmt.Errorf("test: !okMode"))}, + {name: "req_error", reqErr: jhttp.Error(http.StatusBadRequest, errors.New("test_induced"))}, + {name: "bad_mode", mode: -9, err: jhttp.Error(http.StatusInternalServerError, errors.New("test: !okMode"))}, {name: "finalize_fail", mode: finalizeErrorMode, errMode: finalizeErrorMode, errFinalizeErrorCount: 1, - err: jhttp.Error(http.StatusInternalServerError, fmt.Errorf("test: finalizeErrorMode"))}, + err: jhttp.Error(http.StatusInternalServerError, errors.New("test: finalizeErrorMode"))}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { @@ -138,7 +138,7 @@ func TestIntegrator_ResponseWrap(t *testing.T) { tx, err := integrator.GetTx(req, okMode) require.NoError(err) - require.Equal(nil, model) + require.Nil(model) if tc.err != nil { require.Equal(tc.err, httpErr) require.Equal(&txn{ctx: req.Context(), mode: tc.errMode, finalizeErrorCount: tc.errFinalizeErrorCount}, tx) diff --git a/pkg/util/jhttp/reqtx/reqtxtest/reqtxtest_test.go b/pkg/util/jhttp/reqtx/reqtxtest/reqtxtest_test.go index b61aaff0..a9934486 100644 --- a/pkg/util/jhttp/reqtx/reqtxtest/reqtxtest_test.go +++ b/pkg/util/jhttp/reqtx/reqtxtest/reqtxtest_test.go @@ -1,7 +1,7 @@ package reqtxtest import ( - "fmt" + "errors" "net/http" "net/http/httptest" "testing" @@ -31,8 +31,8 @@ func TestPool_SetTxGetTx(t *testing.T) { err error }{ {name: "normal", mode: mode}, - {name: "diff_request", req: newRequest(), mode: mode, err: fmt.Errorf("transaction with id, , does not exist")}, - {name: "diff_mode", mode: -9, err: fmt.Errorf("stored Tx mode (1) is not matching passed mode (-9)")}, + {name: "diff_request", req: newRequest(), mode: mode, err: errors.New("transaction with id, , does not exist")}, + {name: "diff_mode", mode: -9, err: errors.New("stored Tx mode (1) is not matching passed mode (-9)")}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/util/test/data.go b/pkg/util/test/data.go index 782bea9a..9d865ea2 100644 --- a/pkg/util/test/data.go +++ b/pkg/util/test/data.go @@ -114,7 +114,7 @@ func EmptyFields(t *testing.T, s interface{}) []string { emptyFields := make([]string, v.NumField()) a := 0 - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { if v.Field(i).IsZero() { emptyFields[a] = v.Type().Field(i).Name a++ diff --git a/pkg/util/test/fixture/fixture.go b/pkg/util/test/fixture/fixture.go index f55af4d5..7ced6f48 100644 --- a/pkg/util/test/fixture/fixture.go +++ b/pkg/util/test/fixture/fixture.go @@ -49,13 +49,13 @@ func Update(t *testing.T, fixturePath string, resultBytes []byte) { } err := os.MkdirAll(path.Join(TestDataDir, filepath.Dir(fixturePath)), os.ModePerm) - assert.NoError(err) + assert.NoError(err) //nolint:testifylint // requires assert to keep making more fixtures err = os.WriteFile(JoinTestData(fixturePath), resultBytes, ioutil.OwnerRWGroupR) - assert.NoError(err) + assert.NoError(err) //nolint:testifylint // requires assert to keep making more fixtures if WillUpdate() { - assert.Fail(UpdateFailMessage) + assert.Fail(UpdateFailMessage) //nolint:testifylint // requires assert to keep making more fixtures } }