-
Notifications
You must be signed in to change notification settings - Fork 279
/
arg_patterns.go
94 lines (73 loc) · 1.9 KB
/
arg_patterns.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package testhelpers
import (
"fmt"
"reflect"
"strings"
"testing"
"github.com/buildpacks/pack/internal/stringset"
)
func AssertIncludeAllExpectedPatterns(t *testing.T, receivedArgs []string, expectedPatterns ...[]string) {
t.Helper()
missingPatterns := [][]string{}
for _, expectedPattern := range expectedPatterns {
if !patternExists(expectedPattern, receivedArgs) {
missingPatterns = append(missingPatterns, expectedPattern)
}
}
assertSliceEmpty(t,
missingPatterns,
"Expected the patterns %s to exist in [%s]",
missingPatterns,
strings.Join(receivedArgs, " "),
)
}
func patternExists(expectedPattern []string, receivedArgs []string) bool {
_, missing, _ := stringset.Compare(receivedArgs, expectedPattern)
if len(missing) > 0 {
return false
}
if len(expectedPattern) == 1 {
return true
}
for _, loc := range matchLocations(expectedPattern[0], receivedArgs) {
finalElementLoc := intMin(loc+len(expectedPattern), len(receivedArgs))
receivedSubSlice := receivedArgs[loc:finalElementLoc]
if reflect.DeepEqual(receivedSubSlice, expectedPattern) {
return true
}
}
return false
}
func matchLocations(expectedArg string, receivedArgs []string) []int {
indices := []int{}
for i, receivedArg := range receivedArgs {
if receivedArg == expectedArg {
indices = append(indices, i)
}
}
return indices
}
func assertSliceEmpty(t *testing.T, actual [][]string, msg string, msgArgs ...interface{}) {
t.Helper()
empty, err := sliceEmpty(actual)
if err != nil {
t.Fatalf("assertSliceNotEmpty error: %s", err.Error())
}
if !empty {
t.Fatalf(msg, msgArgs...)
}
}
func sliceEmpty(slice [][]string) (bool, error) {
switch reflect.TypeOf(slice).Kind() {
case reflect.Slice:
return reflect.ValueOf(slice).Len() == 0, nil
default:
return true, fmt.Errorf("invoked with non slice actual: %v", slice)
}
}
func intMin(a, b int) int {
if a < b {
return a
}
return b
}