-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
95 lines (79 loc) · 2.15 KB
/
parser.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
package reql
import (
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsimple"
"github.com/zclconf/go-cty/cty"
)
func ParseReqfile(path string, env map[string]string) (Reqfile, error) {
vars := map[string]cty.Value{"env": cty.MapVal(map[string]cty.Value{"": cty.StringVal("")})}
if len(env) > 0 {
envMap := map[string]cty.Value{}
for k, v := range env {
envMap[k] = cty.StringVal(v)
}
vars["env"] = cty.MapVal(envMap)
}
var reqfile Reqfile
err := hclsimple.DecodeFile(
path,
&hcl.EvalContext{Variables: vars},
&reqfile,
)
if err != nil {
return Reqfile{}, err
}
for i := range reqfile.Response.Assertions {
reqfile.Response.Assertions[i].fn = ParseAssertion(reqfile.Response.Assertions[i].Expr)
}
return reqfile, nil
}
type AssertionFunc func(*http.Request, *http.Response) bool
func ParseAssertion(cond string) AssertionFunc {
return func(request *http.Request, response *http.Response) bool {
parts := strings.SplitN(cond, " ", 3)
var l, r string
if strings.HasPrefix(parts[0], "res") {
l = responseProperty(response, parts[0][(strings.Index(parts[0], ".")+1):])
} else {
panic("idk what to do")
}
r = parts[2]
fmt.Printf("Asserting %s %s %s\n", l, parts[1], r)
return getComparator(parts[1])(l, r)
}
}
func responseProperty(res *http.Response, property string) string {
switch {
case property == "code":
return strconv.Itoa(res.StatusCode)
case strings.HasPrefix(property, "headers"):
return res.Header.Get(property[(strings.Index(property, ".") + 1):])
case property == "body":
b, _ := io.ReadAll(res.Body)
return string(b)
}
return ""
}
func getComparator(s string) func(string, string) bool {
switch s {
case "==":
return func(s1, s2 string) bool { return s1 == s2 }
case "!=":
return func(s1, s2 string) bool { return s1 != s2 }
case ">":
return func(s1, s2 string) bool { return s1 > s2 }
case ">=":
return func(s1, s2 string) bool { return s1 >= s2 }
case "<":
return func(s1, s2 string) bool { return s1 < s2 }
case "<=":
return func(s1, s2 string) bool { return s1 <= s2 }
default:
panic("unknown comparator")
}
}