File: expectation.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20250911.df92998-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid
  • size: 7,284 kB
  • sloc: ansic: 1,900; objc: 276; sh: 270; asm: 48; makefile: 27
file content (85 lines) | stat: -rw-r--r-- 2,404 bytes parent folder | download
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
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Code generated by "gen.bash" from internal/trace; DO NOT EDIT.

//go:build go1.23

package testtrace

import (
	"bufio"
	"bytes"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

// Expectation represents the expected result of some operation.
type Expectation struct {
	failure      bool
	errorMatcher *regexp.Regexp
}

// ExpectSuccess returns an Expectation that trivially expects success.
func ExpectSuccess() *Expectation {
	return new(Expectation)
}

// Check validates whether err conforms to the expectation. Returns
// an error if it does not conform.
//
// Conformance means that if failure is true, then err must be non-nil.
// If err is non-nil, then it must match errorMatcher.
func (e *Expectation) Check(err error) error {
	if !e.failure && err != nil {
		return fmt.Errorf("unexpected error while reading the trace: %v", err)
	}
	if e.failure && err == nil {
		return fmt.Errorf("expected error while reading the trace: want something matching %q, got none", e.errorMatcher)
	}
	if e.failure && err != nil && !e.errorMatcher.MatchString(err.Error()) {
		return fmt.Errorf("unexpected error while reading the trace: want something matching %q, got %s", e.errorMatcher, err.Error())
	}
	return nil
}

// ParseExpectation parses the serialized form of an Expectation.
func ParseExpectation(data []byte) (*Expectation, error) {
	exp := new(Expectation)
	s := bufio.NewScanner(bytes.NewReader(data))
	if s.Scan() {
		c := strings.SplitN(s.Text(), " ", 2)
		switch c[0] {
		case "SUCCESS":
		case "FAILURE":
			exp.failure = true
			if len(c) != 2 {
				return exp, fmt.Errorf("bad header line for FAILURE: %q", s.Text())
			}
			matcher, err := parseMatcher(c[1])
			if err != nil {
				return exp, err
			}
			exp.errorMatcher = matcher
		default:
			return exp, fmt.Errorf("bad header line: %q", s.Text())
		}
		return exp, nil
	}
	return exp, s.Err()
}

func parseMatcher(quoted string) (*regexp.Regexp, error) {
	pattern, err := strconv.Unquote(quoted)
	if err != nil {
		return nil, fmt.Errorf("malformed pattern: not correctly quoted: %s: %v", quoted, err)
	}
	matcher, err := regexp.Compile(pattern)
	if err != nil {
		return nil, fmt.Errorf("malformed pattern: not a valid regexp: %s: %v", pattern, err)
	}
	return matcher, nil
}