-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
125 lines (99 loc) · 2.35 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/tidwall/gjson"
)
var testdir string
// var verbose bool
type testDescription struct {
Name string
Test test
Result testResult
}
type test struct {
Token string `json:"x_auth_token"`
Url string
Method string
}
type testResult struct {
StatusCode int `json:"status_code"`
ConnectionType string `json:"connection_type"`
Contains []testResultContent
}
type testResultContent struct {
Field string
Type string
Value string
}
func init() {
flag.StringVar(&testdir, "tests", "./tests/", "Directory with all tests")
// flag.BoolVar(&verbose, "verbose", false, "Verbose to see why a test fails")
}
func main() {
flag.Parse()
files, err := ioutil.ReadDir(testdir)
if err != nil {
log.Fatal(err)
}
for n, file := range files {
testName := strings.SplitN(file.Name(), "_", 3)
fmt.Printf(
"%3d -- %s", n+1,
strings.TrimSuffix(testName[2], filepath.Ext(testName[2])))
execTest(file.Name())
}
}
func execTest(name string) {
t := readTestDescription(name)
req, err := http.NewRequest(t.Test.Method, t.Test.Url, nil)
if err != nil {
log.Print(err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
evaluateTest(resp, t)
}
func readTestDescription(name string) testDescription {
file, err := ioutil.ReadFile(testdir + "/" + name)
if err != nil {
log.Fatal(err)
}
var t testDescription
if err := json.NewDecoder(bytes.NewReader(file)).Decode(&t); err != nil {
log.Fatal(err)
}
return t
}
func evaluateTest(resp *http.Response, t testDescription) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Print(err)
}
succeeded := color.New(color.Faint, color.FgGreen).PrintfFunc()
failed := color.New(color.Bold, color.FgRed).PrintfFunc()
if resp.StatusCode != t.Result.StatusCode {
failed(" [FAIL] Expected StatusCode '%d, got '%d'\n", resp.StatusCode, t.Result.StatusCode)
return
}
for _, c := range t.Result.Contains {
receivedValue := gjson.Get(string(body), c.Field)
if strings.Compare(receivedValue.String(), c.Value) != 0 {
failed(" [FAIL] Expected '%s' for field '%s', got '%s'\n", c.Value, c.Field, receivedValue)
return
}
}
succeeded(" [PASS]\n")
}