1// Copyright (C) MongoDB, Inc. 2017-present. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); you may 4// not use this file except in compliance with the License. You may obtain 5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 7// +build go1.13 8 9package topology 10 11import ( 12 "context" 13 "errors" 14 "sync/atomic" 15 "testing" 16 "time" 17 18 "go.mongodb.org/mongo-driver/internal/testutil/assert" 19 "go.mongodb.org/mongo-driver/mongo/description" 20) 21 22var selectNone description.ServerSelectorFunc = func(description.Topology, []description.Server) ([]description.Server, error) { 23 return []description.Server{}, nil 24} 25 26func TestTopologyErrors(t *testing.T) { 27 t.Run("errors are wrapped", func(t *testing.T) { 28 t.Run("server selection error", func(t *testing.T) { 29 topo, err := New() 30 noerr(t, err) 31 32 topo.cfg.cs.HeartbeatInterval = time.Minute 33 atomic.StoreInt32(&topo.connectionstate, connected) 34 desc := description.Topology{ 35 Servers: []description.Server{}, 36 } 37 topo.desc.Store(desc) 38 39 ctx, cancel := context.WithCancel(context.Background()) 40 cancel() 41 _, err = topo.SelectServer(ctx, description.WriteSelector()) 42 assert.True(t, errors.Is(err, context.Canceled), "expected error %v, got %v", context.Canceled, err) 43 }) 44 t.Run("context deadline error", func(t *testing.T) { 45 topo, err := New() 46 assert.Nil(t, err, "error creating topology: %v", err) 47 48 var serverSelectionErr error 49 callback := func() { 50 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) 51 defer cancel() 52 53 state := newServerSelectionState(selectNone, make(<-chan time.Time)) 54 subCh := make(<-chan description.Topology) 55 _, serverSelectionErr = topo.selectServerFromSubscription(ctx, subCh, state) 56 } 57 assert.Soon(t, callback, 150*time.Millisecond) 58 assert.True(t, errors.Is(serverSelectionErr, context.DeadlineExceeded), "expected %v, recieved %v", 59 context.DeadlineExceeded, serverSelectionErr) 60 }) 61 }) 62} 63