...

Source file src/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology_errors_test.go

Documentation: go.mongodb.org/mongo-driver/x/mongo/driver/topology

     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  //go:build go1.13
     8  // +build go1.13
     9  
    10  package topology
    11  
    12  import (
    13  	"context"
    14  	"errors"
    15  	"sync/atomic"
    16  	"testing"
    17  	"time"
    18  
    19  	"go.mongodb.org/mongo-driver/internal/assert"
    20  	"go.mongodb.org/mongo-driver/mongo/description"
    21  )
    22  
    23  var selectNone description.ServerSelectorFunc = func(description.Topology, []description.Server) ([]description.Server, error) {
    24  	return []description.Server{}, nil
    25  }
    26  
    27  func TestTopologyErrors(t *testing.T) {
    28  	t.Run("errors are wrapped", func(t *testing.T) {
    29  		t.Run("server selection error", func(t *testing.T) {
    30  			topo, err := New(nil)
    31  			noerr(t, err)
    32  
    33  			atomic.StoreInt64(&topo.state, topologyConnected)
    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(nil)
    46  			assert.Nil(t, err, "error creating topology: %v", err)
    47  
    48  			var serverSelectionErr error
    49  			callback := func(ctx context.Context) {
    50  				selectServerCtx, cancel := context.WithTimeout(ctx, 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(selectServerCtx, subCh, state)
    56  			}
    57  			assert.Soon(t, callback, 150*time.Millisecond)
    58  			assert.True(t, errors.Is(serverSelectionErr, context.DeadlineExceeded), "expected %v, received %v",
    59  				context.DeadlineExceeded, serverSelectionErr)
    60  		})
    61  	})
    62  }
    63  

View as plain text