github.com/chainguard-dev/yam@v0.0.7/pkg/yam/formatted/encoder_test.go (about)

     1  package formatted
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/chainguard-dev/yam/pkg/yam/formatted/path"
     9  	"github.com/google/go-cmp/cmp"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  	"gopkg.in/yaml.v3"
    13  )
    14  
    15  const (
    16  	sorted   = "- a\n- b\n- c\n"
    17  	unsorted = "- c\n- a\n- b\n"
    18  )
    19  
    20  func TestEncoder_AutomaticConfig(t *testing.T) {
    21  	t.Run("gracefully handles missing config file", func(t *testing.T) {
    22  		err := os.Chdir("testdata/empty-dir")
    23  		require.NoError(t, err)
    24  
    25  		w := new(bytes.Buffer)
    26  
    27  		assert.NotPanics(t, func() {
    28  			_ = NewEncoder(w).AutomaticConfig()
    29  		})
    30  	})
    31  }
    32  
    33  func TestSortingSequence(t *testing.T) {
    34  	tests := []struct {
    35  		sortExpression string
    36  		nodePath       string
    37  		want           string
    38  	}{
    39  		{sortExpression: ".sorted", nodePath: ".sorted", want: sorted},
    40  		{sortExpression: ".notsorted", nodePath: ".sorted", want: unsorted},
    41  		{sortExpression: ".sorted", nodePath: ".notsorted", want: unsorted},
    42  	}
    43  	for _, tc := range tests {
    44  		// Create an unsorted sequence.
    45  		node := &yaml.Node{
    46  			Kind: yaml.SequenceNode,
    47  			Content: []*yaml.Node{
    48  				{Kind: yaml.ScalarNode, Value: "c"},
    49  				{Kind: yaml.ScalarNode, Value: "a"},
    50  				{Kind: yaml.ScalarNode, Value: "b"},
    51  			},
    52  		}
    53  
    54  		var out bytes.Buffer
    55  		encoder := NewEncoder(&out)
    56  		encoder = encoder.SetIndent(2)
    57  		encoder, err := encoder.SetSortExpressions(tc.sortExpression)
    58  		if err != nil {
    59  			t.Fatalf("Failed to SetSortExpressions for %s: %+v", tc.sortExpression, err)
    60  		}
    61  		nodePath, err := path.Parse(tc.nodePath)
    62  		if err != nil {
    63  			t.Fatalf("failed to parse path: %+v", err)
    64  		}
    65  		got, err := encoder.marshalSequence(node, nodePath)
    66  		if err != nil {
    67  			t.Errorf("Failed to marshal sequence: %+v", err)
    68  		}
    69  		if diff := cmp.Diff(tc.want, string(got)); diff != "" {
    70  			t.Errorf("Not sorted: %s", diff)
    71  		}
    72  	}
    73  }