Skip to content

Commit 91e8015

Browse files
phlogistonjohnobnoxxx
authored andcommitted
test utils: add a mutating input source type
Add an interface and a type implementing that interface to allow for the mutation of resources read from an input source. The mutation is supplied as a function that operates on an *unstructured.Unstructured. This will be used in later changes for making certain sub-fields of a resource unique. Signed-off-by: John Mulligan <[email protected]>
1 parent f63cc2a commit 91e8015

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

tests/utils/kube/dynamic.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,48 @@ func (DirectSource) Rename(n string) string {
7878
return n
7979
}
8080

81+
// MutatingInputSource are input sources that can arbitrarily change the
82+
// objects read from the input.
83+
type MutatingInputSource interface {
84+
InputSource
85+
Apply(*unstructured.Unstructured) error
86+
}
87+
88+
// MutatingSource uses another input source and applies a custom Mutate function
89+
// to change the objects read from the source.
90+
type MutatingSource struct {
91+
Source InputSource
92+
Mutate func(*unstructured.Unstructured) error
93+
}
94+
95+
// Open returns the source.
96+
func (m MutatingSource) Open() (io.ReadCloser, error) {
97+
return m.Source.Open()
98+
}
99+
100+
// GetNamespace returns the specified namespace.
101+
func (m MutatingSource) GetNamespace() string {
102+
return m.Source.GetNamespace()
103+
}
104+
105+
// Rename adjusts the name of the resource.
106+
func (m MutatingSource) Rename(n string) string {
107+
return m.Source.Rename(n)
108+
}
109+
110+
// Apply mutations to the resource.
111+
func (m MutatingSource) Apply(u *unstructured.Unstructured) error {
112+
return m.Mutate(u)
113+
}
114+
115+
func mutateInputObject(u *unstructured.Unstructured, src InputSource) error {
116+
ms, ok := src.(MutatingInputSource)
117+
if !ok {
118+
return nil
119+
}
120+
return ms.Apply(u)
121+
}
122+
81123
// CreateFromFile creates new resources given a (yaml) file input.
82124
// It returns an error if the resource already exists.
83125
func (tc *TestClient) CreateFromFile(
@@ -89,6 +131,9 @@ func (tc *TestClient) CreateFromFile(
89131
return n, err
90132
}
91133
for _, u := range objs {
134+
if err := mutateInputObject(u, src); err != nil {
135+
return n, err
136+
}
92137
newu, err := tc.dynCreate(ctx, src.GetNamespace(), u)
93138
if err != nil {
94139
return n, err
@@ -112,6 +157,9 @@ func (tc *TestClient) CreateFromFileIfMissing(
112157
return n, err
113158
}
114159
for _, u := range objs {
160+
if err := mutateInputObject(u, src); err != nil {
161+
return n, err
162+
}
115163
newu, err := tc.dynCreate(ctx, src.GetNamespace(), u)
116164
if kerrors.IsAlreadyExists(err) {
117165
continue

0 commit comments

Comments
 (0)