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
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// A helper for testing commands
// Author: bratseth
package cmd
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"testing"
"time"
"github.com/logrusorgru/aurora"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/vespa-engine/vespa/util"
)
type command struct {
configDir string
args []string
moreArgs []string
}
func execute(cmd command, t *testing.T, client *mockHttpClient) string {
if client != nil {
util.ActiveHttpClient = client
}
// Never print colors in tests
color = aurora.NewAurora(false)
// Set config dir. Use a separate one per test if none is specified
if cmd.configDir == "" {
cmd.configDir = t.TempDir()
viper.Reset()
}
os.Setenv("VESPA_CLI_HOME", cmd.configDir)
// Reset flags to their default value - persistent flags in Cobra persists over tests
rootCmd.Flags().VisitAll(func(f *pflag.Flag) {
switch v := f.Value.(type) {
case pflag.SliceValue:
_ = v.Replace([]string{})
default:
switch v.Type() {
case "bool", "string", "int":
_ = v.Set(f.DefValue)
}
}
})
// Capture stdout and execute command
var b bytes.Buffer
log.SetOutput(&b)
rootCmd.SetArgs(append(cmd.args, cmd.moreArgs...))
rootCmd.Execute()
out, err := ioutil.ReadAll(&b)
assert.Empty(t, err, "No error")
return string(out)
}
func executeCommand(t *testing.T, client *mockHttpClient, args []string, moreArgs []string) string {
return execute(command{args: args, moreArgs: moreArgs}, t, client)
}
type mockHttpClient struct {
// The HTTP status code that will be returned from the next invocation. Default: 200
nextStatus int
// The response body code that will be returned from the next invocation. Default: ""
nextBody string
// A recording of the last HTTP request made through this
lastRequest *http.Request
}
func (c *mockHttpClient) Do(request *http.Request, timeout time.Duration) (response *http.Response, error error) {
if c.nextStatus == 0 {
c.nextStatus = 200
}
c.lastRequest = request
return &http.Response{
Status: "Status " + strconv.Itoa(c.nextStatus),
StatusCode: c.nextStatus,
Body: ioutil.NopCloser(bytes.NewBufferString(c.nextBody)),
Header: make(http.Header),
},
nil
}
|