-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.go
93 lines (78 loc) · 2.18 KB
/
helpers.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
package test
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/aren55555/jsonapivalidator"
)
var (
noError, noWarning error
)
const (
testErrorExpected = "Was expecting an error\nExpected: %s\nGot: %s"
testErrorLengthExpected = "Was expecting %d errors; got %d\nErrors: %s"
testErrorNotExpected = "Was not expecting an error\nGot: %s"
testWarningExpected = "Was expecting a warning\nExpected: %s\nGot: %s"
testWarningLengthExpected = "Was expecting %d warnings; got %d\nWarnings: %s"
testWarningNotExpected = "Was not expecting a warning\nGot: %s"
)
func validatePayload(t *testing.T, data []byte) *jsonapivalidator.Result {
var obj interface{}
if err := json.Unmarshal(data, &obj); err != nil {
t.Fatal(err)
}
return jsonapivalidator.Validate(obj)
}
func expectedResult(t *testing.T, data []byte, expectedErr error, expectedWarning error) {
r := validatePayload(t, data)
if expectedErr == nil {
// Was not expecting errors
if r.HasErrors() {
t.Fatalf(testErrorNotExpected, joinErrors(r.Errors()))
}
} else {
// An error is expected
if !r.HasError(expectedErr) {
t.Fatalf(testErrorExpected, expectedErr, joinErrors(r.Errors()))
}
}
if expectedWarning == nil {
// Was not expecting warnings
if r.HasWarnings() {
t.Fatalf(testWarningNotExpected, joinErrors(r.Warnings()))
}
} else {
// A warning is expected
if !r.HasWarning(expectedWarning) {
t.Fatalf(testWarningExpected, expectedWarning, joinErrors(r.Warnings()))
}
}
}
func expectedResultHasErrors(t *testing.T, data []byte, errorCount uint) {
r := validatePayload(t, data)
if a := uint(len(r.Errors())); a != errorCount {
t.Fatalf(testErrorLengthExpected, errorCount, a, joinErrors(r.Errors()))
}
}
func loadSample(t *testing.T, sample string) (data io.Reader) {
sampleFile, err := filepath.Abs(fmt.Sprintf("./samples/%s", sample))
if err != nil {
t.Fatal(err)
}
data, err = os.Open(sampleFile)
if err != nil {
t.Fatal(err)
}
return
}
func joinErrors(errors []error) (r string) {
strs := []string{}
for _, err := range errors {
strs = append(strs, fmt.Sprintf(">>> %s <<<", err))
}
return strings.Join(strs, ",\n")
}