...
1
2
3
4
5
6
7
8
9 package testtrace
10
11 import (
12 "bufio"
13 "bytes"
14 "fmt"
15 "regexp"
16 "strconv"
17 "strings"
18 )
19
20
21 type Expectation struct {
22 failure bool
23 errorMatcher *regexp.Regexp
24 }
25
26
27 func ExpectSuccess() *Expectation {
28 return new(Expectation)
29 }
30
31
32
33
34
35
36 func (e *Expectation) Check(err error) error {
37 if !e.failure && err != nil {
38 return fmt.Errorf("unexpected error while reading the trace: %v", err)
39 }
40 if e.failure && err == nil {
41 return fmt.Errorf("expected error while reading the trace: want something matching %q, got none", e.errorMatcher)
42 }
43 if e.failure && err != nil && !e.errorMatcher.MatchString(err.Error()) {
44 return fmt.Errorf("unexpected error while reading the trace: want something matching %q, got %s", e.errorMatcher, err.Error())
45 }
46 return nil
47 }
48
49
50 func ParseExpectation(data []byte) (*Expectation, error) {
51 exp := new(Expectation)
52 s := bufio.NewScanner(bytes.NewReader(data))
53 if s.Scan() {
54 c := strings.SplitN(s.Text(), " ", 2)
55 switch c[0] {
56 case "SUCCESS":
57 case "FAILURE":
58 exp.failure = true
59 if len(c) != 2 {
60 return exp, fmt.Errorf("bad header line for FAILURE: %q", s.Text())
61 }
62 matcher, err := parseMatcher(c[1])
63 if err != nil {
64 return exp, err
65 }
66 exp.errorMatcher = matcher
67 default:
68 return exp, fmt.Errorf("bad header line: %q", s.Text())
69 }
70 return exp, nil
71 }
72 return exp, s.Err()
73 }
74
75 func parseMatcher(quoted string) (*regexp.Regexp, error) {
76 pattern, err := strconv.Unquote(quoted)
77 if err != nil {
78 return nil, fmt.Errorf("malformed pattern: not correctly quoted: %s: %v", quoted, err)
79 }
80 matcher, err := regexp.Compile(pattern)
81 if err != nil {
82 return nil, fmt.Errorf("malformed pattern: not a valid regexp: %s: %v", pattern, err)
83 }
84 return matcher, nil
85 }
86
View as plain text