get.porter.sh/porter@v1.3.0/pkg/yaml/yq_test.go (about)

     1  package yaml_test
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  
     8  	"get.porter.sh/porter/pkg/config"
     9  	"get.porter.sh/porter/pkg/portercontext"
    10  	"get.porter.sh/porter/pkg/yaml"
    11  	"github.com/mikefarah/yq/v3/pkg/yqlib"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestEditor_WalkNodes(t *testing.T) {
    16  	pCtx := portercontext.NewTestContext(t)
    17  	defer pCtx.Close()
    18  	pCtx.AddTestFile("testdata/custom.yaml", config.Name)
    19  
    20  	e := yaml.NewEditor(pCtx.FileSystem)
    21  	err := e.ReadFile(config.Name)
    22  	require.NoError(t, err)
    23  
    24  	testcases := []struct {
    25  		name       string
    26  		path       string
    27  		totalNodes int
    28  		wantErr    error
    29  	}{
    30  		{name: "success", path: "root.array.**.a", totalNodes: 2},
    31  		{name: "no matching nodes found", path: "hello", totalNodes: 0},
    32  		{name: "exit walking on first error", path: "root.array", totalNodes: 1, wantErr: errors.New("failed callback")},
    33  	}
    34  	for _, tc := range testcases {
    35  		t.Run(tc.name, func(t *testing.T) {
    36  			var totalNodes int
    37  			err = e.WalkNodes(context.Background(), tc.path, func(ctx context.Context, nc *yqlib.NodeContext) error {
    38  				totalNodes += 1
    39  				return tc.wantErr
    40  			})
    41  
    42  			require.Equal(t, tc.totalNodes, totalNodes)
    43  			require.Equal(t, tc.wantErr, err)
    44  		})
    45  	}
    46  
    47  }