-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopts_args.go
More file actions
341 lines (310 loc) · 10.8 KB
/
opts_args.go
File metadata and controls
341 lines (310 loc) · 10.8 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// SPDX-FileCopyrightText: Copyright DB InfraGO AG and contributors
// SPDX-License-Identifier: Apache-2.0
package testing
import (
"encoding/json"
"fmt"
"github.com/crossplane/crossplane-runtime/pkg/meta"
fncontext "github.com/crossplane/function-sdk-go/context"
fnapi "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/resource"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/dbinfrago/crossplane-function-test-framework/internal/util/maps"
"github.com/dbinfrago/crossplane-function-test-framework/internal/util/yaml"
)
// WithContextValue sets the expected context field to value.
func WithContextValue(key string, value any) TestFunctionOpt {
return func(tc *FunctionTest) {
val := mustStructValue(value)
tc.req.Context.Fields[key] = val
}
}
// WithContextValueYAML reads a value from a single YAML document and sets it
// as value of the given context field.
func WithContextValueYAML(key string, rawYAML []byte) TestFunctionOpt {
var val any
if err := yaml.Unmarshal(rawYAML, &val); err != nil {
panic(err.Error())
}
return WithContextValue(key, val)
}
// WithContextValueYAML reads a value from a JSON document and sets it
// as value of the given context field.
func WithContextValueJSON(key string, rawJSON []byte) TestFunctionOpt {
var val any
if err := json.Unmarshal(rawJSON, &val); err != nil {
panic(err.Error())
}
return WithContextValue(key, val)
}
// WithInput sets the input that is passed to the function run.
func WithInput(input runtime.Object) TestFunctionOpt {
str, err := resource.AsStruct(input)
if err != nil {
panic(err)
}
return func(tc *FunctionTest) {
tc.req.Input = str
}
}
// WithInputYAML is the same as [WithInput] but accepts raw YAML.
func WithInputYAML(inputYAML []byte) TestFunctionOpt {
u := &unstructured.Unstructured{}
if err := yaml.Unmarshal(inputYAML, u); err != nil {
panic(err)
}
return WithInput(u)
}
// WithInputJSON is the same as [WithInput] but accepts raw JSON.
func WithInputJSON(inputJSON []byte) TestFunctionOpt {
u := &unstructured.Unstructured{}
if err := json.Unmarshal(inputJSON, u); err != nil {
panic(err)
}
return WithInput(u)
}
// WithObservedResourceObject adds o to the observed state passed to the
// function.
func WithObservedResourceObject(name string, o runtime.Object) TestFunctionOpt {
return func(tc *FunctionTest) {
str := mustObjectAsStruct(o)
tc.req.Observed.Resources[name] = &fnapi.Resource{
Resource: str,
}
}
}
// WithObservedResourceYAML reads an object from a single YAML document and adds
// it to the observed state passed to the function.
func WithObservedResourceYAML(name string, rawYAML []byte) TestFunctionOpt {
u := &unstructured.Unstructured{}
if err := yaml.Unmarshal(rawYAML, u); err != nil {
panic(err.Error())
}
return WithObservedResourceObject(name, u)
}
// WithObservedResourceJSON reads an object from a single JSON document and adds
// it to the observed state passed to the function.
func WithObservedResourceJSON(name string, rawJSON []byte) TestFunctionOpt {
u := &unstructured.Unstructured{}
if err := json.Unmarshal(rawJSON, u); err != nil {
panic(err.Error())
}
return WithObservedResourceObject(name, u)
}
// AnnotationKeyResourceName is the key of the annotation that defines the
// resource name.
const AnnotationKeyResourceName = "fn.test/resource-name"
type AnnotatedObject interface {
GetAnnotations() map[string]string
}
// GetTestResourceName returns the resource key of the given object based on its
// annotation. It falls back to the "crossplane.io/composition-resource-name" if
// the explicit test annotation does not exists.
func GetTestResourceName(o AnnotatedObject) string {
ann := o.GetAnnotations()
if testAnn, exists := ann[AnnotationKeyResourceName]; exists {
return testAnn
}
return ann["crossplane.io/composition-resource-name"]
}
// WithObservedResourcesYAML reads all objects from a multi-document YAML and
// passes them with the observed state to the function.
//
// It uses the annotation [AnnotationKeyResourceName] to determine
// the name of the resource.
func WithObservedResourcesYAML(rawYAML []byte) TestFunctionOpt {
return func(tc *FunctionTest) {
uList, err := yaml.UnmarshalObjects[*unstructured.Unstructured](rawYAML)
if err != nil {
panic(err.Error())
}
for _, u := range uList {
key := GetTestResourceName(u)
if key == "" {
panic(fmt.Sprintf("resource has no name annotation: %s/%s", u.GroupVersionKind().String(), u.GetName()))
}
meta.RemoveAnnotations(u, AnnotationKeyResourceName)
str := mustObjectAsStruct(u)
tc.req.Observed.Resources[key] = &fnapi.Resource{
Resource: str,
// ConnectionDetails: str.GetFields()["connectionDetails"],
}
}
}
}
// WithObservedResourcesYAMLOverride loads the given objects from YAML and
// merges them with existing observed objects.
// It only modifies resources that are already observed.
func WithObservedResourcesYAMLOverride(rawYAML []byte) TestFunctionOpt {
return func(tc *FunctionTest) {
if tc.req.GetObserved() == nil || len(tc.req.GetObserved().GetResources()) == 0 {
return
}
uList, err := yaml.UnmarshalObjects[*unstructured.Unstructured](rawYAML)
if err != nil {
panic(err.Error())
}
for _, u := range uList {
key := GetTestResourceName(u)
if key == "" {
panic(fmt.Sprintf("resource has no name annotation: %s/%s", u.GroupVersionKind().String(), u.GetName()))
}
meta.RemoveAnnotations(u, AnnotationKeyResourceName)
observedRes, hasObservedResource := tc.req.GetObserved().GetResources()[key]
if !hasObservedResource {
panic(fmt.Sprintf("tried to override observed resource %s, which was not observed yet", key))
}
resRaw, err := protojson.Marshal(observedRes.GetResource())
if err != nil {
panic(errors.Wrap(err, key).Error())
}
original := map[string]interface{}{}
if err := json.Unmarshal(resRaw, &original); err != nil {
panic(errors.Wrap(err, key).Error())
}
u.Object = maps.Merge(original, u.Object)
str := mustObjectAsStruct(u)
tc.req.Observed.Resources[key] = &fnapi.Resource{
Resource: str,
}
}
}
}
// WithObservedConnectionSecrets expect and reads all ConnectionSecrets from a multi-document YAML and
// passes their data to the respective observed resources state to the function.
//
// It uses the annotation [AnnotationKeyResourceName] to determine
// the name of the resource.
func WithObservedConnectionSecrets(rawYAML []byte) TestFunctionOpt {
return func(tc *FunctionTest) {
uList, err := yaml.UnmarshalObjects[*corev1.Secret](rawYAML)
if err != nil {
panic(err.Error())
}
for _, u := range uList {
if u.Type != "connection.crossplane.io/v1alpha1" {
panic("Secret is not of type connection.crossplane.io/v1alpha1")
}
key, exists := u.GetAnnotations()[AnnotationKeyResourceName]
if !exists || key == "" {
panic("Secret has no name annotation")
}
meta.RemoveAnnotations(u, AnnotationKeyResourceName)
if tc.req.GetObserved().GetResources()[key] == nil {
panic("parent resource of the ConnectionSecret is not (yet) observed")
}
if u.Data == nil && u.StringData != nil {
u.Data = make(map[string][]byte)
for key, value := range u.StringData {
u.Data[key] = []byte(value)
}
}
tc.req.GetObserved().GetResources()[key].ConnectionDetails = u.Data
}
}
}
// WithObservedCompositeObject sets the observed composite to the given object.
func WithObservedCompositeObject(o runtime.Object, mods ...ResourceModifier) TestFunctionOpt {
return func(tc *FunctionTest) {
str := mustObjectAsStruct(o)
res := &fnapi.Resource{
Resource: str,
}
for _, mod := range mods {
mod(res)
}
tc.req.Observed.Composite = res
}
}
// WithObservedCompositeYAML reads an object from a single YAML document and
// passes it as observed composite to the function.
func WithObservedCompositeYAML(rawYAML []byte, mods ...ResourceModifier) TestFunctionOpt {
u := &unstructured.Unstructured{}
if err := yaml.Unmarshal(rawYAML, u); err != nil {
panic(err.Error())
}
return WithObservedCompositeObject(u, mods...)
}
// WithObservedCompositeJSON reads an object from a JSON document and
// passes it as observed composite to the function.
func WithObservedCompositeJSON(rawJSON []byte) TestFunctionOpt {
u := &unstructured.Unstructured{}
if err := json.Unmarshal(rawJSON, u); err != nil {
panic(err.Error())
}
return WithObservedCompositeObject(u)
}
var (
environmentGvk = schema.GroupVersionKind{
Group: "internal.crossplane.io",
Version: "v1alpha1",
Kind: "Environment",
}
)
// WithEnvironmentFromConfigsYAML is a custom test opt that creates an
// environment from a series of EnvironmentConfigs that are read from a
// multi-document YAML file and adds it as environment to the request
// context of a function.
//
// Experimental: Environments are a Crossplane alpha feature and are prone to
// change in the future. This applies to this functions as well.
func WithEnvironmentFromConfigsYAML(rawYAML []byte) TestFunctionOpt {
configs, err := yaml.UnmarshalObjects[*unstructured.Unstructured](rawYAML)
if err != nil {
panic(err.Error())
}
env := unstructured.Unstructured{
Object: map[string]interface{}{},
}
for _, c := range configs {
data, exists := c.Object["data"]
if !exists {
continue
}
dataMap, ok := data.(map[string]interface{})
if !ok {
continue
}
env.Object = maps.Merge(env.Object, dataMap)
}
// Environment Needs a kind because
env.SetGroupVersionKind(environmentGvk)
return WithContextValue(fncontext.KeyEnvironment, env.UnstructuredContent())
}
// WithEnvironmentFromConfigsYAMLMultiple is a custom test opt that creates an
// environment from a series of EnvironmentConfigs that are read from a
// multiple single-document YAML files and adds it as environment to the request
// context of a function.
//
// Experimental: Environments are a Crossplane alpha feature and are prone to
// change in the future. This applies to this functions as well.
func WithEnvironmentFromConfigsYAMLMultiple(rawMulitYAML ...[]byte) TestFunctionOpt {
env := unstructured.Unstructured{
Object: map[string]interface{}{},
}
for i, raw := range rawMulitYAML {
objects, err := yaml.UnmarshalObjects[*unstructured.Unstructured](raw)
if err != nil {
panic(errors.Wrapf(err, "cannot unmarshal file at index %d", i).Error())
}
for _, o := range objects {
data, exists := o.Object["data"]
if !exists {
continue
}
dataMap, ok := data.(map[string]interface{})
if !ok {
continue
}
env.Object = maps.Merge(env.Object, dataMap)
}
}
// Environment Needs a kind because
env.SetGroupVersionKind(environmentGvk)
return WithContextValue(fncontext.KeyEnvironment, env.UnstructuredContent())
}