Skip to content

Commit c472f24

Browse files
JoelSpeedschrej
authored andcommitted
Add WithField transformer
This should allow people to access fields within their objects fetched by the Matcher. This allows easier assertions by allowing specific fields to be compared during tests.
1 parent 714fbf6 commit c472f24

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

pkg/envtest/komega/transforms.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Copyright 2021 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package komega
18+
19+
import (
20+
"fmt"
21+
"reflect"
22+
"strings"
23+
24+
"github.com/onsi/gomega"
25+
gtypes "github.com/onsi/gomega/types"
26+
)
27+
28+
// WithField gets the value of the named field from the object.
29+
// This is intended to be used in assertions with the Matcher make it easy
30+
// to check the value of a particular field in a resource.
31+
// To access nested fields uses a `.` separator.
32+
// Eg.
33+
// m.Eventually(deployment).Should(WithField("spec.replicas", BeZero()))
34+
// To access nested lists, use one of the Gomega list matchers in conjunction with this.
35+
// Eg.
36+
// m.Eventually(deploymentList).Should(WithField("items", ConsistOf(...)))
37+
func WithField(field string, matcher gtypes.GomegaMatcher) gtypes.GomegaMatcher {
38+
// Addressing Field by <struct>.<field> can be recursed
39+
fields := strings.SplitN(field, ".", 2)
40+
if len(fields) == 2 {
41+
matcher = WithField(fields[1], matcher)
42+
}
43+
44+
return gomega.WithTransform(func(obj interface{}) interface{} {
45+
r := reflect.ValueOf(obj)
46+
f := reflect.Indirect(r).FieldByName(fields[0])
47+
if !f.IsValid() {
48+
panic(fmt.Sprintf("Object '%s' does not have a field '%s'", reflect.TypeOf(obj), fields[0]))
49+
}
50+
return f.Interface()
51+
}, matcher)
52+
}

0 commit comments

Comments
 (0)