/
checks.go
108 lines (85 loc) · 2.59 KB
/
checks.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
// Package manatest provides internal workings for go-mana-test.
package manatest
// Imports
import (
"errors"
"fmt"
"github.com/mattrmiller/go-mana-test/http"
"github.com/tidwall/gjson"
"gopkg.in/resty.v1"
"strconv"
"strings"
)
// Checks.
const (
CheckResCode = "response.code"
CheckResBodyJSON = "response.body.json"
)
// ValidateCheck Validates check.
func ValidateCheck(check *string) bool {
// Response code
if strings.HasPrefix(*check, CheckResCode) {
return true
}
// Response body json
if strings.HasPrefix(*check, CheckResBodyJSON) {
return true
}
return false
}
// RunChecks Runs checks for a test and a project.
func RunChecks(checks *[]TestChecks, vars *[]ProjectGlobal, response *resty.Response) error {
// Each check
for _, check := range *checks {
// Replace variables
check.Check = ReplaceVarsInCheck(check.Check, vars)
check.Value = ReplaceVarsInCheck(check.Value, vars)
// Check response code
if strings.HasPrefix(check.Check, CheckResCode) {
err := checkResponseCode(&check, response)
if err != nil {
return err
}
}
// Check response body json
if strings.HasPrefix(check.Check, CheckResBodyJSON) {
err := checkResponseBodyJSON(&check, response)
if err != nil {
return err
}
}
}
return nil
}
// checkResponseCode Checks the response code.
func checkResponseCode(check *TestChecks, response *resty.Response) error {
// Convert response code in value
resCode, err := strconv.Atoi(check.Value)
if err != nil {
return errors.New("invalid numeric 'response.code' in check value")
}
// Check
if resCode != response.StatusCode() {
return fmt.Errorf("check '%s' wanted '%d' != received '%d'", check.Check, resCode, response.StatusCode())
}
return nil
}
// checkResponseBodyJSON Checks the response body json.
func checkResponseBodyJSON(check *TestChecks, response *resty.Response) error {
// First make sure that response type was json
if !strings.Contains(response.Header().Get(http.HeaderContentType), http.ContentTypeJSON) {
return fmt.Errorf("response '%s' was not a proper content type '%s'", check.Check, http.ContentTypeJSON)
}
// Scrape the prefix off the selector
jsonSel := strings.TrimPrefix(check.Check, fmt.Sprintf("%s.", CheckResBodyJSON))
// Get the json
jsonValue := gjson.Get(string(response.Body()), jsonSel)
// Check
if !jsonValue.Exists() {
return fmt.Errorf("check '%s' wanted '%s' != received 'null'", check.Check, check.Value)
}
if jsonValue.String() != check.Value {
return fmt.Errorf("check '%s' wanted '%s' != received '%s'", check.Check, check.Value, jsonValue.String())
}
return nil
}