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
7package mongo
8
9import (
10	"context"
11	"net"
12	"sync/atomic"
13	"testing"
14
15	"github.com/stretchr/testify/require"
16	"go.mongodb.org/mongo-driver/internal/testutil"
17	"go.mongodb.org/mongo-driver/mongo/options"
18	"go.mongodb.org/mongo-driver/x/bsonx"
19)
20
21func TestClientOptions_CustomDialer(t *testing.T) {
22	td := &testDialer{d: &net.Dialer{}}
23	cs := testutil.ConnString(t)
24	opts := options.Client().ApplyURI(cs.String()).SetDialer(td)
25	client, err := NewClient(opts)
26	require.NoError(t, err)
27	err = client.Connect(context.Background())
28	require.NoError(t, err)
29	_, err = client.ListDatabases(context.Background(), bsonx.Doc{})
30	require.NoError(t, err)
31	got := atomic.LoadInt32(&td.called)
32	if got < 1 {
33		t.Errorf("Custom dialer was not used when dialing new connections")
34	}
35}
36
37type testDialer struct {
38	called int32
39	d      Dialer
40}
41
42func (td *testDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
43	atomic.AddInt32(&td.called, 1)
44	return td.d.DialContext(ctx, network, address)
45}
46