diff --git a/.golangci.yml b/.golangci.yml index 9075b9321d..b3c66c4d7d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,12 +1,5 @@ run: timeout: 5m - skip-dirs-use-default: false - skip-dirs: - - (^|/)vendor($|/) - - (^|/)testdata($|/) - - (^|/)etc($|/) - # Disable all linters for "golang.org/x/exp/rand" package in internal/rand. - - internal/rand linters: disable-all: true @@ -35,11 +28,7 @@ linters: linters-settings: errcheck: - exclude: .errcheck-excludes - gocritic: - enabled-checks: - # Detects suspicious append result assignments. E.g. "b := append(a, 1, 2, 3)" - - appendAssign + exclude-functions: .errcheck-excludes govet: disable: - cgocall @@ -55,6 +44,14 @@ linters-settings: ] issues: + exclude-dirs-use-default: false + exclude-dirs: + - (^|/)testdata($|/) + - (^|/)etc($|/) + # Disable all linters for copied third-party code. + - internal/rand + - internal/aws + - internal/assert exclude-use-default: false exclude: # Add all default excluded issues except issues related to exported types/functions not having diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 12e77d5a09..733618dead 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -51,6 +51,6 @@ repos: exclude: ^(vendor) - repo: https://github.com/golangci/golangci-lint - rev: v1.55.1 + rev: v1.59.1 hooks: - id: golangci-lint diff --git a/Makefile b/Makefile index 33001650db..2c5112d248 100644 --- a/Makefile +++ b/Makefile @@ -65,9 +65,11 @@ doc: fmt: go fmt ./... +# NOTE: A golangci-lint version is also pinned in .pre-commit-config.yaml. Make +# sure to change it there to keep it in-sync with what's used here! .PHONY: install-golangci-lint install-golangci-lint: - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.52.2 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.59.1 # Lint with various GOOS and GOARCH targets to catch static analysis failures that may only affect # specific operating systems or architectures. For example, staticcheck will only check for 64-bit diff --git a/bson/bsoncodec_test.go b/bson/bsoncodec_test.go index 61c38933ee..57bbec8d36 100644 --- a/bson/bsoncodec_test.go +++ b/bson/bsoncodec_test.go @@ -23,7 +23,7 @@ func ExampleValueEncoder() { } func ExampleValueDecoder() { - var _ ValueDecoderFunc = func(dc DecodeContext, vr ValueReader, val reflect.Value) error { + var _ ValueDecoderFunc = func(_ DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Kind() != reflect.String { return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} } diff --git a/bson/decimal.go b/bson/decimal.go index 34a919c46a..85c506ef8a 100644 --- a/bson/decimal.go +++ b/bson/decimal.go @@ -75,13 +75,12 @@ func (d Decimal128) BigInt() (*big.Int, int, error) { // Bits: 1*sign 2*ignored 14*exponent 111*significand. // Implicit 0b100 prefix in significand. exp = int(high >> 47 & (1<<14 - 1)) - //high = 4<<47 | d.h&(1<<47-1) // Spec says all of these values are out of range. high, low = 0, 0 } else { // Bits: 1*sign 14*exponent 113*significand exp = int(high >> 49 & (1<<14 - 1)) - high = high & (1<<49 - 1) + high &= (1<<49 - 1) } exp += MinDecimal128Exp @@ -258,7 +257,7 @@ var ( // ParseDecimal128FromBigInt attempts to parse the given significand and exponent into a valid Decimal128 value. func ParseDecimal128FromBigInt(bi *big.Int, exp int) (Decimal128, bool) { - //copy + // copy bi = new(big.Int).Set(bi) q := new(big.Int) diff --git a/bson/decoder_test.go b/bson/decoder_test.go index 3b424f4623..4cebea9d0e 100644 --- a/bson/decoder_test.go +++ b/bson/decoder_test.go @@ -508,7 +508,7 @@ func TestDecoderConfiguration(t *testing.T) { // independent of the top-level Go value type. { description: "DocumentD nested by default", - configure: func(dec *Decoder) {}, + configure: func(_ *Decoder) {}, input: bsoncore.NewDocumentBuilder(). AppendDocument("myDocument", bsoncore.NewDocumentBuilder(). AppendString("myString", "test value"). diff --git a/bson/default_value_decoders.go b/bson/default_value_decoders.go index 2786a71b55..7dab1fa5a5 100644 --- a/bson/default_value_decoders.go +++ b/bson/default_value_decoders.go @@ -1286,7 +1286,8 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle var elem reflect.Value if vDecoder == nil { elem = val.Index(idx).Elem() - if elem.Kind() != reflect.Ptr || elem.IsNil() { + switch { + case elem.Kind() != reflect.Ptr || elem.IsNil(): valueDecoder, err := dc.LookupDecoder(elem.Type()) if err != nil { return nil, err @@ -1295,12 +1296,12 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle if err != nil { return nil, newDecodeError(strconv.Itoa(idx), err) } - } else if vr.Type() == TypeNull { + case vr.Type() == TypeNull: if err = vr.ReadNull(); err != nil { return nil, err } elem = reflect.Zero(val.Index(idx).Type()) - } else { + default: e := elem.Elem() valueDecoder, err := dc.LookupDecoder(e.Type()) if err != nil { diff --git a/bson/default_value_encoders_test.go b/bson/default_value_encoders_test.go index c1cad80c5e..e15019785d 100644 --- a/bson/default_value_encoders_test.go +++ b/bson/default_value_encoders_test.go @@ -1075,7 +1075,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "WriteArrayElement Error", - bsoncore.Array(buildDocumentArray(func(doc []byte) []byte { + bsoncore.Array(buildDocumentArray(func([]byte) []byte { return bsoncore.AppendNullElement(nil, "foo") })), nil, @@ -1085,7 +1085,7 @@ func TestDefaultValueEncoders(t *testing.T) { }, { "encodeValue error", - bsoncore.Array(buildDocumentArray(func(doc []byte) []byte { + bsoncore.Array(buildDocumentArray(func([]byte) []byte { return bsoncore.AppendNullElement(nil, "foo") })), nil, diff --git a/bson/extjson_parser.go b/bson/extjson_parser.go index 540416cbec..dba0ec77ec 100644 --- a/bson/extjson_parser.go +++ b/bson/extjson_parser.go @@ -303,7 +303,7 @@ func (ejp *extJSONParser) readValue(t Type) (*extJSONValue, error) { } // remove hyphens - uuidNoHyphens := strings.Replace(uuid, "-", "", -1) + uuidNoHyphens := strings.ReplaceAll(uuid, "-", "") if len(uuidNoHyphens) != 32 { return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding length and hyphens") } diff --git a/bson/extjson_writer.go b/bson/extjson_writer.go index 797e24883f..5f231ba1c7 100644 --- a/bson/extjson_writer.go +++ b/bson/extjson_writer.go @@ -567,13 +567,14 @@ func (ejvw *extJSONValueWriter) WriteArrayEnd() error { func formatDouble(f float64) string { var s string - if math.IsInf(f, 1) { + switch { + case math.IsInf(f, 1): s = "Infinity" - } else if math.IsInf(f, -1) { + case math.IsInf(f, -1): s = "-Infinity" - } else if math.IsNaN(f) { + case math.IsNaN(f): s = "NaN" - } else { + default: // Print exactly one decimalType place for integers; otherwise, print as many are necessary to // perfectly represent it. s = strconv.FormatFloat(f, 'G', -1, 64) @@ -678,9 +679,7 @@ func (ss sortableString) Less(i, j int) bool { } func (ss sortableString) Swap(i, j int) { - oldI := ss[i] - ss[i] = ss[j] - ss[j] = oldI + ss[i], ss[j] = ss[j], ss[i] } func sortStringAlphebeticAscending(s string) string { diff --git a/bson/json_scanner.go b/bson/json_scanner.go index a0a840c6cc..b6eba79e9e 100644 --- a/bson/json_scanner.go +++ b/bson/json_scanner.go @@ -82,12 +82,13 @@ func (js *jsonScanner) nextToken() (*jsonToken, error) { return js.scanString() default: // check if it's a number - if c == '-' || isDigit(c) { + switch { + case c == '-' || isDigit(c): return js.scanNumber(c) - } else if c == 't' || c == 'f' || c == 'n' { + case c == 't' || c == 'f' || c == 'n': // maybe a literal return js.scanLiteral(c) - } else { + default: return nil, fmt.Errorf("invalid JSON input. Position: %d. Character: %c", js.pos-1, c) } } @@ -174,7 +175,7 @@ func getu4(s []byte) rune { for _, c := range s[:4] { switch { case '0' <= c && c <= '9': - c = c - '0' + c -= '0' case 'a' <= c && c <= 'f': c = c - 'a' + 10 case 'A' <= c && c <= 'F': @@ -325,13 +326,14 @@ func (js *jsonScanner) scanLiteral(first byte) (*jsonToken, error) { c5, err := js.readNextByte() - if bytes.Equal([]byte("true"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)) { + switch { + case bytes.Equal([]byte("true"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)): js.pos = int(math.Max(0, float64(js.pos-1))) return &jsonToken{t: jttBool, v: true, p: p}, nil - } else if bytes.Equal([]byte("null"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)) { + case bytes.Equal([]byte("null"), lit) && (isValueTerminator(c5) || errors.Is(err, io.EOF)): js.pos = int(math.Max(0, float64(js.pos-1))) return &jsonToken{t: jttNull, v: nil, p: p}, nil - } else if bytes.Equal([]byte("fals"), lit) { + case bytes.Equal([]byte("fals"), lit): if c5 == 'e' { c5, err = js.readNextByte() @@ -430,12 +432,13 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { case '}', ']', ',': s = nssDone default: - if isWhiteSpace(c) || errors.Is(err, io.EOF) { + switch { + case isWhiteSpace(c) || errors.Is(err, io.EOF): s = nssDone - } else if isDigit(c) { + case isDigit(c): s = nssSawIntegerDigits b.WriteByte(c) - } else { + default: s = nssInvalid } } @@ -455,12 +458,13 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { case '}', ']', ',': s = nssDone default: - if isWhiteSpace(c) || errors.Is(err, io.EOF) { + switch { + case isWhiteSpace(c) || errors.Is(err, io.EOF): s = nssDone - } else if isDigit(c) { + case isDigit(c): s = nssSawFractionDigits b.WriteByte(c) - } else { + default: s = nssInvalid } } @@ -490,12 +494,13 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { case '}', ']', ',': s = nssDone default: - if isWhiteSpace(c) || errors.Is(err, io.EOF) { + switch { + case isWhiteSpace(c) || errors.Is(err, io.EOF): s = nssDone - } else if isDigit(c) { + case isDigit(c): s = nssSawExponentDigits b.WriteByte(c) - } else { + default: s = nssInvalid } } diff --git a/bson/mgoregistry_test.go b/bson/mgoregistry_test.go index d8576e5189..fa0051ea14 100644 --- a/bson/mgoregistry_test.go +++ b/bson/mgoregistry_test.go @@ -137,7 +137,7 @@ var allItems = []testItemType{ {M{"_": Undefined{}}, // Obsolete, but still seen in the wild. "\x06_\x00"}, {M{"_": ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}, - "\x07_\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, //technically this is not the same as the original mgo test + "\x07_\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, // technically this is not the same as the original mgo test {M{"_": DBPointer{DB: "testnamespace", Pointer: ObjectID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B}}}, "\x0C_\x00\x0e\x00\x00\x00testnamespace\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"}, {M{"_": false}, @@ -1678,6 +1678,8 @@ var jsonIDTests = []struct { func TestObjectIdJSONMarshaling(t *testing.T) { for i, test := range jsonIDTests { + test := test // Capture range variable. + t.Run(strconv.Itoa(i), func(t *testing.T) { if test.marshal { data, err := json.Marshal(&test.value) diff --git a/bson/registry_examples_test.go b/bson/registry_examples_test.go index c38094fcea..82ccf17169 100644 --- a/bson/registry_examples_test.go +++ b/bson/registry_examples_test.go @@ -23,7 +23,7 @@ func ExampleRegistry_customEncoder() { negatedIntType := reflect.TypeOf(negatedInt(0)) negatedIntEncoder := func( - ec bson.EncodeContext, + _ bson.EncodeContext, vw bson.ValueWriter, val reflect.Value, ) error { @@ -85,7 +85,7 @@ func ExampleRegistry_customDecoder() { lenientBoolType := reflect.TypeOf(lenientBool(true)) lenientBoolDecoder := func( - dc bson.DecodeContext, + _ bson.DecodeContext, vr bson.ValueReader, val reflect.Value, ) error { @@ -164,7 +164,7 @@ func ExampleRegistry_RegisterKindEncoder() { // encoder for kind reflect.Int32. That way, even user-defined types with // underlying type int32 will be encoded as a BSON int64. int32To64Encoder := func( - ec bson.EncodeContext, + _ bson.EncodeContext, vw bson.ValueWriter, val reflect.Value, ) error { @@ -223,7 +223,7 @@ func ExampleRegistry_RegisterKindDecoder() { // "kind" decoder for kind reflect.Int64. That way, we can even decode to // user-defined types with underlying type int64. flexibleInt64KindDecoder := func( - dc bson.DecodeContext, + _ bson.DecodeContext, vr bson.ValueReader, val reflect.Value, ) error { diff --git a/bson/registry_test.go b/bson/registry_test.go index f07f6b5f3f..b3a94e6195 100644 --- a/bson/registry_test.go +++ b/bson/registry_test.go @@ -25,408 +25,6 @@ func newTestRegistry() *Registry { } } -func TestRegistryBuilder(t *testing.T) { - t.Run("Register", func(t *testing.T) { - fc1, fc2, fc3, fc4 := new(fakeCodec), new(fakeCodec), new(fakeCodec), new(fakeCodec) - t.Run("interface", func(t *testing.T) { - var t1f *testInterface1 - var t2f *testInterface2 - var t4f *testInterface4 - ips := []interfaceValueEncoder{ - {i: reflect.TypeOf(t1f).Elem(), ve: fc1}, - {i: reflect.TypeOf(t2f).Elem(), ve: fc2}, - {i: reflect.TypeOf(t1f).Elem(), ve: fc3}, - {i: reflect.TypeOf(t4f).Elem(), ve: fc4}, - } - want := []interfaceValueEncoder{ - {i: reflect.TypeOf(t1f).Elem(), ve: fc3}, - {i: reflect.TypeOf(t2f).Elem(), ve: fc2}, - {i: reflect.TypeOf(t4f).Elem(), ve: fc4}, - } - reg := newTestRegistry() - for _, ip := range ips { - reg.RegisterInterfaceEncoder(ip.i, ip.ve) - } - - got := reg.interfaceEncoders - if !cmp.Equal(got, want, cmp.AllowUnexported(interfaceValueEncoder{}, fakeCodec{}), cmp.Comparer(typeComparer)) { - t.Errorf("the registered interfaces are not correct: got %#v, want %#v", got, want) - } - }) - t.Run("type", func(t *testing.T) { - ft1, ft2, ft4 := fakeType1{}, fakeType2{}, fakeType4{} - reg := newTestRegistry() - reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc1) - reg.RegisterTypeEncoder(reflect.TypeOf(ft2), fc2) - reg.RegisterTypeEncoder(reflect.TypeOf(ft1), fc3) - reg.RegisterTypeEncoder(reflect.TypeOf(ft4), fc4) - want := []struct { - t reflect.Type - c ValueEncoder - }{ - {reflect.TypeOf(ft1), fc3}, - {reflect.TypeOf(ft2), fc2}, - {reflect.TypeOf(ft4), fc4}, - } - - got := reg.typeEncoders - for _, s := range want { - wantT, wantC := s.t, s.c - gotC, exists := got.Load(wantT) - if !exists { - t.Errorf("Did not find type in the type registry: %v", wantT) - } - if !cmp.Equal(gotC, wantC, cmp.AllowUnexported(fakeCodec{})) { - t.Errorf("codecs did not match: got %#v; want %#v", gotC, wantC) - } - } - }) - t.Run("kind", func(t *testing.T) { - k1, k2, k4 := reflect.Struct, reflect.Slice, reflect.Map - reg := newTestRegistry() - reg.RegisterKindEncoder(k1, fc1) - reg.RegisterKindEncoder(k2, fc2) - reg.RegisterKindEncoder(k1, fc3) - reg.RegisterKindEncoder(k4, fc4) - want := []struct { - k reflect.Kind - c ValueEncoder - }{ - {k1, fc3}, - {k2, fc2}, - {k4, fc4}, - } - - got := reg.kindEncoders - for _, s := range want { - wantK, wantC := s.k, s.c - gotC, exists := got.Load(wantK) - if !exists { - t.Errorf("Did not find kind in the kind registry: %v", wantK) - } - if !cmp.Equal(gotC, wantC, cmp.AllowUnexported(fakeCodec{})) { - t.Errorf("codecs did not match: got %#v; want %#v", gotC, wantC) - } - } - }) - t.Run("RegisterDefault", func(t *testing.T) { - t.Run("MapCodec", func(t *testing.T) { - codec := &fakeCodec{num: 1} - codec2 := &fakeCodec{num: 2} - reg := newTestRegistry() - - reg.RegisterKindEncoder(reflect.Map, codec) - if reg.kindEncoders.get(reflect.Map) != codec { - t.Errorf("map codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Map), codec) - } - - reg.RegisterKindEncoder(reflect.Map, codec2) - if reg.kindEncoders.get(reflect.Map) != codec2 { - t.Errorf("map codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Map), codec2) - } - }) - t.Run("StructCodec", func(t *testing.T) { - codec := &fakeCodec{num: 1} - codec2 := &fakeCodec{num: 2} - reg := newTestRegistry() - - reg.RegisterKindEncoder(reflect.Struct, codec) - if reg.kindEncoders.get(reflect.Struct) != codec { - t.Errorf("struct codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Struct), codec) - } - - reg.RegisterKindEncoder(reflect.Struct, codec2) - if reg.kindEncoders.get(reflect.Struct) != codec2 { - t.Errorf("struct codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Struct), codec2) - } - }) - t.Run("SliceCodec", func(t *testing.T) { - codec := &fakeCodec{num: 1} - codec2 := &fakeCodec{num: 2} - reg := newTestRegistry() - - reg.RegisterKindEncoder(reflect.Slice, codec) - if reg.kindEncoders.get(reflect.Slice) != codec { - t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Slice), codec) - } - - reg.RegisterKindEncoder(reflect.Slice, codec2) - if reg.kindEncoders.get(reflect.Slice) != codec2 { - t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Slice), codec2) - } - }) - t.Run("ArrayCodec", func(t *testing.T) { - codec := &fakeCodec{num: 1} - codec2 := &fakeCodec{num: 2} - reg := newTestRegistry() - - reg.RegisterKindEncoder(reflect.Array, codec) - if reg.kindEncoders.get(reflect.Array) != codec { - t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Array), codec) - } - - reg.RegisterKindEncoder(reflect.Array, codec2) - if reg.kindEncoders.get(reflect.Array) != codec2 { - t.Errorf("slice codec not properly set: got %#v, want %#v", reg.kindEncoders.get(reflect.Array), codec2) - } - }) - }) - t.Run("Lookup", func(t *testing.T) { - type Codec interface { - ValueEncoder - ValueDecoder - } - - var ( - arrinstance [12]int - arr = reflect.TypeOf(arrinstance) - slc = reflect.TypeOf(make([]int, 12)) - m = reflect.TypeOf(make(map[string]int)) - strct = reflect.TypeOf(struct{ Foo string }{}) - ft1 = reflect.PtrTo(reflect.TypeOf(fakeType1{})) - ft2 = reflect.TypeOf(fakeType2{}) - ft3 = reflect.TypeOf(fakeType5(func(string, string) string { return "fakeType5" })) - ti1 = reflect.TypeOf((*testInterface1)(nil)).Elem() - ti2 = reflect.TypeOf((*testInterface2)(nil)).Elem() - ti1Impl = reflect.TypeOf(testInterface1Impl{}) - ti2Impl = reflect.TypeOf(testInterface2Impl{}) - ti3 = reflect.TypeOf((*testInterface3)(nil)).Elem() - ti3Impl = reflect.TypeOf(testInterface3Impl{}) - ti3ImplPtr = reflect.TypeOf((*testInterface3Impl)(nil)) - fc1, fc2 = &fakeCodec{num: 1}, &fakeCodec{num: 2} - fsc, fslcc, fmc = new(fakeStructCodec), new(fakeSliceCodec), new(fakeMapCodec) - pc = &pointerCodec{} - ) - - reg := newTestRegistry() - reg.RegisterTypeEncoder(ft1, fc1) - reg.RegisterTypeEncoder(ft2, fc2) - reg.RegisterTypeEncoder(ti1, fc1) - reg.RegisterKindEncoder(reflect.Struct, fsc) - reg.RegisterKindEncoder(reflect.Slice, fslcc) - reg.RegisterKindEncoder(reflect.Array, fslcc) - reg.RegisterKindEncoder(reflect.Map, fmc) - reg.RegisterKindEncoder(reflect.Ptr, pc) - reg.RegisterTypeDecoder(ft1, fc1) - reg.RegisterTypeDecoder(ft2, fc2) - reg.RegisterTypeDecoder(ti1, fc1) // values whose exact type is testInterface1 will use fc1 encoder - reg.RegisterKindDecoder(reflect.Struct, fsc) - reg.RegisterKindDecoder(reflect.Slice, fslcc) - reg.RegisterKindDecoder(reflect.Array, fslcc) - reg.RegisterKindDecoder(reflect.Map, fmc) - reg.RegisterKindDecoder(reflect.Ptr, pc) - reg.RegisterInterfaceEncoder(ti2, fc2) - reg.RegisterInterfaceDecoder(ti2, fc2) - reg.RegisterInterfaceEncoder(ti3, fc3) - reg.RegisterInterfaceDecoder(ti3, fc3) - - testCases := []struct { - name string - t reflect.Type - wantcodec Codec - wanterr error - testcache bool - }{ - { - "type registry (pointer)", - ft1, - fc1, - nil, - false, - }, - { - "type registry (non-pointer)", - ft2, - fc2, - nil, - false, - }, - { - // lookup an interface type and expect that the registered encoder is returned - "interface with type encoder", - ti1, - fc1, - nil, - true, - }, - { - // lookup a type that implements an interface and expect that the default struct codec is returned - "interface implementation with type encoder", - ti1Impl, - fsc, - nil, - false, - }, - { - // lookup an interface type and expect that the registered hook is returned - "interface with hook", - ti2, - fc2, - nil, - false, - }, - { - // lookup a type that implements an interface and expect that the registered hook is returned - "interface implementation with hook", - ti2Impl, - fc2, - nil, - false, - }, - { - // lookup a pointer to a type where the pointer implements an interface and expect that the - // registered hook is returned - "interface pointer to implementation with hook (pointer)", - ti3ImplPtr, - fc3, - nil, - false, - }, - { - "default struct codec (pointer)", - reflect.PtrTo(strct), - pc, - nil, - false, - }, - { - "default struct codec (non-pointer)", - strct, - fsc, - nil, - false, - }, - { - "default array codec", - arr, - fslcc, - nil, - false, - }, - { - "default slice codec", - slc, - fslcc, - nil, - false, - }, - { - "default map", - m, - fmc, - nil, - false, - }, - { - "map non-string key", - reflect.TypeOf(map[int]int{}), - fmc, - nil, - false, - }, - { - "No Codec Registered", - ft3, - nil, - errNoEncoder{Type: ft3}, - false, - }, - } - - allowunexported := cmp.AllowUnexported(fakeCodec{}, fakeStructCodec{}, fakeSliceCodec{}, fakeMapCodec{}) - comparepc := func(pc1, pc2 *pointerCodec) bool { return true } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - t.Run("Encoder", func(t *testing.T) { - gotcodec, goterr := reg.LookupEncoder(tc.t) - if !cmp.Equal(goterr, tc.wanterr, cmp.Comparer(assert.CompareErrors)) { - t.Errorf("errors did not match: got %#v, want %#v", goterr, tc.wanterr) - } - if !cmp.Equal(gotcodec, tc.wantcodec, allowunexported, cmp.Comparer(comparepc)) { - t.Errorf("codecs did not match: got %#v, want %#v", gotcodec, tc.wantcodec) - } - }) - t.Run("Decoder", func(t *testing.T) { - wanterr := tc.wanterr - if ene, ok := tc.wanterr.(errNoEncoder); ok { - wanterr = errNoDecoder(ene) - } - - gotcodec, goterr := reg.LookupDecoder(tc.t) - if !cmp.Equal(goterr, wanterr, cmp.Comparer(assert.CompareErrors)) { - t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) - } - if !cmp.Equal(gotcodec, tc.wantcodec, allowunexported, cmp.Comparer(comparepc)) { - t.Errorf("codecs did not match: got %#v, want %#v", gotcodec, tc.wantcodec) - } - }) - }) - } - // lookup a type whose pointer implements an interface and expect that the registered hook is - // returned - t.Run("interface implementation with hook (pointer)", func(t *testing.T) { - t.Run("Encoder", func(t *testing.T) { - gotEnc, err := reg.LookupEncoder(ti3Impl) - assert.Nil(t, err, "LookupEncoder error: %v", err) - - cae, ok := gotEnc.(*condAddrEncoder) - assert.True(t, ok, "Expected CondAddrEncoder, got %T", gotEnc) - if !cmp.Equal(cae.canAddrEnc, fc3, allowunexported, cmp.Comparer(comparepc)) { - t.Errorf("expected canAddrEnc %#v, got %#v", cae.canAddrEnc, fc3) - } - if !cmp.Equal(cae.elseEnc, fsc, allowunexported, cmp.Comparer(comparepc)) { - t.Errorf("expected elseEnc %#v, got %#v", cae.elseEnc, fsc) - } - }) - t.Run("Decoder", func(t *testing.T) { - gotDec, err := reg.LookupDecoder(ti3Impl) - assert.Nil(t, err, "LookupDecoder error: %v", err) - - cad, ok := gotDec.(*condAddrDecoder) - assert.True(t, ok, "Expected CondAddrDecoder, got %T", gotDec) - if !cmp.Equal(cad.canAddrDec, fc3, allowunexported, cmp.Comparer(comparepc)) { - t.Errorf("expected canAddrDec %#v, got %#v", cad.canAddrDec, fc3) - } - if !cmp.Equal(cad.elseDec, fsc, allowunexported, cmp.Comparer(comparepc)) { - t.Errorf("expected elseDec %#v, got %#v", cad.elseDec, fsc) - } - }) - }) - }) - }) - t.Run("Type Map", func(t *testing.T) { - reg := newTestRegistry() - reg.RegisterTypeMapEntry(TypeString, reflect.TypeOf("")) - reg.RegisterTypeMapEntry(TypeInt32, reflect.TypeOf(int(0))) - - var got, want reflect.Type - - want = reflect.TypeOf("") - got, err := reg.LookupTypeMapEntry(TypeString) - noerr(t, err) - if got != want { - t.Errorf("unexpected type: got %#v, want %#v", got, want) - } - - want = reflect.TypeOf(int(0)) - got, err = reg.LookupTypeMapEntry(TypeInt32) - noerr(t, err) - if got != want { - t.Errorf("unexpected type: got %#v, want %#v", got, want) - } - - want = nil - wanterr := errNoTypeMapEntry{Type: TypeObjectID} - got, err = reg.LookupTypeMapEntry(TypeObjectID) - if !errors.Is(err, wanterr) { - t.Errorf("did not get expected error: got %#v, want %#v", err, wanterr) - } - if got != want { - t.Errorf("unexpected type: got %#v, want %#v", got, want) - } - }) -} - func TestRegistry(t *testing.T) { t.Parallel() @@ -749,7 +347,7 @@ func TestRegistry(t *testing.T) { } allowunexported := cmp.AllowUnexported(fakeCodec{}, fakeStructCodec{}, fakeSliceCodec{}, fakeMapCodec{}) - comparepc := func(pc1, pc2 *pointerCodec) bool { return true } + comparepc := func(pc1, pc2 *pointerCodec) bool { return pc1 == pc2 } for _, tc := range testCases { tc := tc diff --git a/bson/unmarshal_test.go b/bson/unmarshal_test.go index 0f101581d0..35a66141be 100644 --- a/bson/unmarshal_test.go +++ b/bson/unmarshal_test.go @@ -636,7 +636,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: []byte{0, 1, 2, 3, 4, 5}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooBytes))).Foo + return (val.(*fooBytes)).Foo }, }, { @@ -662,7 +662,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: myBytes{0, 1, 2, 3, 4, 5}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooMyBytes))).Foo + return (val.(*fooMyBytes)).Foo }, }, { @@ -688,7 +688,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: Binary{Subtype: 0, Data: []byte{0, 1, 2, 3, 4, 5}}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooBinary))).Foo.Data + return (val.(*fooBinary)).Foo.Data }, }, { @@ -714,7 +714,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { Foo: ObjectID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooObjectID))).Foo[:] + return (val.(*fooObjectID)).Foo[:] }, }, { @@ -747,7 +747,7 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { }, }, getByteSlice: func(val interface{}) []byte { - return (*(val.(*fooDBPointer))).Foo.Pointer[:] + return (val.(*fooDBPointer)).Foo.Pointer[:] }, }, { diff --git a/bson/value_writer.go b/bson/value_writer.go index 0c91aad251..57334a925d 100644 --- a/bson/value_writer.go +++ b/bson/value_writer.go @@ -535,7 +535,7 @@ func (vw *valueWriter) writeLength() error { return errMaxDocumentSizeExceeded{size: int64(len(vw.buf))} } frame := &vw.stack[vw.frame] - length = length - int(frame.start) + length -= int(frame.start) start := frame.start _ = vw.buf[start+3] // BCE diff --git a/internal/cmd/build-oss-fuzz-corpus/main.go b/internal/cmd/build-oss-fuzz-corpus/main.go index 547103c805..8a06546331 100644 --- a/internal/cmd/build-oss-fuzz-corpus/main.go +++ b/internal/cmd/build-oss-fuzz-corpus/main.go @@ -79,7 +79,7 @@ func jsonToBytes(ej, ejType, testDesc string) ([]byte, error) { func seedExtJSON(zw *zip.Writer, extJSON string, extJSONType string, desc string) { jbytes, err := jsonToBytes(extJSON, extJSONType, desc) if err != nil { - log.Fatalf("failed to convert JSON to bytes: %v", err) + log.Panicf("failed to convert JSON to bytes: %v", err) } // Use a SHA256 hash of the BSON bytes for the filename. This isn't an oss-fuzz requirement, it @@ -88,12 +88,12 @@ func seedExtJSON(zw *zip.Writer, extJSON string, extJSONType string, desc string f, err := zw.Create(zipFile) if err != nil { - log.Fatalf("error creating zip file: %v", err) + log.Panicf("error creating zip file: %v", err) } _, err = f.Write(jbytes) if err != nil { - log.Fatalf("failed to write file: %s into zip file: %v", zipFile, err) + log.Panicf("failed to write file: %s into zip file: %v", zipFile, err) } } @@ -125,7 +125,7 @@ func seedTestCase(zw *zip.Writer, tcase []*validityTestCase) { func seedBSONCorpus(zw *zip.Writer) { fileNames, err := findJSONFilesInDir(dataDir) if err != nil { - log.Fatalf("failed to find JSON files in directory %q: %v", dataDir, err) + log.Panicf("failed to find JSON files in directory %q: %v", dataDir, err) } for _, fileName := range fileNames { @@ -133,7 +133,7 @@ func seedBSONCorpus(zw *zip.Writer) { file, err := os.Open(filePath) if err != nil { - log.Fatalf("failed to open file %q: %v", filePath, err) + log.Panicf("failed to open file %q: %v", filePath, err) } tc := struct { @@ -141,7 +141,7 @@ func seedBSONCorpus(zw *zip.Writer) { }{} if err := json.NewDecoder(file).Decode(&tc); err != nil { - log.Fatalf("failed to decode file %q: %v", filePath, err) + log.Panicf("failed to decode file %q: %v", filePath, err) } seedTestCase(zw, tc.Valid) @@ -153,18 +153,18 @@ func seedBSONCorpus(zw *zip.Writer) { func main() { seedCorpus := os.Args[1] if filepath.Ext(seedCorpus) != ".zip" { - log.Fatalf("expected zip file .zip, got %s", seedCorpus) + log.Panicf("expected zip file .zip, got %s", seedCorpus) } zipFile, err := os.Create(seedCorpus) if err != nil { - log.Fatalf("failed creating zip file: %v", err) + log.Panicf("failed creating zip file: %v", err) } defer func() { err := zipFile.Close() if err != nil { - log.Fatalf("failed to close zip file: %v", err) + log.Panicf("failed to close zip file: %v", err) } }() @@ -172,6 +172,6 @@ func main() { seedBSONCorpus(zipWriter) if err := zipWriter.Close(); err != nil { - log.Fatalf("failed to close zip writer: %v", err) + log.Panicf("failed to close zip writer: %v", err) } } diff --git a/internal/cmd/parse-api-report/main.go b/internal/cmd/parse-api-report/main.go index cd372e7498..7864ea75c2 100644 --- a/internal/cmd/parse-api-report/main.go +++ b/internal/cmd/parse-api-report/main.go @@ -23,7 +23,7 @@ func main() { // open file to read fRead, err := os.Open("api-report.txt") if err != nil { - log.Fatal(err) + log.Panic(err) } // remember to close the file at the end of the program defer fRead.Close() @@ -31,7 +31,7 @@ func main() { // open file to write fWrite, err := os.Create("api-report.md") if err != nil { - log.Fatal(err) + log.Panic(err) } // remember to close the file at the end of the program defer fWrite.Close() @@ -57,7 +57,7 @@ func main() { } if strings.Contains(line, "go.mongodb.org/mongo-driver") { - line = strings.Replace(line, "go.mongodb.org/mongo-driver", ".", -1) + line = strings.ReplaceAll(line, "go.mongodb.org/mongo-driver", ".") line = "##" + line } if !suppress { @@ -74,10 +74,10 @@ func main() { } if !foundSummary { - log.Fatal("Could not parse api summary") + log.Panic("Could not parse api summary") } if err := scanner.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/internal/cmd/testentauth/main.go b/internal/cmd/testentauth/main.go index c073dc3175..cb0bce11a8 100644 --- a/internal/cmd/testentauth/main.go +++ b/internal/cmd/testentauth/main.go @@ -24,17 +24,17 @@ func main() { client, err := mongo.Connect( options.Client().ApplyURI(uri).SetCompressors([]string{compressor})) if err != nil { - log.Fatalf("Error connecting client: %v", err) + log.Panicf("Error connecting client: %v", err) } // Use the defaultauthdb (i.e. the database name after the "/") specified in the connection // string to run the count operation. cs, err := connstring.Parse(uri) if err != nil { - log.Fatalf("Error parsing connection string: %v", err) + log.Panicf("Error parsing connection string: %v", err) } if cs.Database == "" { - log.Fatal("Connection string must contain a defaultauthdb.") + log.Panic("Connection string must contain a defaultauthdb.") } coll := client.Database(cs.Database).Collection("test") @@ -44,7 +44,7 @@ func main() { count, err := coll.EstimatedDocumentCount(ctx) if err != nil { - log.Fatalf("failed executing count command: %v", err) + log.Panicf("failed executing count command: %v", err) } log.Println("Count of test collection:", count) } diff --git a/internal/cmd/testoidcauth/main.go b/internal/cmd/testoidcauth/main.go index b8f541be68..f3feff53bb 100644 --- a/internal/cmd/testoidcauth/main.go +++ b/internal/cmd/testoidcauth/main.go @@ -134,7 +134,7 @@ func machine11callbackIsCalled() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -176,7 +176,7 @@ func machine12callbackIsCalledOnlyOneForMultipleConnections() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -288,7 +288,7 @@ func machine23oidcCallbackReturnMissingData() error { callbackCount := 0 countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -321,7 +321,7 @@ func machine23oidcCallbackReturnMissingData() error { } func machine24invalidClientConfigurationWithCallback() error { - _, err := connectWithMachineCBAndProperties(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + _, err := connectWithMachineCBAndProperties(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) return &options.OIDCCredential{ AccessToken: "", @@ -342,7 +342,7 @@ func machine31failureWithCachedTokensFetchANewTokenAndRetryAuth() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -394,7 +394,7 @@ func machine32authFailuresWithoutCachedTokensReturnsAnError() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -438,7 +438,7 @@ func machine33UnexpectedErrorCodeDoesNotClearTheCache() error { return fmt.Errorf("machine_3_3: failed connecting admin client: %v", err) } - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -514,7 +514,7 @@ func machine41ReauthenticationSucceeds() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -581,7 +581,7 @@ func machine42ReadCommandsFailIfReauthenticationFails() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -663,7 +663,7 @@ func machine43WriteCommandsFailIfReauthenticationFails() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithMachineCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithMachineCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -735,7 +735,7 @@ func human11singlePrincipalImplictUsername() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -776,7 +776,7 @@ func human12singlePrincipalExplicitUsername() error { callbackCount := 0 var callbackFailed error countMutex := sync.Mutex{} - cb := func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + cb := func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -822,7 +822,7 @@ func human13mulitplePrincipalUser1() error { callbackCount := 0 var callbackFailed error countMutex := sync.Mutex{} - cb := func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + cb := func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -868,7 +868,7 @@ func human14mulitplePrincipalUser2() error { callbackCount := 0 var callbackFailed error countMutex := sync.Mutex{} - cb := func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + cb := func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -915,7 +915,7 @@ func human15mulitplePrincipalNoUser() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriMulti, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriMulti, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -953,7 +953,7 @@ func human15mulitplePrincipalNoUser() error { func human16allowedHostsBlocked() error { var callbackFailed error { - cb := func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + cb := func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) tokenFile := tokenFile("test_user1") accessToken, err := os.ReadFile(tokenFile) @@ -986,7 +986,7 @@ func human16allowedHostsBlocked() error { } } { - cb := func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + cb := func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) tokenFile := tokenFile("test_user1") accessToken, err := os.ReadFile(tokenFile) @@ -1036,7 +1036,7 @@ func human21validCallbackInputs() error { var callbackFailed error countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(_ context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1083,7 +1083,7 @@ func human22CallbackReturnsMissingData() error { callbackCount := 0 countMutex := sync.Mutex{} - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1121,7 +1121,7 @@ func human23RefreshTokenIsPassedToCallback() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(_ context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1189,7 +1189,7 @@ func human31usesSpeculativeAuth() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { // the callback should not even be called due to spec auth. return &options.OIDCCredential{}, nil }) @@ -1250,7 +1250,7 @@ func human32doesNotUseSpecualtiveAuth() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { t := time.Now().Add(time.Hour) tokenFile := tokenFile("test_user1") accessToken, err := os.ReadFile(tokenFile) @@ -1311,7 +1311,7 @@ func human42ReauthenticationSucceedsNoRefreshToken() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1388,7 +1388,7 @@ func human43ReauthenticationSucceedsAfterRefreshFails() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ @@ -1466,7 +1466,7 @@ func human44ReauthenticationFails() error { } defer func() { _ = adminClient.Disconnect(context.Background()) }() - client, err := connectWithHumanCB(uriSingle, func(ctx context.Context, args *options.OIDCArgs) (*options.OIDCCredential, error) { + client, err := connectWithHumanCB(uriSingle, func(context.Context, *options.OIDCArgs) (*options.OIDCCredential, error) { countMutex.Lock() defer countMutex.Unlock() callbackCount++ diff --git a/internal/decimal128/decinal128.go b/internal/decimal128/decinal128.go index 337ed366ae..2767e4457b 100644 --- a/internal/decimal128/decinal128.go +++ b/internal/decimal128/decinal128.go @@ -55,7 +55,6 @@ func String(h, l uint64) string { // Bits: 1*sign 2*ignored 14*exponent 111*significand. // Implicit 0b100 prefix in significand. exp = int(h >> 47 & (1<<14 - 1)) - //high = 4<<47 | d.h&(1<<47-1) // Spec says all of these values are out of range. high, low = 0, 0 } else { diff --git a/internal/docexamples/examples_test.go b/internal/docexamples/examples_test.go index ab42782b61..9046971d90 100644 --- a/internal/docexamples/examples_test.go +++ b/internal/docexamples/examples_test.go @@ -32,11 +32,11 @@ func TestMain(m *testing.M) { } if err := mtest.Setup(); err != nil { - log.Fatal(err) + log.Panic(err) } defer os.Exit(m.Run()) if err := mtest.Teardown(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/internal/driverutil/description.go b/internal/driverutil/description.go index f0ab6ab846..0d06aee4f7 100644 --- a/internal/driverutil/description.go +++ b/internal/driverutil/description.go @@ -72,7 +72,6 @@ func EqualServers(srv1, srv2 description.Server) bool { } } - //if !s.WireVersion.Equals(other.WireVersion) { if !equalWireVersion(srv1.WireVersion, srv2.WireVersion) { return false } @@ -100,8 +99,6 @@ func EqualServers(srv1, srv2 description.Server) bool { return true } - //return s.TopologyVersion.CompareToIncoming(other.TopologyVersion) == 0 - return CompareTopologyVersions(srv1.TopologyVersion, srv2.TopologyVersion) == 0 } @@ -451,21 +448,23 @@ func NewServerDescription(addr address.Address, response bson.Raw) description.S desc.Kind = description.ServerKindStandalone - if isReplicaSet { + switch { + case isReplicaSet: desc.Kind = description.ServerKindRSGhost - } else if desc.SetName != "" { - if isWritablePrimary { + case desc.SetName != "": + switch { + case isWritablePrimary: desc.Kind = description.ServerKindRSPrimary - } else if hidden { + case hidden: desc.Kind = description.ServerKindRSMember - } else if secondary { + case secondary: desc.Kind = description.ServerKindRSSecondary - } else if arbiterOnly { + case arbiterOnly: desc.Kind = description.ServerKindRSArbiter - } else { + default: desc.Kind = description.ServerKindRSMember } - } else if msg == "isdbgrid" { + case msg == "isdbgrid": desc.Kind = description.ServerKindMongos } diff --git a/internal/integration/clam_prose_test.go b/internal/integration/clam_prose_test.go index 00dc670b13..f4aaf7eb7c 100644 --- a/internal/integration/clam_prose_test.go +++ b/internal/integration/clam_prose_test.go @@ -346,7 +346,7 @@ func TestCommandLoggingAndMonitoringProse(t *testing.T) { sinkCtx, sinkCancel := context.WithDeadline(ctx, time.Now().Add(deadline)) defer sinkCancel() - validator := func(order int, level int, msg string, keysAndValues ...interface{}) error { + validator := func(order int, _ int, _ string, keysAndValues ...interface{}) error { // If the order exceeds the length of the // "orderedCaseValidators," then throw an error. if order >= len(tcase.orderedLogValidators) { diff --git a/internal/integration/client_side_encryption_prose_test.go b/internal/integration/client_side_encryption_prose_test.go index 40a7e74936..cdd1605472 100644 --- a/internal/integration/client_side_encryption_prose_test.go +++ b/internal/integration/client_side_encryption_prose_test.go @@ -1951,7 +1951,7 @@ func TestClientSideEncryptionProse(t *testing.T) { assert.True(t, correctError, "expected error to contain %q, got: %v", e110000, err) }) - mt.Run("case 2: addKeyAltName()", func(t *mtest.T) { + mt.Run("case 2: addKeyAltName()", func(mt *mtest.T) { defKeyID := initialize() var someNewKeyID bson.Binary diff --git a/internal/integration/collection_test.go b/internal/integration/collection_test.go index 79613bd421..13d95913d0 100644 --- a/internal/integration/collection_test.go +++ b/internal/integration/collection_test.go @@ -1496,7 +1496,7 @@ func TestCollection(t *testing.T) { assert.False(mt, res.Acknowledged) }) - mt.Run("insert many", func(t *mtest.T) { + mt.Run("insert many", func(mt *mtest.T) { docs := []interface{}{ bson.D{{"x", 1}}, bson.D{{"y", 1}}, @@ -1515,7 +1515,7 @@ func TestCollection(t *testing.T) { assert.False(mt, res.Acknowledged) }) - mt.Run("update", func(t *mtest.T) { + mt.Run("update", func(mt *mtest.T) { res, err := mt.Coll.UpdateOne(context.Background(), bson.D{{"x", 1}}, bson.D{{"$set", bson.D{{"x", "2"}}}}) assert.NoError(mt, err) @@ -1573,7 +1573,7 @@ func TestCollection(t *testing.T) { assert.NoError(mt, err) }) - mt.Run("dropping an index", func(t *mtest.T) { + mt.Run("dropping an index", func(mt *mtest.T) { indexModel := mongo.IndexModel{ Keys: bson.M{"username": 1}, Options: options.Index().SetUnique(true).SetName("username_1"), diff --git a/internal/integration/crud_helpers_test.go b/internal/integration/crud_helpers_test.go index c06bf7670f..595fc134bf 100644 --- a/internal/integration/crud_helpers_test.go +++ b/internal/integration/crud_helpers_test.go @@ -1066,7 +1066,7 @@ func executeWithTransaction(mt *mtest.T, sess *mongo.Session, args bson.Raw) err assert.Nil(mt, err, "error creating withTransactionArgs: %v", err) opts := createTransactionOptions(mt, testArgs.Options) - _, err = sess.WithTransaction(context.Background(), func(sc context.Context) (interface{}, error) { + _, err = sess.WithTransaction(context.Background(), func(_ context.Context) (interface{}, error) { err := runWithTransactionOperations(mt, testArgs.Callback.Operations, sess) return nil, err }, opts) @@ -1616,11 +1616,11 @@ func verifyInsertManyResult(mt *mtest.T, actualResult *mongo.InsertManyResult, e } assert.NotNil(mt, actualResult, "expected InsertMany result %v but got nil", expectedResult) - var expected struct{ InsertedIds map[string]interface{} } + var expected struct{ InsertedIDs map[string]interface{} } err := bson.Unmarshal(expectedResult.(bson.Raw), &expected) assert.Nil(mt, err, "error creating expected InsertMany result: %v", err) - for _, val := range expected.InsertedIds { + for _, val := range expected.InsertedIDs { var found bool for _, inserted := range actualResult.InsertedIDs { if val == inserted { diff --git a/internal/integration/csot_prose_test.go b/internal/integration/csot_prose_test.go index 1997a6824c..28dcef7015 100644 --- a/internal/integration/csot_prose_test.go +++ b/internal/integration/csot_prose_test.go @@ -88,7 +88,7 @@ func TestCSOTProse(t *testing.T) { mtOpts := mtest.NewOptions().ClientOptions(cliOpts).CreateCollection(false) mt.RunOpts("serverSelectionTimeoutMS honored if timeoutMS is not set", mtOpts, func(mt *mtest.T) { // TODO(GODRIVER-3266): Why do parallel tests fail on windows builds? - //mt.Parallel() + // mt.Parallel() callback := func() bool { err := mt.Client.Ping(context.Background(), nil) diff --git a/internal/integration/errors_test.go b/internal/integration/errors_test.go index e81f8ec9e8..cfc4715512 100644 --- a/internal/integration/errors_test.go +++ b/internal/integration/errors_test.go @@ -393,7 +393,7 @@ func TestErrors(t *testing.T) { }) }) mt.Run("error helpers", func(mt *mtest.T) { - //IsDuplicateKeyError + // IsDuplicateKeyError mt.Run("IsDuplicateKeyError", func(mt *mtest.T) { testCases := []struct { name string @@ -472,7 +472,7 @@ func TestErrors(t *testing.T) { }) } }) - //IsNetworkError + // IsNetworkError mt.Run("IsNetworkError", func(mt *mtest.T) { const networkLabel = "NetworkError" const otherLabel = "other" @@ -493,7 +493,7 @@ func TestErrors(t *testing.T) { }) } }) - //IsTimeout + // IsTimeout mt.Run("IsTimeout", func(mt *mtest.T) { testCases := []struct { name string diff --git a/internal/integration/main_test.go b/internal/integration/main_test.go index 325318934f..8f0f5cb4ac 100644 --- a/internal/integration/main_test.go +++ b/internal/integration/main_test.go @@ -26,10 +26,10 @@ func TestMain(m *testing.M) { } if err := mtest.Setup(); err != nil { - log.Fatal(err) + log.Panic(err) } defer os.Exit(m.Run()) if err := mtest.Teardown(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/internal/integration/mtest/mongotest.go b/internal/integration/mtest/mongotest.go index 9f4543ba04..1e3879b9ef 100644 --- a/internal/integration/mtest/mongotest.go +++ b/internal/integration/mtest/mongotest.go @@ -609,7 +609,7 @@ func (t *T) CloneCollection(opts *options.CollectionOptionsBuilder) { func sanitizeCollectionName(db string, coll string) string { // Collections can't have "$" in their names, so we substitute it with "%". - coll = strings.Replace(coll, "$", "%", -1) + coll = strings.ReplaceAll(coll, "$", "%") // Namespaces can only have 120 bytes max. if len(db+"."+coll) >= 120 { diff --git a/internal/integration/mtest/setup.go b/internal/integration/mtest/setup.go index 5220d458e1..38fe5b84bf 100644 --- a/internal/integration/mtest/setup.go +++ b/internal/integration/mtest/setup.go @@ -332,11 +332,12 @@ func addServerlessAuthCredentials(uri string) (string, error) { var scheme string // remove the scheme - if strings.HasPrefix(uri, "mongodb+srv://") { + switch { + case strings.HasPrefix(uri, "mongodb+srv://"): scheme = "mongodb+srv://" - } else if strings.HasPrefix(uri, "mongodb://") { + case strings.HasPrefix(uri, "mongodb://"): scheme = "mongodb://" - } else { + default: return "", errors.New(`scheme must be "mongodb" or "mongodb+srv"`) } diff --git a/internal/integration/retryable_writes_prose_test.go b/internal/integration/retryable_writes_prose_test.go index 5e67d74ee8..355a4858d3 100644 --- a/internal/integration/retryable_writes_prose_test.go +++ b/internal/integration/retryable_writes_prose_test.go @@ -242,7 +242,7 @@ func TestRetryableWritesProse(t *testing.T) { // shutdownInProgressErrorCode actually configures the "NoWritablePrimary" fail command. var secondFailPointConfigured bool - //Set a command monitor on the client that configures a failpoint with a "NoWritesPerformed" + // Set a command monitor on the client that configures a failpoint with a "NoWritesPerformed" monitor.Succeeded = func(_ context.Context, evt *event.CommandSucceededEvent) { var errorCode int32 if wce := evt.Reply.Lookup("writeConcernError"); wce.Type == bson.TypeEmbeddedDocument { diff --git a/internal/integration/sdam_prose_test.go b/internal/integration/sdam_prose_test.go index cff676b455..776c63dd6e 100644 --- a/internal/integration/sdam_prose_test.go +++ b/internal/integration/sdam_prose_test.go @@ -214,10 +214,10 @@ func TestServerHeartbeatStartedEvent(t *testing.T) { 1*time.Second, topology.WithServerMonitor(func(*event.ServerMonitor) *event.ServerMonitor { return &event.ServerMonitor{ - ServerHeartbeatStarted: func(e *event.ServerHeartbeatStartedEvent) { + ServerHeartbeatStarted: func(*event.ServerHeartbeatStartedEvent) { events <- "serverHeartbeatStartedEvent" }, - ServerHeartbeatFailed: func(e *event.ServerHeartbeatFailedEvent) { + ServerHeartbeatFailed: func(*event.ServerHeartbeatFailedEvent) { events <- "serverHeartbeatFailedEvent" }, } diff --git a/internal/integration/unified/context.go b/internal/integration/unified/context.go index 151f727fef..c84651b8c3 100644 --- a/internal/integration/unified/context.go +++ b/internal/integration/unified/context.go @@ -48,11 +48,9 @@ func newTestContext( return ctx } -func addFailPoint(ctx context.Context, failPoint string, client *mongo.Client) error { +func addFailPoint(ctx context.Context, failPoint string, client *mongo.Client) { failPoints := ctx.Value(failPointsKey).(map[string]*mongo.Client) - failPoints[failPoint] = client - return nil } func addTargetedFailPoint(ctx context.Context, failPoint string, host string) error { diff --git a/internal/integration/unified/logger.go b/internal/integration/unified/logger.go index c951cc2ac2..8c9a0700fa 100644 --- a/internal/integration/unified/logger.go +++ b/internal/integration/unified/logger.go @@ -70,7 +70,7 @@ func (log *Logger) Info(level int, msg string, args ...interface{}) { // Add the Diff back to the level, as there is no need to create a // logging offset. - level = level + logger.DiffToInfo + level += logger.DiffToInfo logMessage, err := newLogMessage(level, msg, args...) if err != nil { diff --git a/internal/integration/unified/main_test.go b/internal/integration/unified/main_test.go index dfacb3c786..fb0338ebc3 100644 --- a/internal/integration/unified/main_test.go +++ b/internal/integration/unified/main_test.go @@ -26,10 +26,10 @@ func TestMain(m *testing.M) { } if err := mtest.Setup(); err != nil { - log.Fatal(err) + log.Panic(err) } defer os.Exit(m.Run()) if err := mtest.Teardown(); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/internal/integration/unified/testrunner_operation.go b/internal/integration/unified/testrunner_operation.go index e6eff60816..bb1f9ecac6 100644 --- a/internal/integration/unified/testrunner_operation.go +++ b/internal/integration/unified/testrunner_operation.go @@ -104,7 +104,8 @@ func executeTestRunnerOperation(ctx context.Context, op *operation, loopDone <-c if err := mtest.SetRawFailPoint(fpDoc, client.Client); err != nil { return err } - return addFailPoint(ctx, fpDoc.Index(0).Value().StringValue(), client.Client) + addFailPoint(ctx, fpDoc.Index(0).Value().StringValue(), client.Client) + return nil case "targetedFailPoint": sessID := lookupString(args, "session") sess, err := entities(ctx).session(sessID) @@ -119,7 +120,7 @@ func executeTestRunnerOperation(ctx context.Context, op *operation, loopDone <-c targetHost := clientSession.PinnedServerAddr.String() fpDoc := args.Lookup("failPoint").Document() - commandFn := func(ctx context.Context, client *mongo.Client) error { + commandFn := func(_ context.Context, client *mongo.Client) error { return mtest.SetRawFailPoint(fpDoc, client) } diff --git a/internal/integtest/integtest.go b/internal/integtest/integtest.go index 40f99d2932..2f09c4dc30 100644 --- a/internal/integtest/integtest.go +++ b/internal/integtest/integtest.go @@ -208,11 +208,12 @@ func AddServerlessAuthCredentials(uri string) (string, error) { var scheme string // remove the scheme - if strings.HasPrefix(uri, "mongodb+srv://") { + switch { + case strings.HasPrefix(uri, "mongodb+srv://"): scheme = "mongodb+srv://" - } else if strings.HasPrefix(uri, "mongodb://") { + case strings.HasPrefix(uri, "mongodb://"): scheme = "mongodb://" - } else { + default: return "", errors.New(`scheme must be "mongodb" or "mongodb+srv"`) } diff --git a/internal/serverselector/server_selector_test.go b/internal/serverselector/server_selector_test.go index bc330e27c7..886c3fe994 100644 --- a/internal/serverselector/server_selector_test.go +++ b/internal/serverselector/server_selector_test.go @@ -554,7 +554,7 @@ func BenchmarkLatencySelector(b *testing.B) { }{ { name: "AllFit", - serversHook: func(servers []description.Server) {}, + serversHook: func([]description.Server) {}, }, { name: "AllButOneFit", @@ -597,8 +597,8 @@ func BenchmarkLatencySelector(b *testing.B) { servers[i] = s } bcase.serversHook(servers) - //this will make base 1 sec latency < min (0.5) + conf (1) - //and high latency 2 higher than the threshold + // this will make base 1 sec latency < min (0.5) + conf (1) + // and high latency 2 higher than the threshold servers[99].AverageRTT = 500 * time.Millisecond c := description.Topology{ Kind: description.TopologyKindSharded, @@ -623,7 +623,7 @@ func BenchmarkSelector_Sharded(b *testing.B) { }{ { name: "AllFit", - serversHook: func(servers []description.Server) {}, + serversHook: func([]description.Server) {}, }, { name: "AllButOneFit", diff --git a/mongo/client_examples_test.go b/mongo/client_examples_test.go index c939a77ceb..2ae670f282 100644 --- a/mongo/client_examples_test.go +++ b/mongo/client_examples_test.go @@ -23,18 +23,18 @@ func ExampleClient() { client, err := mongo.Connect( options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { - log.Fatal(err) + log.Panic(err) } }() collection := client.Database("db").Collection("coll") result, err := collection.InsertOne(context.TODO(), bson.D{{"x", 1}}) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("inserted ID: %v\n", result.InsertedID) } @@ -46,11 +46,11 @@ func ExampleConnect_ping() { clientOpts := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { - log.Fatal(err) + log.Panic(err) } }() @@ -59,7 +59,7 @@ func ExampleConnect_ping() { // reduces application resiliency as the server may be temporarily // unavailable when Ping is called. if err = client.Ping(context.TODO(), readpref.Primary()); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -75,7 +75,7 @@ func ExampleConnect_replicaSet() { "mongodb://localhost:27017,localhost:27018/?replicaSet=replset") client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -89,7 +89,7 @@ func ExampleConnect_sharded() { "mongodb://localhost:27017,localhost:27018") client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -107,7 +107,7 @@ func ExampleConnect_sRV() { clientOpts := options.Client().ApplyURI("mongodb+srv://mongodb.example.com") client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -121,7 +121,7 @@ func ExampleConnect_direct() { "mongodb://localhost:27017/?connect=direct") client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -144,7 +144,7 @@ func ExampleConnect_sCRAM() { SetAuth(credential) client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -180,7 +180,7 @@ func ExampleConnect_x509() { client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -205,7 +205,7 @@ func ExampleConnect_pLAIN() { client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } @@ -240,7 +240,7 @@ func ExampleConnect_kerberos() { client, err := mongo.Connect(clientOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } _ = client } diff --git a/mongo/client_side_encryption_examples_test.go b/mongo/client_side_encryption_examples_test.go index 7e88d42925..0ca9e2a5aa 100644 --- a/mongo/client_side_encryption_examples_test.go +++ b/mongo/client_side_encryption_examples_test.go @@ -22,7 +22,7 @@ func Example_clientSideEncryption() { // encryption key. localKey := make([]byte, 96) if _, err := rand.Read(localKey); err != nil { - log.Fatal(err) + log.Panic(err) } kmsProviders := map[string]map[string]interface{}{ "local": { @@ -40,28 +40,28 @@ func Example_clientSideEncryption() { SetAutoEncryptionOptions(autoEncryptionOpts) client, err := Connect(clientOpts) if err != nil { - log.Fatalf("Connect error: %v", err) + log.Panicf("Connect error: %v", err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { - log.Fatalf("Disconnect error: %v", err) + log.Panicf("Disconnect error: %v", err) } }() collection := client.Database("test").Collection("coll") if err := collection.Drop(context.TODO()); err != nil { - log.Fatalf("Collection.Drop error: %v", err) + log.Panicf("Collection.Drop error: %v", err) } _, err = collection.InsertOne( context.TODO(), bson.D{{"encryptedField", "123456789"}}) if err != nil { - log.Fatalf("InsertOne error: %v", err) + log.Panicf("InsertOne error: %v", err) } res, err := collection.FindOne(context.TODO(), bson.D{}).Raw() if err != nil { - log.Fatalf("FindOne error: %v", err) + log.Panicf("FindOne error: %v", err) } fmt.Println(res) } @@ -79,23 +79,23 @@ func Example_clientSideEncryptionCreateKey() { SetKmsProviders(kmsProviders) keyVaultClient, err := Connect(options.Client().ApplyURI(uri)) if err != nil { - log.Fatalf("Connect error for keyVaultClient: %v", err) + log.Panicf("Connect error for keyVaultClient: %v", err) } clientEnc, err := NewClientEncryption(keyVaultClient, clientEncryptionOpts) if err != nil { - log.Fatalf("NewClientEncryption error: %v", err) + log.Panicf("NewClientEncryption error: %v", err) } defer func() { // this will disconnect the keyVaultClient as well if err = clientEnc.Close(context.TODO()); err != nil { - log.Fatalf("Close error: %v", err) + log.Panicf("Close error: %v", err) } }() // Create a new data key and encode it as base64 dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), "local") if err != nil { - log.Fatalf("CreateDataKey error: %v", err) + log.Panicf("CreateDataKey error: %v", err) } dataKeyBase64 := base64.StdEncoding.EncodeToString(dataKeyID.Data) @@ -122,7 +122,7 @@ func Example_clientSideEncryptionCreateKey() { var schemaDoc bson.Raw err = bson.UnmarshalExtJSON([]byte(schema), true, &schemaDoc) if err != nil { - log.Fatalf("UnmarshalExtJSON error: %v", err) + log.Panicf("UnmarshalExtJSON error: %v", err) } // Configure a Client with auto encryption using the new schema @@ -141,7 +141,7 @@ func Example_clientSideEncryptionCreateKey() { SetAutoEncryptionOptions(autoEncryptionOpts) client, err := Connect(clientOptions) if err != nil { - log.Fatalf("Connect error for encrypted client: %v", err) + log.Panicf("Connect error for encrypted client: %v", err) } defer func() { _ = client.Disconnect(context.TODO()) diff --git a/mongo/crud_examples_test.go b/mongo/crud_examples_test.go index 27b2f9bafe..159b5cb761 100644 --- a/mongo/crud_examples_test.go +++ b/mongo/crud_examples_test.go @@ -31,7 +31,7 @@ func ExampleClient_ListDatabaseNames() { context.TODO(), bson.D{{"empty", false}}) if err != nil { - log.Fatal(err) + log.Panic(err) } for _, db := range result { @@ -52,7 +52,7 @@ func ExampleClient_Watch() { mongo.Pipeline{matchStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Print out all change stream events in the order they're received. @@ -95,7 +95,7 @@ func ExampleDatabase_CreateCollection() { err := db.CreateCollection(context.TODO(), "users", opts) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -123,7 +123,7 @@ func ExampleDatabase_CreateView() { err := db.CreateView(context.TODO(), "usernames", "users", pipeline, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -135,7 +135,7 @@ func ExampleDatabase_ListCollectionNames() { context.TODO(), bson.D{{"options.capped", true}}) if err != nil { - log.Fatal(err) + log.Panic(err) } for _, coll := range result { @@ -155,7 +155,7 @@ func ExampleDatabase_RunCommand() { var result bson.M err := db.RunCommand(context.TODO(), command, opts).Decode(&result) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(result) } @@ -173,7 +173,7 @@ func ExampleDatabase_Watch() { mongo.Pipeline{matchStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Print out all change stream events in the order they're received. @@ -207,14 +207,14 @@ func ExampleCollection_Aggregate() { mongo.Pipeline{groupStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Get a list of all returned documents and print them out. // See the mongo.Cursor documentation for more examples of using cursors. var results []bson.M if err = cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } for _, result := range results { fmt.Printf( @@ -252,7 +252,7 @@ func ExampleCollection_BulkWrite() { opts := options.BulkWrite().SetOrdered(false) res, err := coll.BulkWrite(context.TODO(), models, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf( @@ -272,7 +272,7 @@ func ExampleCollection_CountDocuments() { // Count the number of times the name "Bob" appears in the collection. count, err := coll.CountDocuments(ctx, bson.D{{"name", "Bob"}}, nil) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("name Bob appears in %v documents", count) } @@ -290,7 +290,7 @@ func ExampleCollection_DeleteMany() { }) res, err := coll.DeleteMany(context.TODO(), bson.D{{"name", "bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("deleted %v documents\n", res.DeletedCount) } @@ -308,7 +308,7 @@ func ExampleCollection_DeleteOne() { }) res, err := coll.DeleteOne(context.TODO(), bson.D{{"name", "bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("deleted %v documents\n", res.DeletedCount) } @@ -326,12 +326,12 @@ func ExampleCollection_Distinct() { filter := bson.D{{"age", bson.D{{"$gt", 25}}}} res := coll.Distinct(ctx, "name", filter) if err := res.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } values, err := res.Raw() if err != nil { - log.Fatal(err) + log.Panic(err) } for _, value := range values { @@ -350,7 +350,7 @@ func ExampleCollection_EstimatedDocumentCount() { // Get and print an estimated of the number of documents in the collection. count, err := coll.EstimatedDocumentCount(ctx, nil) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("estimated document count: %v", count) } @@ -364,14 +364,14 @@ func ExampleCollection_Find() { opts := options.Find().SetSort(bson.D{{"age", 1}}) cursor, err := coll.Find(context.TODO(), bson.D{{"name", "Bob"}}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Get a list of all returned documents and print them out. // See the mongo.Cursor documentation for more examples of using cursors. var results []bson.M if err = cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } for _, result := range results { fmt.Println(result) @@ -398,7 +398,7 @@ func ExampleCollection_FindOne() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("found document %v", result) } @@ -424,7 +424,7 @@ func ExampleCollection_FindOneAndDelete() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("deleted document %v", deletedDocument) } @@ -453,7 +453,7 @@ func ExampleCollection_FindOneAndReplace() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("replaced document %v", replacedDocument) } @@ -482,7 +482,7 @@ func ExampleCollection_FindOneAndUpdate() { if errors.Is(err, mongo.ErrNoDocuments) { return } - log.Fatal(err) + log.Panic(err) } fmt.Printf("updated document %v", updatedDocument) } @@ -500,7 +500,7 @@ func ExampleCollection_InsertMany() { opts := options.InsertMany().SetOrdered(false) res, err := coll.InsertMany(context.TODO(), docs, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("inserted documents with IDs %v\n", res.InsertedIDs) } @@ -511,7 +511,7 @@ func ExampleCollection_InsertOne() { // Insert the document {name: "Alice"}. res, err := coll.InsertOne(context.TODO(), bson.D{{"name", "Alice"}}) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("inserted document with ID %v\n", res.InsertedID) } @@ -529,7 +529,7 @@ func ExampleCollection_ReplaceOne() { replacement := bson.D{{"location", "NYC"}} result, err := coll.ReplaceOne(context.TODO(), filter, replacement, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } if result.MatchedCount != 0 { @@ -551,7 +551,7 @@ func ExampleCollection_UpdateMany() { result, err := coll.UpdateMany(context.TODO(), filter, update) if err != nil { - log.Fatal(err) + log.Panic(err) } if result.MatchedCount != 0 { @@ -574,7 +574,7 @@ func ExampleCollection_UpdateOne() { result, err := coll.UpdateOne(context.TODO(), filter, update, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } if result.MatchedCount != 0 { @@ -599,7 +599,7 @@ func ExampleCollection_Watch() { mongo.Pipeline{matchStage}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } // Print out all change stream events in the order they're received. @@ -626,7 +626,7 @@ func ExampleWithSession() { opts := options.Session().SetDefaultTransactionOptions(txnOpts) sess, err := client.StartSession(opts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer sess.EndSession(context.TODO()) @@ -675,7 +675,7 @@ func ExampleWithSession() { return sess.CommitTransaction(context.Background()) }) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -734,7 +734,7 @@ func ExampleClient_UseSessionWithOptions() { return sess.CommitTransaction(context.Background()) }) if err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -752,7 +752,7 @@ func ExampleClient_StartSession_withTransaction() { opts := options.Session().SetDefaultTransactionOptions(txnOpts) sess, err := client.StartSession(opts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer sess.EndSession(context.TODO()) @@ -784,7 +784,7 @@ func ExampleClient_StartSession_withTransaction() { }, txnOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("result: %v\n", result) } @@ -847,7 +847,7 @@ func ExampleCursor_All() { var results []bson.M if err := cursor.All(context.TODO(), &results); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(results) } @@ -862,12 +862,12 @@ func ExampleCursor_Next() { // A new result variable should be declared for each document. var result bson.M if err := cursor.Decode(&result); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(result) } if err := cursor.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -882,7 +882,7 @@ func ExampleCursor_TryNext() { // A new result variable should be declared for each document. var result bson.M if err := cursor.Decode(&result); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(result) continue @@ -892,7 +892,7 @@ func ExampleCursor_TryNext() { // cursor was exhausted and was closed, or an error occurred. TryNext // should only be called again for the empty batch case. if err := cursor.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } if cursor.ID() == 0 { break @@ -955,12 +955,12 @@ func ExampleChangeStream_Next() { // A new event variable should be declared for each event. var event bson.M if err := stream.Decode(&event); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(event) } if err := stream.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -976,7 +976,7 @@ func ExampleChangeStream_TryNext() { // A new event variable should be declared for each event. var event bson.M if err := stream.Decode(&event); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(event) continue @@ -986,7 +986,7 @@ func ExampleChangeStream_TryNext() { // change stream was closed by the server, or an error occurred. TryNext // should only be called again for the empty batch case. if err := stream.Err(); err != nil { - log.Fatal(err) + log.Panic(err) } if stream.ID() == 0 { break @@ -1031,7 +1031,7 @@ func ExampleChangeStream_ResumeToken() { opts := options.ChangeStream().SetResumeAfter(resumeToken) newStream, err := newClient.Watch(context.TODO(), mongo.Pipeline{}, opts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer newStream.Close(context.TODO()) } @@ -1060,7 +1060,7 @@ func ExampleIndexView_CreateMany() { // run on the server names, err := indexView.CreateMany(context.TODO(), models, nil) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("created indexes %v\n", names) @@ -1076,13 +1076,13 @@ func ExampleIndexView_List() { cursor, err := indexView.List(ctx, nil) if err != nil { - log.Fatal(err) + log.Panic(err) } // Get a slice of all indexes returned and print them out. var results []bson.M if err = cursor.All(ctx, &results); err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Println(results) } diff --git a/mongo/cursor_test.go b/mongo/cursor_test.go index 0d49d4b585..4ce9c463a5 100644 --- a/mongo/cursor_test.go +++ b/mongo/cursor_test.go @@ -100,11 +100,6 @@ func (tbc *testBatchCursor) SetComment(interface{}) {} func (tbc *testBatchCursor) SetMaxAwaitTime(time.Duration) {} func TestCursor(t *testing.T) { - t.Run("loops until docs available", func(t *testing.T) {}) - t.Run("returns false on context cancellation", func(t *testing.T) {}) - t.Run("returns false if error occurred", func(t *testing.T) {}) - t.Run("returns false if ID is zero and no more docs", func(t *testing.T) {}) - t.Run("TestAll", func(t *testing.T) { t.Run("errors if argument is not pointer to slice", func(t *testing.T) { cursor, err := newCursor(newTestBatchCursor(1, 5), nil, nil) diff --git a/mongo/gridfs_bucket.go b/mongo/gridfs_bucket.go index 988f08e2a2..65fd7bc29b 100644 --- a/mongo/gridfs_bucket.go +++ b/mongo/gridfs_bucket.go @@ -443,7 +443,7 @@ func numericalIndexDocsEqual(expected, actual bsoncore.Document) (bool, error) { actualInt, actualOK := actualVal.AsInt64OK() expectedInt, expectedOK := expectedVal.AsInt64OK() - //GridFS indexes always have numeric values + // GridFS indexes always have numeric values if !actualOK || !expectedOK { return false, nil } diff --git a/mongo/gridfs_examples_test.go b/mongo/gridfs_examples_test.go index fde726031b..df7e4bb5b3 100644 --- a/mongo/gridfs_examples_test.go +++ b/mongo/gridfs_examples_test.go @@ -35,16 +35,16 @@ func ExampleGridFSBucket_OpenUploadStream() { uploadStream, err := bucket.OpenUploadStream(ctx, "filename", uploadOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err = uploadStream.Close(); err != nil { - log.Fatal(err) + log.Panic(err) } }() if _, err = uploadStream.Write(fileContent); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -62,7 +62,7 @@ func ExampleGridFSBucket_UploadFromStream() { bytes.NewBuffer(fileContent), uploadOpts) if err != nil { - log.Fatal(err) + log.Panic(err) } fmt.Printf("new file created with ID %s", fileID) @@ -79,17 +79,17 @@ func ExampleGridFSBucket_OpenDownloadStream() { downloadStream, err := bucket.OpenDownloadStream(ctx, fileID) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err := downloadStream.Close(); err != nil { - log.Fatal(err) + log.Panic(err) } }() fileBuffer := bytes.NewBuffer(nil) if _, err := io.Copy(fileBuffer, downloadStream); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -101,7 +101,7 @@ func ExampleGridFSBucket_DownloadToStream() { fileBuffer := bytes.NewBuffer(nil) if _, err := bucket.DownloadToStream(ctx, fileID, fileBuffer); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -110,7 +110,7 @@ func ExampleGridFSBucket_Delete() { var fileID bson.ObjectID if err := bucket.Delete(context.Background(), fileID); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -123,11 +123,11 @@ func ExampleGridFSBucket_Find() { } cursor, err := bucket.Find(context.Background(), filter) if err != nil { - log.Fatal(err) + log.Panic(err) } defer func() { if err := cursor.Close(context.TODO()); err != nil { - log.Fatal(err) + log.Panic(err) } }() @@ -137,7 +137,7 @@ func ExampleGridFSBucket_Find() { } var foundFiles []gridfsFile if err = cursor.All(context.TODO(), &foundFiles); err != nil { - log.Fatal(err) + log.Panic(err) } for _, file := range foundFiles { @@ -152,7 +152,7 @@ func ExampleGridFSBucket_Rename() { ctx := context.Background() if err := bucket.Rename(ctx, fileID, "new file name"); err != nil { - log.Fatal(err) + log.Panic(err) } } @@ -160,6 +160,6 @@ func ExampleGridFSBucket_Drop() { var bucket *mongo.GridFSBucket if err := bucket.Drop(context.Background()); err != nil { - log.Fatal(err) + log.Panic(err) } } diff --git a/mongo/options/clientoptions.go b/mongo/options/clientoptions.go index 0853773a2b..f3d1b17844 100644 --- a/mongo/options/clientoptions.go +++ b/mongo/options/clientoptions.go @@ -1344,7 +1344,10 @@ func addClientCertFromBytes(cfg *tls.Config, data []byte, keyPasswd string) (str } } var encoded bytes.Buffer - pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: keyBytes}) + err = pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: keyBytes}) + if err != nil { + return "", fmt.Errorf("error encoding private key as PEM: %w", err) + } keyBlock := encoded.Bytes() keyBlocks = append(keyBlocks, keyBlock) start = len(data) - len(remaining) diff --git a/mongo/options/example_test.go b/mongo/options/example_test.go index 0c4ff3c214..49b403498f 100644 --- a/mongo/options/example_test.go +++ b/mongo/options/example_test.go @@ -56,7 +56,7 @@ func ExampleClientOptionsBuilder_SetLoggerOptions_customLogger() { client, err := mongo.Connect(clientOptions) if err != nil { - log.Fatalf("error connecting to MongoDB: %v", err) + log.Panicf("error connecting to MongoDB: %v", err) } defer func() { _ = client.Disconnect(context.TODO()) }() @@ -66,7 +66,7 @@ func ExampleClientOptionsBuilder_SetLoggerOptions_customLogger() { _, err = coll.InsertOne(context.TODO(), map[string]string{"foo": "bar"}) if err != nil { - log.Fatalf("InsertOne failed: %v", err) + log.Panicf("InsertOne failed: %v", err) } // Print the logs. diff --git a/mongo/options/serverapioptions.go b/mongo/options/serverapioptions.go index 729f10f170..cf407390df 100644 --- a/mongo/options/serverapioptions.go +++ b/mongo/options/serverapioptions.go @@ -85,8 +85,7 @@ const ( // Validate determines if the provided ServerAPIVersion is currently supported by the driver. func (sav ServerAPIVersion) Validate() error { - switch sav { - case ServerAPIVersion1: + if sav == ServerAPIVersion1 { return nil } return fmt.Errorf("api version %q not supported; this driver version only supports API version \"1\"", sav) diff --git a/mongo/with_transactions_test.go b/mongo/with_transactions_test.go index 9878ebb92d..3b4d927754 100644 --- a/mongo/with_transactions_test.go +++ b/mongo/with_transactions_test.go @@ -120,7 +120,7 @@ func TestConvenientTransactions(t *testing.T) { "expected error with label %v, got %v", driver.TransientTransactionError, cmdErr) }) t.Run("unknown transaction commit result", func(t *testing.T) { - //set failpoint + // set failpoint failpoint := bson.D{{"configureFailPoint", "failCommand"}, {"mode", "alwaysOn"}, {"data", bson.D{ @@ -153,7 +153,7 @@ func TestConvenientTransactions(t *testing.T) { "expected error with label %v, got %v", driver.UnknownTransactionCommitResult, cmdErr) }) t.Run("commit transient transaction error", func(t *testing.T) { - //set failpoint + // set failpoint failpoint := bson.D{{"configureFailPoint", "failCommand"}, {"mode", "alwaysOn"}, {"data", bson.D{ @@ -271,7 +271,7 @@ func TestConvenientTransactions(t *testing.T) { var abortSucceeded []*event.CommandSucceededEvent var abortFailed []*event.CommandFailedEvent monitor := &event.CommandMonitor{ - Started: func(ctx context.Context, evt *event.CommandStartedEvent) { + Started: func(_ context.Context, evt *event.CommandStartedEvent) { if evt.CommandName == "abortTransaction" { abortStarted = append(abortStarted, evt) } @@ -349,7 +349,7 @@ func TestConvenientTransactions(t *testing.T) { var abortSucceeded []*event.CommandSucceededEvent var abortFailed []*event.CommandFailedEvent monitor := &event.CommandMonitor{ - Started: func(ctx context.Context, evt *event.CommandStartedEvent) { + Started: func(_ context.Context, evt *event.CommandStartedEvent) { if evt.CommandName == "abortTransaction" { abortStarted = append(abortStarted, evt) } diff --git a/x/bsonx/bsoncore/element.go b/x/bsonx/bsoncore/element.go index 8720c4076c..dcb5e86e71 100644 --- a/x/bsonx/bsoncore/element.go +++ b/x/bsonx/bsoncore/element.go @@ -50,7 +50,7 @@ func (e Element) KeyErr() (string, error) { // KeyBytesErr returns the key for this element as a []byte, returning an error if the element is // not valid. func (e Element) KeyBytesErr() ([]byte, error) { - if len(e) <= 0 { + if len(e) == 0 { return nil, ErrElementMissingType } idx := bytes.IndexByte(e[1:], 0x00) @@ -98,7 +98,7 @@ func (e Element) Value() Value { // ValueErr returns the value for this element, returning an error if the element is not valid. func (e Element) ValueErr() (Value, error) { - if len(e) <= 0 { + if len(e) == 0 { return Value{}, ErrElementMissingType } idx := bytes.IndexByte(e[1:], 0x00) @@ -120,7 +120,7 @@ func (e Element) String() string { // StringN implements the fmt.String interface for upto N bytes. The output will be in extended JSON format. func (e Element) StringN(n int) string { - if len(e) <= 0 { + if len(e) == 0 { return "" } t := Type(e[0]) @@ -149,7 +149,7 @@ func (e Element) StringN(n int) string { // DebugString outputs a human readable version of RawElement. It will attempt to stringify the // valid components of the element even if the entire element is not valid. func (e Element) DebugString() string { - if len(e) <= 0 { + if len(e) == 0 { return "" } t := Type(e[0]) diff --git a/x/bsonx/bsoncore/value.go b/x/bsonx/bsoncore/value.go index c459485baa..b0fd907436 100644 --- a/x/bsonx/bsoncore/value.go +++ b/x/bsonx/bsoncore/value.go @@ -946,13 +946,14 @@ func escapeString(s string) string { func formatDouble(f float64) string { var s string - if math.IsInf(f, 1) { + switch { + case math.IsInf(f, 1): s = "Infinity" - } else if math.IsInf(f, -1) { + case math.IsInf(f, -1): s = "-Infinity" - } else if math.IsNaN(f) { + case math.IsNaN(f): s = "NaN" - } else { + default: // Print exactly one decimalType place for integers; otherwise, print as many are necessary to // perfectly represent it. s = strconv.FormatFloat(f, 'G', -1, 64) @@ -975,9 +976,7 @@ func (ss sortableString) Less(i, j int) bool { } func (ss sortableString) Swap(i, j int) { - oldI := ss[i] - ss[i] = ss[j] - ss[j] = oldI + ss[i], ss[j] = ss[j], ss[i] } func sortStringAlphebeticAscending(s string) string { diff --git a/x/mongo/driver/auth/auth_test.go b/x/mongo/driver/auth/auth_test.go index c4103cf3b7..4736144e59 100644 --- a/x/mongo/driver/auth/auth_test.go +++ b/x/mongo/driver/auth/auth_test.go @@ -13,7 +13,7 @@ import ( "github.com/google/go-cmp/cmp" "go.mongodb.org/mongo-driver/v2/internal/require" "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" - . "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage" ) @@ -22,25 +22,25 @@ func TestCreateAuthenticator(t *testing.T) { tests := []struct { name string source string - auth Authenticator + auth auth.Authenticator }{ - {name: "", auth: &DefaultAuthenticator{}}, - {name: "SCRAM-SHA-1", auth: &ScramAuthenticator{}}, - {name: "SCRAM-SHA-256", auth: &ScramAuthenticator{}}, - {name: "MONGODB-CR", auth: &MongoDBCRAuthenticator{}}, - {name: "PLAIN", auth: &PlainAuthenticator{}}, - {name: "MONGODB-X509", auth: &MongoDBX509Authenticator{}}, + {name: "", auth: &auth.DefaultAuthenticator{}}, + {name: "SCRAM-SHA-1", auth: &auth.ScramAuthenticator{}}, + {name: "SCRAM-SHA-256", auth: &auth.ScramAuthenticator{}}, + {name: "MONGODB-CR", auth: &auth.MongoDBCRAuthenticator{}}, + {name: "PLAIN", auth: &auth.PlainAuthenticator{}}, + {name: "MONGODB-X509", auth: &auth.MongoDBX509Authenticator{}}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - cred := &Cred{ + cred := &auth.Cred{ Username: "user", Password: "pencil", PasswordSet: true, } - a, err := CreateAuthenticator(test.name, cred, &http.Client{}) + a, err := auth.CreateAuthenticator(test.name, cred, &http.Client{}) require.NoError(t, err) require.IsType(t, test.auth, a) }) @@ -53,8 +53,7 @@ func compareResponses(t *testing.T, wm []byte, expectedPayload bsoncore.Document t.Fatalf("wiremessage is too short to unmarshal") } var actualPayload bsoncore.Document - switch opcode { - case wiremessage.OpMsg: + if opcode == wiremessage.OpMsg { // Append the $db field. elems, err := expectedPayload.Elements() if err != nil { @@ -89,7 +88,7 @@ func compareResponses(t *testing.T, wm []byte, expectedPayload bsoncore.Document t.Fatalf("wiremessage is too short to unmarshal") } case wiremessage.SingleDocument: - actualPayload, wm, ok = wiremessage.ReadMsgSectionSingleDocument(wm) + actualPayload, _, ok = wiremessage.ReadMsgSectionSingleDocument(wm) if !ok { t.Fatalf("wiremessage is too short to unmarshal") } diff --git a/x/mongo/driver/auth/mongodbcr_test.go b/x/mongo/driver/auth/mongodbcr_test.go index 8bc956d499..0d6a4d0da1 100644 --- a/x/mongo/driver/auth/mongodbcr_test.go +++ b/x/mongo/driver/auth/mongodbcr_test.go @@ -14,7 +14,7 @@ import ( "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" - . "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/drivertest" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/mnet" @@ -23,7 +23,7 @@ import ( func TestMongoDBCRAuthenticator_Fails(t *testing.T) { t.Parallel() - authenticator := MongoDBCRAuthenticator{ + authenticator := auth.MongoDBCRAuthenticator{ DB: "source", Username: "user", Password: "pencil", @@ -64,7 +64,7 @@ func TestMongoDBCRAuthenticator_Fails(t *testing.T) { func TestMongoDBCRAuthenticator_Succeeds(t *testing.T) { t.Parallel() - authenticator := MongoDBCRAuthenticator{ + authenticator := auth.MongoDBCRAuthenticator{ DB: "source", Username: "user", Password: "pencil", diff --git a/x/mongo/driver/auth/oidc.go b/x/mongo/driver/auth/oidc.go index 2d2106ca4b..228e9f4097 100644 --- a/x/mongo/driver/auth/oidc.go +++ b/x/mongo/driver/auth/oidc.go @@ -287,7 +287,7 @@ func (oa *OIDCAuthenticator) providerCallback() (OIDCCallback, error) { func getAzureOIDCCallback(clientID string, resource string, httpClient *http.Client) OIDCCallback { // return the callback parameterized by the clientID and resource, also passing in the user // configured httpClient. - return func(ctx context.Context, args *OIDCArgs) (*OIDCCredential, error) { + return func(ctx context.Context, _ *OIDCArgs) (*OIDCCredential, error) { resource = url.QueryEscape(resource) var uri string if clientID != "" { @@ -330,7 +330,7 @@ func getAzureOIDCCallback(clientID string, resource string, httpClient *http.Cli func getGCPOIDCCallback(resource string, httpClient *http.Client) OIDCCallback { // return the callback parameterized by the clientID and resource, also passing in the user // configured httpClient. - return func(ctx context.Context, args *OIDCArgs) (*OIDCCredential, error) { + return func(ctx context.Context, _ *OIDCArgs) (*OIDCCredential, error) { resource = url.QueryEscape(resource) uri := fmt.Sprintf("http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=%s", resource) req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil) diff --git a/x/mongo/driver/auth/plain_test.go b/x/mongo/driver/auth/plain_test.go index d50e3f5b22..c83f0d7de3 100644 --- a/x/mongo/driver/auth/plain_test.go +++ b/x/mongo/driver/auth/plain_test.go @@ -16,7 +16,7 @@ import ( "go.mongodb.org/mongo-driver/v2/internal/require" "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" - . "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/drivertest" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/mnet" @@ -25,7 +25,7 @@ import ( func TestPlainAuthenticator_Fails(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -66,7 +66,7 @@ func TestPlainAuthenticator_Fails(t *testing.T) { func TestPlainAuthenticator_Extra_server_message(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -111,7 +111,7 @@ func TestPlainAuthenticator_Extra_server_message(t *testing.T) { func TestPlainAuthenticator_Succeeds(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } @@ -158,7 +158,7 @@ func TestPlainAuthenticator_Succeeds(t *testing.T) { func TestPlainAuthenticator_SucceedsBoolean(t *testing.T) { t.Parallel() - authenticator := PlainAuthenticator{ + authenticator := auth.PlainAuthenticator{ Username: "user", Password: "pencil", } diff --git a/x/mongo/driver/batch_cursor.go b/x/mongo/driver/batch_cursor.go index d3ef0ea6c0..fa0bb90665 100644 --- a/x/mongo/driver/batch_cursor.go +++ b/x/mongo/driver/batch_cursor.go @@ -113,12 +113,12 @@ func NewCursorResponse(info ResponseInfo) (CursorResponse, error) { if !ok { return CursorResponse{}, fmt.Errorf("ns should be a string but is a BSON %s", elem.Value().Type) } - index := strings.Index(ns, ".") - if index == -1 { + database, collection, ok := strings.Cut(ns, ".") + if !ok { return CursorResponse{}, errors.New("ns field must contain a valid namespace, but is missing '.'") } - curresp.Database = ns[:index] - curresp.Collection = ns[index+1:] + curresp.Database = database + curresp.Collection = collection case "id": curresp.ID, ok = elem.Value().Int64OK() if !ok { @@ -144,7 +144,6 @@ func NewCursorResponse(info ResponseInfo) (CursorResponse, error) { refConn := info.Connection.Pinner if refConn == nil { - //debug.PrintStack() return CursorResponse{}, fmt.Errorf("expected Connection used to establish a cursor to implement PinnedConnection, but got %T", info.Connection) } if err := refConn.PinToCursor(); err != nil { @@ -320,7 +319,7 @@ func (bc *BatchCursor) KillCursor(ctx context.Context) error { } return Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "killCursors", bc.collection) dst = bsoncore.BuildArrayElement(dst, "cursors", bsoncore.Value{Type: bsoncore.TypeInt64, Data: bsoncore.AppendInt64(nil, bc.id)}) return dst, nil @@ -514,8 +513,7 @@ func (bc *BatchCursor) getOperationDeployment() Deployment { // handled for these commands in this mode. type loadBalancedCursorDeployment struct { errorProcessor ErrorProcessor - //conn PinnedConnection - conn *mnet.Connection + conn *mnet.Connection } var _ Deployment = (*loadBalancedCursorDeployment)(nil) diff --git a/x/mongo/driver/connstring/connstring.go b/x/mongo/driver/connstring/connstring.go index 6f44d17a98..d550a68127 100644 --- a/x/mongo/driver/connstring/connstring.go +++ b/x/mongo/driver/connstring/connstring.go @@ -886,15 +886,16 @@ func (p *parser) parse(original string) (*ConnString, error) { uri := original var err error - if strings.HasPrefix(uri, SchemeMongoDBSRV+"://") { + switch { + case strings.HasPrefix(uri, SchemeMongoDBSRV+"://"): connStr.Scheme = SchemeMongoDBSRV // remove the scheme uri = uri[len(SchemeMongoDBSRV)+3:] - } else if strings.HasPrefix(uri, SchemeMongoDB+"://") { + case strings.HasPrefix(uri, SchemeMongoDB+"://"): connStr.Scheme = SchemeMongoDB // remove the scheme uri = uri[len(SchemeMongoDB)+3:] - } else { + default: return nil, errors.New(`scheme must be "mongodb" or "mongodb+srv"`) } @@ -905,9 +906,9 @@ func (p *parser) parse(original string) (*ConnString, error) { username := userInfo var password string - if idx := strings.Index(userInfo, ":"); idx != -1 { - username = userInfo[:idx] - password = userInfo[idx+1:] + if u, p, ok := strings.Cut(userInfo, ":"); ok { + username = u + password = p connStr.PasswordSet = true } diff --git a/x/mongo/driver/errors.go b/x/mongo/driver/errors.go index 93f60c83f4..1a0afca5d9 100644 --- a/x/mongo/driver/errors.go +++ b/x/mongo/driver/errors.go @@ -138,7 +138,7 @@ func (wce WriteCommandError) Retryable(wireVersion *description.VersionRange) bo if wce.WriteConcernError == nil { return false } - return (*wce.WriteConcernError).Retryable() + return wce.WriteConcernError.Retryable() } // HasErrorLabel returns true if the error contains the specified label. diff --git a/x/mongo/driver/integration/aggregate_test.go b/x/mongo/driver/integration/aggregate_test.go index 554a11961d..b055d9f11e 100644 --- a/x/mongo/driver/integration/aggregate_test.go +++ b/x/mongo/driver/integration/aggregate_test.go @@ -30,13 +30,13 @@ func setUpMonitor() (*event.CommandMonitor, chan *event.CommandStartedEvent, cha failed := make(chan *event.CommandFailedEvent, 1) return &event.CommandMonitor{ - Started: func(ctx context.Context, e *event.CommandStartedEvent) { + Started: func(_ context.Context, e *event.CommandStartedEvent) { started <- e }, - Succeeded: func(ctx context.Context, e *event.CommandSucceededEvent) { + Succeeded: func(_ context.Context, e *event.CommandSucceededEvent) { succeeded <- e }, - Failed: func(ctx context.Context, e *event.CommandFailedEvent) { + Failed: func(_ context.Context, e *event.CommandFailedEvent) { failed <- e }, }, started, succeeded, failed diff --git a/x/mongo/driver/operation.go b/x/mongo/driver/operation.go index 8c2e3e8e9a..35e363a1a6 100644 --- a/x/mongo/driver/operation.go +++ b/x/mongo/driver/operation.go @@ -564,19 +564,18 @@ func (op Operation) Execute(ctx context.Context) error { // Set the previous indefinite error to be returned in any case where a retryable write error does not have a // NoWritesPerfomed label (the definite case). - switch err := err.(type) { - case labeledError: + if lerr, ok := err.(labeledError); ok { // If the "prevIndefiniteErr" is nil, then the current error is the first error encountered // during the retry attempt cycle. We must persist the first error in the case where all // following errors are labeled "NoWritesPerformed", which would otherwise raise nil as the // error. if prevIndefiniteErr == nil { - prevIndefiniteErr = err + prevIndefiniteErr = lerr } // If the error is not labeled NoWritesPerformed and is retryable, then set the previous // indefinite error to be the current error. - if !err.HasErrorLabel(NoWritesPerformed) && err.HasErrorLabel(RetryableWriteError) { + if !lerr.HasErrorLabel(NoWritesPerformed) && lerr.HasErrorLabel(RetryableWriteError) { prevIndefiniteErr = err } } diff --git a/x/mongo/driver/operation/command.go b/x/mongo/driver/operation/command.go index 776da1a096..b1520f54fa 100644 --- a/x/mongo/driver/operation/command.go +++ b/x/mongo/driver/operation/command.go @@ -79,7 +79,7 @@ func (c *Command) Execute(ctx context.Context) error { } return driver.Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { return append(dst, c.command[4:len(c.command)-1]...), nil }, ProcessResponseFn: func(info driver.ResponseInfo) error { diff --git a/x/mongo/driver/operation/delete.go b/x/mongo/driver/operation/delete.go index 9b9348dae1..fe1f9a202a 100644 --- a/x/mongo/driver/operation/delete.go +++ b/x/mongo/driver/operation/delete.go @@ -59,8 +59,7 @@ func buildDeleteResult(response bsoncore.Document) (DeleteResult, error) { } dr := DeleteResult{} for _, element := range elements { - switch element.Key() { - case "n": + if element.Key() == "n" { var ok bool dr.N, ok = element.Value().AsInt64OK() if !ok { diff --git a/x/mongo/driver/operation/distinct.go b/x/mongo/driver/operation/distinct.go index 1f30b05248..cfff2f7c31 100644 --- a/x/mongo/driver/operation/distinct.go +++ b/x/mongo/driver/operation/distinct.go @@ -57,8 +57,7 @@ func buildDistinctResult(response bsoncore.Document) (DistinctResult, error) { } dr := DistinctResult{} for _, element := range elements { - switch element.Key() { - case "values": + if element.Key() == "values" { dr.Values = element.Value() } } diff --git a/x/mongo/driver/operation/drop_indexes.go b/x/mongo/driver/operation/drop_indexes.go index ce5bab8aa7..2514de4233 100644 --- a/x/mongo/driver/operation/drop_indexes.go +++ b/x/mongo/driver/operation/drop_indexes.go @@ -52,8 +52,7 @@ func buildDropIndexesResult(response bsoncore.Document) (DropIndexesResult, erro } dir := DropIndexesResult{} for _, element := range elements { - switch element.Key() { - case "nIndexesWas": + if element.Key() == "nIndexesWas" { var ok bool dir.NIndexesWas, ok = element.Value().AsInt32OK() if !ok { @@ -108,12 +107,12 @@ func (di *DropIndexes) Execute(ctx context.Context) error { func (di *DropIndexes) command(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "dropIndexes", di.collection) - switch di.index.(type) { + switch t := di.index.(type) { case string: - dst = bsoncore.AppendStringElement(dst, "index", di.index.(string)) + dst = bsoncore.AppendStringElement(dst, "index", t) case bsoncore.Document: if di.index != nil { - dst = bsoncore.AppendDocumentElement(dst, "index", di.index.(bsoncore.Document)) + dst = bsoncore.AppendDocumentElement(dst, "index", t) } } diff --git a/x/mongo/driver/operation/drop_search_index.go b/x/mongo/driver/operation/drop_search_index.go index 5061c62052..3a6adead32 100644 --- a/x/mongo/driver/operation/drop_search_index.go +++ b/x/mongo/driver/operation/drop_search_index.go @@ -48,8 +48,7 @@ func buildDropSearchIndexResult(response bsoncore.Document) (DropSearchIndexResu } dsir := DropSearchIndexResult{} for _, element := range elements { - switch element.Key() { - case "ok": + if element.Key() == "ok" { var ok bool dsir.Ok, ok = element.Value().AsInt32OK() if !ok { diff --git a/x/mongo/driver/operation/insert.go b/x/mongo/driver/operation/insert.go index 8cd338c03b..f64c586c83 100644 --- a/x/mongo/driver/operation/insert.go +++ b/x/mongo/driver/operation/insert.go @@ -58,8 +58,7 @@ func buildInsertResult(response bsoncore.Document) (InsertResult, error) { } ir := InsertResult{} for _, element := range elements { - switch element.Key() { - case "n": + if element.Key() == "n" { var ok bool ir.N, ok = element.Value().AsInt64OK() if !ok { diff --git a/x/mongo/driver/operation/update_search_index.go b/x/mongo/driver/operation/update_search_index.go index 979bb3bc79..943de7c61e 100644 --- a/x/mongo/driver/operation/update_search_index.go +++ b/x/mongo/driver/operation/update_search_index.go @@ -49,8 +49,7 @@ func buildUpdateSearchIndexResult(response bsoncore.Document) (UpdateSearchIndex } usir := UpdateSearchIndexResult{} for _, element := range elements { - switch element.Key() { - case "ok": + if element.Key() == "ok" { var ok bool usir.Ok, ok = element.Value().AsInt32OK() if !ok { diff --git a/x/mongo/driver/operation_test.go b/x/mongo/driver/operation_test.go index 1b4a89b80a..3efee28865 100644 --- a/x/mongo/driver/operation_test.go +++ b/x/mongo/driver/operation_test.go @@ -570,7 +570,7 @@ func TestOperation(t *testing.T) { mnetconn := mnet.NewConnection(conn) op := Operation{ - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { return bsoncore.AppendInt32Element(dst, handshake.LegacyHello, 1), nil }, Database: "admin", @@ -632,7 +632,7 @@ func TestOperation(t *testing.T) { op := Operation{ Database: "foobar", Deployment: SingleConnectionDeployment{C: conn}, - CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) { + CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendInt32Element(dst, "ping", 1) return dst, nil }, diff --git a/x/mongo/driver/session/client_session.go b/x/mongo/driver/session/client_session.go index 16328c645c..e084e9a024 100644 --- a/x/mongo/driver/session/client_session.go +++ b/x/mongo/driver/session/client_session.go @@ -147,13 +147,14 @@ func MaxClusterTime(ct1, ct2 bson.Raw) bson.Raw { epoch1, ord1 := getClusterTime(ct1) epoch2, ord2 := getClusterTime(ct2) - if epoch1 > epoch2 { + switch { + case epoch1 > epoch2: return ct1 - } else if epoch1 < epoch2 { + case epoch1 < epoch2: return ct2 - } else if ord1 > ord2 { + case ord1 > ord2: return ct1 - } else if ord1 < ord2 { + case ord1 < ord2: return ct2 } @@ -463,11 +464,12 @@ func (c *Client) UpdateCommitTransactionWriteConcern() { // CheckAbortTransaction checks to see if allowed to abort transaction and returns // an error if not allowed. func (c *Client) CheckAbortTransaction() error { - if c.TransactionState == None { + switch { + case c.TransactionState == None: return ErrNoTransactStarted - } else if c.TransactionState == Committed { + case c.TransactionState == Committed: return ErrAbortAfterCommit - } else if c.TransactionState == Aborted { + case c.TransactionState == Aborted: return ErrAbortTwice } return nil diff --git a/x/mongo/driver/topology/CMAP_spec_test.go b/x/mongo/driver/topology/CMAP_spec_test.go index aaec9f36c5..c0ff65d3ff 100644 --- a/x/mongo/driver/topology/CMAP_spec_test.go +++ b/x/mongo/driver/topology/CMAP_spec_test.go @@ -202,7 +202,7 @@ func runCMAPTest(t *testing.T, testFileName string) { return msc, nil }) }), - WithHandshaker(func(h Handshaker) Handshaker { + WithHandshaker(func(Handshaker) Handshaker { return operation.NewHello() }), } diff --git a/x/mongo/driver/topology/connection_test.go b/x/mongo/driver/topology/connection_test.go index 2e520d5ee6..5b7dac4537 100644 --- a/x/mongo/driver/topology/connection_test.go +++ b/x/mongo/driver/topology/connection_test.go @@ -139,17 +139,21 @@ func TestConnection(t *testing.T) { ) // Call connect in a goroutine because it will block. - var wg sync.WaitGroup - wg.Add(1) + var done atomic.Value go func() { - defer wg.Done() + defer done.Store(true) _ = conn.connect(context.Background()) }() // Simulate cancelling connection establishment and assert that this clears the CancelFunc. conn.closeConnectContext() close(doneChan) - wg.Wait() + + assert.Eventually(t, + func() bool { return done.Load().(bool) }, + 100*time.Millisecond, + 1*time.Millisecond, + "TODO") }) }) t.Run("tls", func(t *testing.T) { @@ -626,7 +630,7 @@ func TestConnection(t *testing.T) { makeMultipleConnections := func(t *testing.T, numConns int) (*pool, []*Connection, func()) { t.Helper() - addr := bootstrapConnections(t, numConns, func(nc net.Conn) {}) + addr := bootstrapConnections(t, numConns, func(net.Conn) {}) pool := newPool(poolConfig{ Address: address.Address(addr.String()), ConnectTimeout: defaultConnectionTimeout, diff --git a/x/mongo/driver/topology/pool_test.go b/x/mongo/driver/topology/pool_test.go index de44a4a68f..e8ecbe1476 100644 --- a/x/mongo/driver/topology/pool_test.go +++ b/x/mongo/driver/topology/pool_test.go @@ -1217,7 +1217,7 @@ func TestPool_PoolMonitor(t *testing.T) { }, // Add a 10ms delay to dialing so the test is reliable on operating // systems that can't measure very short durations (e.g. Windows). - WithDialer(func(d Dialer) Dialer { + WithDialer(func(Dialer) Dialer { return DialerFunc(func(ctx context.Context, n, a string) (net.Conn, error) { time.Sleep(10 * time.Millisecond) return dialer.DialContext(ctx, n, a) diff --git a/x/mongo/driver/topology/sdam_spec_test.go b/x/mongo/driver/topology/sdam_spec_test.go index 789881501a..9186aae157 100644 --- a/x/mongo/driver/topology/sdam_spec_test.go +++ b/x/mongo/driver/topology/sdam_spec_test.go @@ -320,7 +320,7 @@ func applyErrors(t *testing.T, topo *Topology, errors []applicationError) { if appErr.Generation != nil { generation = *appErr.Generation } - //use generation number to check conn stale + // use generation number to check conn stale innerConn := connection{ desc: desc, generation: generation, diff --git a/x/mongo/driver/topology/server.go b/x/mongo/driver/topology/server.go index 183d2795e6..55a2ddd8c6 100644 --- a/x/mongo/driver/topology/server.go +++ b/x/mongo/driver/topology/server.go @@ -806,7 +806,7 @@ func (s *Server) updateDescription(desc description.Server) { func (s *Server) createConnection() *connection { opts := copyConnectionOpts(s.cfg.connectionOpts) opts = append(opts, - WithHandshaker(func(h Handshaker) Handshaker { + WithHandshaker(func(Handshaker) Handshaker { return operation.NewHello().AppName(s.cfg.appname).Compressors(s.cfg.compressionOpts). ServerAPI(s.cfg.serverAPI) }), diff --git a/x/mongo/driver/topology/server_test.go b/x/mongo/driver/topology/server_test.go index 47a55f395a..b7ffd079a0 100644 --- a/x/mongo/driver/topology/server_test.go +++ b/x/mongo/driver/topology/server_test.go @@ -173,19 +173,19 @@ func TestServerHeartbeatTimeout(t *testing.T) { }), WithConnectionOptions(func(opts ...ConnectionOption) []ConnectionOption { return append(opts, - WithDialer(func(d Dialer) Dialer { + WithDialer(func(Dialer) Dialer { var dialer net.Dialer return &timeoutDialer{&dialer, errors} })) }), WithServerMonitor(func(*event.ServerMonitor) *event.ServerMonitor { return &event.ServerMonitor{ - ServerHeartbeatSucceeded: func(e *event.ServerHeartbeatSucceededEvent) { + ServerHeartbeatSucceeded: func(*event.ServerHeartbeatSucceededEvent) { if !errors.dequeue() { wg.Done() } }, - ServerHeartbeatFailed: func(e *event.ServerHeartbeatFailedEvent) { + ServerHeartbeatFailed: func(*event.ServerHeartbeatFailedEvent) { if !errors.dequeue() { wg.Done() } @@ -611,10 +611,10 @@ func TestServer(t *testing.T) { s := NewServer(address.Address(addr.String()), bson.NewObjectID(), defaultConnectionTimeout, - WithConnectionOptions(func(option ...ConnectionOption) []ConnectionOption { + WithConnectionOptions(func(...ConnectionOption) []ConnectionOption { return []ConnectionOption{WithDialer(func(_ Dialer) Dialer { return d })} }), - WithMaxConnections(func(u uint64) uint64 { + WithMaxConnections(func(uint64) uint64 { return 1 })) s.state = serverConnected diff --git a/x/mongo/driver/topology/topology_options.go b/x/mongo/driver/topology/topology_options.go index 5be0731a74..2dbfb55673 100644 --- a/x/mongo/driver/topology/topology_options.go +++ b/x/mongo/driver/topology/topology_options.go @@ -196,11 +196,11 @@ func NewConfigFromOptionsWithAuthenticator(opts *options.ClientOptions, clock *s for _, comp := range comps { switch comp { case "zlib": - connOpts = append(connOpts, WithZlibLevel(func(level *int) *int { + connOpts = append(connOpts, WithZlibLevel(func(*int) *int { return opts.ZlibLevel })) case "zstd": - connOpts = append(connOpts, WithZstdLevel(func(level *int) *int { + connOpts = append(connOpts, WithZstdLevel(func(*int) *int { return opts.ZstdLevel })) } @@ -340,7 +340,7 @@ func NewConfigFromOptionsWithAuthenticator(opts *options.ClientOptions, clock *s if opts.ServerSelectionTimeout != nil { cfgp.ServerSelectionTimeout = *opts.ServerSelectionTimeout } - //ConnectionTimeout + // ConnectionTimeout if opts.ConnectTimeout != nil { cfgp.ConnectTimeout = *opts.ConnectTimeout } diff --git a/x/mongo/driver/topology/topology_test.go b/x/mongo/driver/topology/topology_test.go index c55db8b778..0f445b5d32 100644 --- a/x/mongo/driver/topology/topology_test.go +++ b/x/mongo/driver/topology/topology_test.go @@ -992,7 +992,7 @@ func BenchmarkSelectServerFromDescription(b *testing.B) { }{ { name: "AllFit", - serversHook: func(servers []description.Server) {}, + serversHook: func([]description.Server) {}, }, { name: "AllButOneFit",