-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrors.go
67 lines (59 loc) · 1.84 KB
/
errors.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
package spectest
import (
"errors"
"fmt"
"sort"
"strings"
)
var (
// ErrTimeout is an error that indicates a timeout.
ErrTimeout = errors.New("deadline exceeded")
)
// errorOrNil returns nil if the statement is true, otherwise it returns an error with the given message.
func errorOrNil(statement bool, errorMessage func() string) error {
if statement {
return nil
}
return errors.New(errorMessage())
}
// unmatchedMockError is used to store errors when a request does not match any mocks.
// It implements the error interface.
type unmatchedMockError struct {
// errors is a map of mock number to errors
errors map[int][]error
}
// newUnmatchedMockError creates a new unmatchedMockError
func newUnmatchedMockError() *unmatchedMockError {
return &unmatchedMockError{
errors: map[int][]error{},
}
}
// append adds errors to the unmatchedMockError
func (u *unmatchedMockError) append(mockNumber int, errors ...error) *unmatchedMockError {
u.errors[mockNumber] = append(u.errors[mockNumber], errors...)
return u
}
// Error implementation of in-built error human readable string function
func (u *unmatchedMockError) Error() string {
var strBuilder strings.Builder
strBuilder.WriteString("received request did not match any mocks\n\n")
for _, mockNumber := range u.orderedMockKeys() {
strBuilder.WriteString(fmt.Sprintf("Mock %d mismatches:\n", mockNumber))
for _, err := range u.errors[mockNumber] {
strBuilder.WriteString("• ")
strBuilder.WriteString(err.Error())
strBuilder.WriteString("\n")
}
strBuilder.WriteString("\n")
}
return strBuilder.String()
}
// orderedMockKeys returns the keys of the errors map in order.
func (u *unmatchedMockError) orderedMockKeys() []int {
mockKeys := make([]int, 0, len(u.errors))
for mockKey := range u.errors {
mockKeys = append(mockKeys, mockKey)
}
sort.Ints(mockKeys)
return mockKeys
}