1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 // Expectation represents the expected result of some operation.
17 type Expectation struct {
19 errorMatcher *regexp.Regexp
22 // ExpectSuccess returns an Expectation that trivially expects success.
23 func ExpectSuccess() *Expectation {
24 return new(Expectation)
27 // Check validates whether err conforms to the expectation. Returns
28 // an error if it does not conform.
30 // Conformance means that if failure is true, then err must be non-nil.
31 // If err is non-nil, then it must match errorMatcher.
32 func (e *Expectation) Check(err error) error {
33 if !e.failure && err != nil {
34 return fmt.Errorf("unexpected error while reading the trace: %v", err)
36 if e.failure && err == nil {
37 return fmt.Errorf("expected error while reading the trace: want something matching %q, got none", e.errorMatcher)
39 if e.failure && err != nil && !e.errorMatcher.MatchString(err.Error()) {
40 return fmt.Errorf("unexpected error while reading the trace: want something matching %q, got %s", e.errorMatcher, err.Error())
45 // ParseExpectation parses the serialized form of an Expectation.
46 func ParseExpectation(data []byte) (*Expectation, error) {
47 exp := new(Expectation)
48 s := bufio.NewScanner(bytes.NewReader(data))
50 c := strings.SplitN(s.Text(), " ", 2)
56 return exp, fmt.Errorf("bad header line for FAILURE: %q", s.Text())
58 matcher, err := parseMatcher(c[1])
62 exp.errorMatcher = matcher
64 return exp, fmt.Errorf("bad header line: %q", s.Text())
71 func parseMatcher(quoted string) (*regexp.Regexp, error) {
72 pattern, err := strconv.Unquote(quoted)
74 return nil, fmt.Errorf("malformed pattern: not correctly quoted: %s: %v", quoted, err)
76 matcher, err := regexp.Compile(pattern)
78 return nil, fmt.Errorf("malformed pattern: not a valid regexp: %s: %v", pattern, err)