|
| 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