1 // Copyright 2017 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build dragonfly freebsd linux netbsd openbsd solaris
17 testDirCN
= "test-dir"
18 testFile
= "test-file.crt"
19 testFileCN
= "test-file"
20 testMissing
= "missing"
23 func TestEnvVars(t
*testing
.T
) {
24 testCases
:= []struct {
33 // Environment variables override the default locations preventing fall through.
34 name
: "override-defaults",
37 files
: []string{testFile
},
38 dirs
: []string{testDir
},
42 // File environment overrides default file locations.
48 cns
: []string{testFileCN
},
51 // Directory environment overrides default directory locations.
57 cns
: []string{testDirCN
},
60 // File & directory environment overrides both default locations.
66 cns
: []string{testFileCN
, testDirCN
},
69 // Environment variable empty / unset uses default locations.
70 name
: "empty-fall-through",
73 files
: []string{testFile
},
74 dirs
: []string{testDir
},
75 cns
: []string{testFileCN
, testDirCN
},
79 // Save old settings so we can restore before the test ends.
80 origCertFiles
, origCertDirectories
:= certFiles
, certDirectories
81 origFile
, origDir
:= os
.Getenv(certFileEnv
), os
.Getenv(certDirEnv
)
83 certFiles
= origCertFiles
84 certDirectories
= origCertDirectories
85 os
.Setenv(certFileEnv
, origFile
)
86 os
.Setenv(certDirEnv
, origDir
)
89 for _
, tc
:= range testCases
{
90 t
.Run(tc
.name
, func(t
*testing
.T
) {
91 if err
:= os
.Setenv(certFileEnv
, tc
.fileEnv
); err
!= nil {
92 t
.Fatalf("setenv %q failed: %v", certFileEnv
, err
)
94 if err
:= os
.Setenv(certDirEnv
, tc
.dirEnv
); err
!= nil {
95 t
.Fatalf("setenv %q failed: %v", certDirEnv
, err
)
98 certFiles
, certDirectories
= tc
.files
, tc
.dirs
100 r
, err
:= loadSystemRoots()
102 t
.Fatal("unexpected failure:", err
)
113 // Verify that the returned certs match, otherwise report where the mismatch is.
114 for i
, cn
:= range tc
.cns
{
115 if i
>= len(r
.certs
) {
116 t
.Errorf("missing cert %v @ %v", cn
, i
)
117 } else if r
.certs
[i
].Subject
.CommonName
!= cn
{
118 fmt
.Printf("%#v\n", r
.certs
[0].Subject
)
119 t
.Errorf("unexpected cert common name %q, want %q", r
.certs
[i
].Subject
.CommonName
, cn
)
122 if len(r
.certs
) > len(tc
.cns
) {
123 t
.Errorf("got %v certs, which is more than %v wanted", len(r
.certs
), len(tc
.cns
))