From a7a28a85a4706506572d027750b5aa31b52e1c7e Mon Sep 17 00:00:00 2001 From: Phillip Wittrock Date: Fri, 3 Jan 2020 12:33:28 -0800 Subject: [PATCH] Fix `kio` sorting for files with more than 9 Resources --- kyaml/kio/kioutil/kioutil.go | 2 +- kyaml/kio/kioutil/kioutil_test.go | 77 +++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 kyaml/kio/kioutil/kioutil_test.go diff --git a/kyaml/kio/kioutil/kioutil.go b/kyaml/kio/kioutil/kioutil.go index 7a3afaf4d..56e8b74a5 100644 --- a/kyaml/kio/kioutil/kioutil.go +++ b/kyaml/kio/kioutil/kioutil.go @@ -136,7 +136,7 @@ func SortNodes(nodes []*yaml.RNode) error { return false } if iIndex != jIndex { - return iValue < jValue + return iIndex < jIndex } // elements are equal diff --git a/kyaml/kio/kioutil/kioutil_test.go b/kyaml/kio/kioutil/kioutil_test.go new file mode 100644 index 000000000..2ee1615bc --- /dev/null +++ b/kyaml/kio/kioutil/kioutil_test.go @@ -0,0 +1,77 @@ +// Copyright 2019 The Kubernetes Authors. +// SPDX-License-Identifier: Apache-2.0 + +package kioutil_test + +import ( + "bytes" + "math/rand" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "sigs.k8s.io/kustomize/kyaml/kio" + "sigs.k8s.io/kustomize/kyaml/kio/kioutil" +) + +func TestSortNodes_moreThan10(t *testing.T) { + input := ` +a: b +--- +c: d +--- +e: f +--- +g: h +--- +i: j +--- +k: l +--- +m: n +--- +o: p +--- +q: r +--- +s: t +--- +u: v +--- +w: x +--- +y: z +` + actual := &bytes.Buffer{} + rw := kio.ByteReadWriter{Reader: bytes.NewBufferString(input), Writer: actual} + nodes, err := rw.Read() + if !assert.NoError(t, err) { + t.Fail() + } + + // randomize the list + rand.Seed(time.Now().UnixNano()) + rand.Shuffle(len(nodes), func(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] }) + + // sort them back into their original order + if !assert.NoError(t, kioutil.SortNodes(nodes)) { + t.Fail() + } + + // check the sorted values + expected := strings.Split(input, "---") + for i := range nodes { + a := strings.TrimSpace(nodes[i].MustString()) + b := strings.TrimSpace(expected[i]) + if !assert.Contains(t, a, b) { + t.Fail() + } + } + + if !assert.NoError(t, rw.Write(nodes)) { + t.Fail() + } + + assert.Equal(t, strings.TrimSpace(input), strings.TrimSpace(actual.String())) +}