github.com/myhau/pulumi/pkg/v3@v3.70.2-0.20221116134521-f2775972e587/util/yamlutil/node_tools_test.go (about)

     1  package yamlutil
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"gopkg.in/yaml.v3"
     9  )
    10  
    11  func assertYaml(t *testing.T, before, after string, mutation func(node *yaml.Node) error) {
    12  	t.Helper()
    13  	var beforeNode yaml.Node
    14  	err := yaml.Unmarshal([]byte(before), &beforeNode)
    15  	assert.NoError(t, err)
    16  	err = mutation(&beforeNode)
    17  	assert.NoError(t, err)
    18  	afterBytes, err := yaml.Marshal(beforeNode.Content[0])
    19  	assert.NoError(t, err)
    20  
    21  	assert.Equal(t, strings.TrimSpace(after), strings.TrimSpace(string(afterBytes)))
    22  }
    23  
    24  func TestInsertNode(t *testing.T) {
    25  	t.Parallel()
    26  
    27  	assertYaml(t, `
    28  foo: baz
    29  `, `
    30  foo: bar
    31  `, func(node *yaml.Node) error { return Insert(node, "foo", "bar") })
    32  }
    33  
    34  func TestInsertNodeNew(t *testing.T) {
    35  	t.Parallel()
    36  
    37  	assertYaml(t, `
    38  # comment
    39  existing: node # comment
    40  `, `
    41  # comment
    42  existing: node # comment
    43  foo: bar
    44  `, func(node *yaml.Node) error { return Insert(node, "foo", "bar") })
    45  }
    46  
    47  func TestInsertNodeOverwrite(t *testing.T) {
    48  	t.Parallel()
    49  
    50  	assertYaml(t, `
    51  foo: 1
    52  # header
    53  bar: 2 # this should become 42
    54  # trailer
    55  quux: 3
    56  `, `
    57  foo: 1
    58  # header
    59  bar: 42
    60  # trailer
    61  quux: 3
    62  `, func(node *yaml.Node) error { return Insert(node, "bar", "42") })
    63  }
    64  
    65  func TestDeleteNode(t *testing.T) {
    66  	t.Parallel()
    67  
    68  	assertYaml(t, `
    69  foo: 1
    70  # header
    71  bar: 2 # this should become 42
    72  # trailer
    73  quux: 3
    74  `, `
    75  foo: 1
    76  # trailer
    77  quux: 3
    78  `, func(node *yaml.Node) error { return Delete(node, "bar") })
    79  }