@@ -2,9 +2,14 @@ package command
2
2
3
3
import (
4
4
"flag"
5
+ "os"
5
6
"reflect"
6
7
"sort"
7
8
"testing"
9
+
10
+ "github.com/kr/pty"
11
+ "github.com/mitchellh/cli"
12
+ "github.com/stretchr/testify/assert"
8
13
)
9
14
10
15
func TestMeta_FlagSet (t * testing.T ) {
@@ -53,3 +58,63 @@ func TestMeta_FlagSet(t *testing.T) {
53
58
}
54
59
}
55
60
}
61
+
62
+ func TestMeta_Colorize (t * testing.T ) {
63
+ type testCaseSetupFn func (* testing.T , * Meta )
64
+
65
+ cases := []struct {
66
+ Name string
67
+ SetupFn testCaseSetupFn
68
+ ExpectColor bool
69
+ }{
70
+ {
71
+ Name : "disable colors if UI is not colored" ,
72
+ ExpectColor : false ,
73
+ },
74
+ {
75
+ Name : "colors if UI is colored" ,
76
+ SetupFn : func (t * testing.T , m * Meta ) {
77
+ m .Ui = & cli.ColoredUi {}
78
+ },
79
+ ExpectColor : true ,
80
+ },
81
+ {
82
+ Name : "disable colors via CLI flag" ,
83
+ SetupFn : func (t * testing.T , m * Meta ) {
84
+ m .Ui = & cli.ColoredUi {}
85
+
86
+ fs := m .FlagSet ("colorize_test" , FlagSetDefault )
87
+ err := fs .Parse ([]string {"-no-color" })
88
+ assert .NoError (t , err )
89
+ },
90
+ ExpectColor : false ,
91
+ },
92
+ }
93
+
94
+ for _ , tc := range cases {
95
+ t .Run (tc .Name , func (t * testing.T ) {
96
+ // Create fake test terminal.
97
+ _ , tty , err := pty .Open ()
98
+ if err != nil {
99
+ t .Fatalf ("%v" , err )
100
+ }
101
+ defer tty .Close ()
102
+
103
+ oldStdout := os .Stdout
104
+ defer func () { os .Stdout = oldStdout }()
105
+ os .Stdout = tty
106
+
107
+ // Run test case.
108
+ m := & Meta {}
109
+ if tc .SetupFn != nil {
110
+ tc .SetupFn (t , m )
111
+ }
112
+
113
+ if tc .ExpectColor {
114
+ assert .False (t , m .Colorize ().Disable )
115
+ } else {
116
+ assert .True (t , m .Colorize ().Disable )
117
+ }
118
+ })
119
+ }
120
+ }
0 commit comments