forked from JumboInteractiveLimited/Gandalf
/
checks.go
51 lines (45 loc) · 1.8 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
// Package pathing is a collection of functions that are able to
// extract values from data using on a path/query.
package pathing
import (
"fmt"
"testing"
"github.com/Nekroze/Gandalf/check"
)
// An Extractor is any func that takes two strings and returns a slice of strings and an error.
// These functions take a source string and a path string. The source string is the structured
// text document that this extractor will try to extract data from. The path string is an
// address/expression in a pathing DSL (eg. XPath or JSonPath) that describes what data should be
// extracted from the source. All Extractors should return the extracted data as a slice of string
// along with an error to indicate failure or success.
type Extractor func(source, path string) ([]string, error)
// PathChecks is a collection of path expressions for a given Extrator and
// check.Func's to check the value(s) with.
type PathChecks map[string]check.Func
// Checks extracts paths (keys of the given PathChecks and passes the value add
// that path to a check.Func for assertion.
func Checks(ex Extractor, pcs PathChecks) check.Func {
cname := "PathingChecks"
return func(found string) error {
for path, check := range pcs {
extracts, err := ex(found, path)
if err != nil {
return throw(cname, found,
fmt.Errorf("check for path `%s` failed due to error:\n%s", path, err))
}
for _, s := range extracts {
if e := check(s); e != nil {
return throw(cname, found,
fmt.Errorf("check for path `%s` failed due to error:\n%s", path, e))
}
}
}
return nil
}
}
func throw(check, found string, err error) error {
if testing.Verbose() {
return fmt.Errorf("Pathcheck `%s` failed on value `%s` with error:\n%s", check, found, err)
}
return fmt.Errorf("Pathcheck `%s` failed with error:\n%s", check, err)
}