| 1 |
// Copyright 2022 The Kubernetes Authors. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package nameref |
| 5 |
|
| 6 |
import ( |
| 7 |
"strings" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/stretchr/testify/assert" |
| 11 |
"sigs.k8s.io/kustomize/kyaml/yaml" |
| 12 |
) |
| 13 |
|
| 14 |
func SeqFilter(node *yaml.RNode) (*yaml.RNode, error) { |
| 15 |
if node.YNode().Value == "aaa" { |
| 16 |
node.YNode().SetString("ccc") |
| 17 |
} |
| 18 |
return node, nil |
| 19 |
} |
| 20 |
|
| 21 |
func TestApplyFilterToSeq(t *testing.T) { |
| 22 |
fltr := yaml.FilterFunc(SeqFilter) |
| 23 |
|
| 24 |
testCases := map[string]struct { |
| 25 |
input string |
| 26 |
expect string |
| 27 |
}{ |
| 28 |
"replace in seq": { |
| 29 |
input: ` |
| 30 |
- aaa |
| 31 |
- bbb`, |
| 32 |
expect: ` |
| 33 |
- ccc |
| 34 |
- bbb`, |
| 35 |
}, |
| 36 |
} |
| 37 |
|
| 38 |
for tn, tc := range testCases { |
| 39 |
t.Run(tn, func(t *testing.T) { |
| 40 |
node, err := yaml.Parse(tc.input) |
| 41 |
if err != nil { |
| 42 |
t.Fatal(err) |
| 43 |
} |
| 44 |
err = applyFilterToSeq(fltr, node) |
| 45 |
if err != nil { |
| 46 |
t.Fatal(err) |
| 47 |
} |
| 48 |
if !assert.Equal(t, |
| 49 |
strings.TrimSpace(tc.expect), |
| 50 |
strings.TrimSpace(node.MustString())) { |
| 51 |
t.Fatalf("expect:\n%s\nactual:\n%s", |
| 52 |
strings.TrimSpace(tc.expect), |
| 53 |
strings.TrimSpace(node.MustString())) |
| 54 |
} |
| 55 |
}) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
func TestApplyFilterToSeqUnhappy(t *testing.T) { |
| 60 |
fltr := yaml.FilterFunc(SeqFilter) |
| 61 |
|
| 62 |
testCases := map[string]struct { |
| 63 |
input string |
| 64 |
}{ |
| 65 |
"replace in seq": { |
| 66 |
input: ` |
| 67 |
aaa`, |
| 68 |
}, |
| 69 |
} |
| 70 |
|
| 71 |
for tn, tc := range testCases { |
| 72 |
t.Run(tn, func(t *testing.T) { |
| 73 |
node, err := yaml.Parse(tc.input) |
| 74 |
if err != nil { |
| 75 |
t.Fatal(err) |
| 76 |
} |
| 77 |
err = applyFilterToSeq(fltr, node) |
| 78 |
if err == nil { |
| 79 |
t.Fatalf("expect an error") |
| 80 |
} |
| 81 |
}) |
| 82 |
} |
| 83 |
} |