forked from FeatureBaseDB/featurebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot_test.go
198 lines (176 loc) · 6 KB
/
root_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Copyright 2017 Pilosa Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd_test
import (
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/pilosa/pilosa/v2/cmd"
"github.com/spf13/cobra"
)
// failErr calls t.Fatal if err != nil and adds the optional context to the
// error message.
func failErr(t *testing.T, err error, context ...string) {
ctx := strings.Join(context, "; ")
if err != nil {
t.Fatal(ctx, ": ", err)
}
}
// tExec executes the given `cmd`, which will be writing its output to `w`, and
// can be read from `out`. It will fail the test if the command does not return
// within 1 second. Useful for testing help messages and such.
func tExec(t *testing.T, cmd *cobra.Command, out io.Reader, w io.WriteCloser) (output []byte, err error) {
done := make(chan struct{})
var readErr error
go func() {
output, readErr = ioutil.ReadAll(out)
close(done)
}()
err = cmd.Execute()
if err != nil {
return output, err
}
if err := w.Close(); err != nil {
return output, fmt.Errorf("closing cmd's stdout: %v", err)
}
select {
case <-done:
case <-time.After(time.Second * 1):
t.Fatal("Test failed due to command execution timeout")
}
return output, readErr
}
// ExecNewRootCommand executes the pilosa root command with the given arguments
// and returns it's output. It will fail if the command does not complete within
// 1 second.
func ExecNewRootCommand(t *testing.T, args ...string) (string, error) {
out, w := io.Pipe()
rc := cmd.NewRootCommand(os.Stdin, w, w)
rc.SetArgs(args)
output, err := tExec(t, rc, out, w)
return string(output), err
}
// validator is a simple helper to avoid repeated `if err != nil` checks in
// validation code. One can use it to check that several pairs of things are
// equal, and at the end access an informative error message about the first
// non-equal pair encountered (or nil if all were equal)
type validator struct {
err error
}
// Check that two things are equal, and if not set v.err to a descriptive error
// message.
func (v *validator) Check(actual, expected interface{}) {
if v.err != nil {
return
}
if !reflect.DeepEqual(actual, expected) {
v.err = fmt.Errorf("Actual: '%v' is not equal to '%v'", actual, expected)
}
}
// Error returns the validator's error value if any v.Check call found an error.
func (v *validator) Error() error { return v.err }
// commandTest represents all possible ways to configure a pilosa command, as
// well as a function for validating whether the command worked as expected.
// args should be set to everything that comes after "pilosa" on the comand
// line.
type commandTest struct {
args []string
env map[string]string
cfgFileContent string
validation func() error
}
// executeDry sets up and executes each commandTest with the --dry-run flag set
// to true, and then executes the tests validation function. This stops
// execution after PersistentPreRunE (and so before the command's Run or RunE
// function is called). This is useful for verifying that configuration happened
// properly.
func executeDry(t *testing.T, tests []commandTest) {
for i, test := range tests {
test.args = append(test.args[:1], append([]string{"--dry-run"}, test.args[1:]...)...)
com := test.setupCommand(t)
err := com.Execute()
if err.Error() != "dry run" {
t.Fatalf("Problem with test %d, err: '%v'", i, err)
}
if err := test.validation(); err != nil {
t.Fatalf("Failed test %d due to: %v", i, err)
}
test.reset()
}
}
// setupCommand sets up all the configuration specified in the commandTest so
// that it can be run. This includes setting environment variables, and creating
// a temp config file with the cfgFileContent string as its content.
func (ct *commandTest) setupCommand(t *testing.T) *cobra.Command {
// make config file
cfgFile, err := ioutil.TempFile("", "")
failErr(t, err, "making temp file")
_, err = cfgFile.WriteString(ct.cfgFileContent)
failErr(t, err, "writing config to temp file")
// set up config file args/env
ct.env["PILOSA_CONFIG"] = cfgFile.Name()
// set up env
for name, val := range ct.env {
err = os.Setenv(name, val)
failErr(t, err, fmt.Sprintf("setting environment variable '%s' to '%s'", name, val))
}
// make command and set args
rc := cmd.NewRootCommand(strings.NewReader(""), ioutil.Discard, ioutil.Discard)
rc.SetArgs(ct.args)
err = cfgFile.Close()
failErr(t, err, "closing config file")
return rc
}
// reset the environment after setup/run of a commandTest.
func (ct *commandTest) reset() {
for name := range ct.env {
os.Setenv(name, "")
}
}
func TestRootCommand(t *testing.T) {
outStr, err := ExecNewRootCommand(t, "--help")
if !strings.Contains(outStr, "Usage:") ||
!strings.Contains(outStr, "Available Commands:") ||
!strings.Contains(outStr, "--help") || err != nil {
t.Fatalf("Expected standard usage message from RootCommand, but err: '%v', output: '%s'", err, outStr)
}
}
func TestRootCommand_Config(t *testing.T) {
file, err := ioutil.TempFile("", "test.conf")
if err != nil {
panic(err)
}
config := `data-dir = "/tmp/pil5_0"
bind = "127.0.0.1:10101"
[cluster]
replicas = 2
partitions = 128
hosts = [
"127.0.0.1:10101",
"127.0.0.1:10111",
]`
if _, err := file.Write([]byte(config)); err != nil {
t.Fatalf("writing config file: %v", err)
}
file.Close()
_, err = ExecNewRootCommand(t, "server", "--config", file.Name())
if err == nil || err.Error() != "invalid option in configuration file: cluster.partitions" {
t.Fatalf("Expected invalid option in configuration file, but err: '%v'", err)
}
}