...
1
2
3
4
5
6
7 package auth_test
8
9 import (
10 "encoding/json"
11 "fmt"
12 "io/ioutil"
13 "path"
14 "testing"
15
16 "go.mongodb.org/mongo-driver/internal/require"
17 "go.mongodb.org/mongo-driver/internal/spectest"
18 "go.mongodb.org/mongo-driver/mongo/options"
19 )
20
21 type credential struct {
22 Username string
23 Password *string
24 Source string
25 Mechanism string
26 MechProps map[string]interface{} `json:"mechanism_properties"`
27 }
28
29 type testCase struct {
30 Description string
31 URI string
32 Valid bool
33 Credential *credential
34 }
35
36 type testContainer struct {
37 Tests []testCase
38 }
39
40
41 const authTestsDir = "../../../../testdata/auth/"
42
43 func runTestsInFile(t *testing.T, dirname string, filename string) {
44 filepath := path.Join(dirname, filename)
45 content, err := ioutil.ReadFile(filepath)
46 require.NoError(t, err)
47
48 var container testContainer
49 require.NoError(t, json.Unmarshal(content, &container))
50
51
52 filename = filename[:len(filename)-5]
53
54 for _, testCase := range container.Tests {
55 runTest(t, filename, testCase)
56 }
57 }
58
59 func runTest(t *testing.T, filename string, test testCase) {
60 t.Run(filename+":"+test.Description, func(t *testing.T) {
61 opts := options.Client().ApplyURI(test.URI)
62 if test.Valid {
63 require.NoError(t, opts.Validate())
64 } else {
65 require.Error(t, opts.Validate())
66 return
67 }
68
69 if test.Credential == nil {
70 require.Nil(t, opts.Auth)
71 return
72 }
73 require.NotNil(t, opts.Auth)
74 require.Equal(t, test.Credential.Username, opts.Auth.Username)
75
76 if test.Credential.Password == nil {
77 require.False(t, opts.Auth.PasswordSet)
78 } else {
79 require.True(t, opts.Auth.PasswordSet)
80 require.Equal(t, *test.Credential.Password, opts.Auth.Password)
81 }
82
83 require.Equal(t, test.Credential.Source, opts.Auth.AuthSource)
84
85 require.Equal(t, test.Credential.Mechanism, opts.Auth.AuthMechanism)
86
87 if len(test.Credential.MechProps) > 0 {
88 require.Equal(t, mapInterfaceToString(test.Credential.MechProps), opts.Auth.AuthMechanismProperties)
89 } else {
90 require.Equal(t, 0, len(opts.Auth.AuthMechanismProperties))
91 }
92 })
93 }
94
95
96 func mapInterfaceToString(m map[string]interface{}) map[string]string {
97 out := make(map[string]string)
98
99 for key, value := range m {
100 out[key] = fmt.Sprint(value)
101 }
102
103 return out
104 }
105
106
107 func TestAuthSpec(t *testing.T) {
108 for _, file := range spectest.FindJSONFilesInDir(t, authTestsDir) {
109 runTestsInFile(t, authTestsDir, file)
110 }
111 }
112
View as plain text