-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalues.go
More file actions
67 lines (59 loc) · 1.9 KB
/
Copy pathvalues.go
File metadata and controls
67 lines (59 loc) · 1.9 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
package helpers
import (
"encoding/json"
"fmt"
k8syaml "sigs.k8s.io/yaml"
"github.com/deckhouse/module-sdk/pkg"
patchablevalues "github.com/deckhouse/module-sdk/pkg/patchable-values"
)
// NewValues constructs a real pkg.PatchableValuesCollector seeded with the
// provided map. Use it when the hook under test should observe a working
// values store rather than a mock.
//
// Tests can then assert on the patches the hook produced via GetPatches().
func NewValues(initial map[string]any) pkg.PatchableValuesCollector {
if initial == nil {
initial = map[string]any{}
}
v, err := patchablevalues.NewPatchableValues(initial)
if err != nil {
panic(fmt.Errorf("helpers.NewValues: %w", err))
}
return v
}
// NewValuesFromJSON is like NewValues but parses a JSON document.
// Empty or whitespace-only input is treated as `{}`.
func NewValuesFromJSON(raw string) pkg.PatchableValuesCollector {
return NewValues(parseJSONOrYAML(raw))
}
// NewValuesFromYAML is like NewValues but parses a YAML document.
// Empty or whitespace-only input is treated as `{}`.
func NewValuesFromYAML(raw string) pkg.PatchableValuesCollector {
return NewValues(parseJSONOrYAML(raw))
}
func parseJSONOrYAML(raw string) map[string]any {
if raw == "" {
return map[string]any{}
}
var out map[string]any
if err := k8syaml.Unmarshal([]byte(raw), &out); err != nil {
panic(fmt.Errorf("helpers: parse values: %w", err))
}
if out == nil {
out = map[string]any{}
}
return out
}
// MarshalValues returns the JSON encoding of the patch operations recorded
// on the values collector. It is a small convenience for snapshot-style
// assertions:
//
// require.JSONEq(t, `[{"op":"add","path":"/foo","value":"bar"}]`,
// string(helpers.MarshalValues(values)))
func MarshalValues(v pkg.PatchableValuesCollector) []byte {
out, err := json.Marshal(v.GetPatches())
if err != nil {
panic(fmt.Errorf("helpers.MarshalValues: %w", err))
}
return out
}