@@ -2,8 +2,12 @@ package cli_test
2
2
3
3
import (
4
4
"bytes"
5
+ "flag"
5
6
"net/http"
6
7
"net/http/httptest"
8
+ "os"
9
+ "path/filepath"
10
+ "strings"
7
11
"testing"
8
12
9
13
"github.com/spf13/cobra"
@@ -16,8 +20,80 @@ import (
16
20
"github.com/coder/coder/cli/cliflag"
17
21
"github.com/coder/coder/cli/clitest"
18
22
"github.com/coder/coder/codersdk"
23
+ "github.com/coder/coder/testutil"
19
24
)
20
25
26
+ var updateGoldenFiles = flag .Bool ("update" , false , "update .golden files" )
27
+
28
+ //nolint:tparallel,paralleltest // These test sets env vars.
29
+ func TestCommandHelp (t * testing.T ) {
30
+ t .Parallel ()
31
+
32
+ tests := []struct {
33
+ name string
34
+ cmd []string
35
+ env map [string ]string
36
+ }{
37
+ {
38
+ name : "coder --help" ,
39
+ cmd : []string {"--help" },
40
+ env : map [string ]string {
41
+ "CODER_CONFIG_DIR" : "/tmp/coder-cli-test-config" ,
42
+ },
43
+ },
44
+ {
45
+ name : "coder server --help" ,
46
+ cmd : []string {"server" , "--help" },
47
+ env : map [string ]string {
48
+ "CODER_CONFIG_DIR" : "/tmp/coder-cli-test-config" ,
49
+ "CODER_CACHE_DIRECTORY" : "/tmp/coder-cli-test-cache" ,
50
+ },
51
+ },
52
+ }
53
+
54
+ for _ , tt := range tests {
55
+ tt := tt
56
+ t .Run (tt .name , func (t * testing.T ) {
57
+ // Unset all CODER_ environment variables for a clean slate.
58
+ for _ , kv := range os .Environ () {
59
+ name := strings .Split (kv , "=" )[0 ]
60
+ if _ , ok := tt .env [name ]; ! ok && strings .HasPrefix (name , "CODER_" ) {
61
+ t .Setenv (name , "" )
62
+ }
63
+ }
64
+ // Override environment variables for a reproducible test.
65
+ for k , v := range tt .env {
66
+ t .Setenv (k , v )
67
+ }
68
+
69
+ ctx , _ := testutil .Context (t )
70
+
71
+ var buf bytes.Buffer
72
+ root , _ := clitest .New (t , tt .cmd ... )
73
+ root .SetOut (& buf )
74
+ err := root .ExecuteContext (ctx )
75
+ require .NoError (t , err )
76
+
77
+ got := buf .Bytes ()
78
+ // Remove CRLF newlines (Windows).
79
+ got = bytes .ReplaceAll (got , []byte {'\r' , '\n' }, []byte {'\n' })
80
+
81
+ gf := filepath .Join ("testdata" , strings .Replace (tt .name , " " , "_" , - 1 )+ ".golden" )
82
+ if * updateGoldenFiles {
83
+ t .Logf ("update golden file for: %q: %s" , tt .name , gf )
84
+ err = os .WriteFile (gf , got , 0o600 )
85
+ require .NoError (t , err , "update golden file" )
86
+ }
87
+
88
+ want , err := os .ReadFile (gf )
89
+ require .NoError (t , err , "read golden file, run \" make update-golden-files\" and commit the changes" )
90
+ // Remove CRLF newlines (Windows).
91
+ want = bytes .ReplaceAll (want , []byte {'\r' , '\n' }, []byte {'\n' })
92
+ require .Equal (t , string (want ), string (got ), "golden file mismatch: %s, run \" make update-golden-files\" , verify and commit the changes" , gf )
93
+ })
94
+ }
95
+ }
96
+
21
97
func TestRoot (t * testing.T ) {
22
98
t .Parallel ()
23
99
t .Run ("FormatCobraError" , func (t * testing.T ) {
0 commit comments