-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathversion_test.go
113 lines (91 loc) · 2.53 KB
/
version_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
// Copyright 2020 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package cmd
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"
"github.com/open-policy-agent/opa/internal/report"
)
func TestGenerateCmdOutputDisableCheckFlag(t *testing.T) {
var stdout bytes.Buffer
generateCmdOutput(&stdout, false)
expectOutputKeys(t, stdout.String(), []string{
"Version",
"Build Commit",
"Build Timestamp",
"Build Hostname",
"Go Version",
"Platform",
"WebAssembly",
"Rego Version",
})
}
func TestGenerateCmdOutputWithCheckFlagNoError(t *testing.T) {
exp := &report.DataResponse{Latest: report.ReleaseDetails{
Download: "https://openpolicyagent.org/downloads/v100.0.0/opa_darwin_amd64",
ReleaseNotes: "https://github.com/open-policy-agent/opa/releases/tag/v100.0.0",
LatestRelease: "v100.0.0",
}}
// test server
baseURL, teardown := getTestServer(exp, http.StatusOK)
defer teardown()
t.Setenv("OPA_TELEMETRY_SERVICE_URL", baseURL)
var stdout bytes.Buffer
generateCmdOutput(&stdout, true)
expectOutputKeys(t, stdout.String(), []string{
"Version",
"Build Commit",
"Build Timestamp",
"Build Hostname",
"Go Version",
"Platform",
"WebAssembly",
"Latest Upstream Version",
"Release Notes",
"Download",
"Rego Version",
})
}
func TestCheckOPAUpdateBadURL(t *testing.T) {
url := "http://foo:8112"
t.Setenv("OPA_TELEMETRY_SERVICE_URL", url)
err := checkOPAUpdate(nil)
if err == nil {
t.Fatal("Expected error but got nil")
}
}
func expectOutputKeys(t *testing.T, stdout string, expectedKeys []string) {
t.Helper()
lines := strings.Split(strings.Trim(stdout, "\n"), "\n")
gotKeys := make([]string, 0, len(lines))
for _, line := range lines {
gotKeys = append(gotKeys, strings.Split(line, ":")[0])
}
sort.Strings(expectedKeys)
sort.Strings(gotKeys)
if len(expectedKeys) != len(gotKeys) {
t.Fatalf("expected %v but got %v", expectedKeys, gotKeys)
}
for i, got := range gotKeys {
if expectedKeys[i] != got {
t.Fatalf("expected %v but got %v", expectedKeys, gotKeys)
}
}
}
func getTestServer(update interface{}, statusCode int) (baseURL string, teardownFn func()) {
mux := http.NewServeMux()
ts := httptest.NewServer(mux)
mux.HandleFunc("/v1/version", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(statusCode)
bs, _ := json.Marshal(update)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(bs)
})
return ts.URL, ts.Close
}