github.com/crossplane/upjet@v1.3.0/pkg/resource/json/canonical_test.go (about)

     1  // SPDX-FileCopyrightText: 2024 The Crossplane Authors <https://crossplane.io>
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package json
     6  
     7  import (
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/crossplane/crossplane-runtime/pkg/test"
    14  	"github.com/google/go-cmp/cmp"
    15  	"github.com/pkg/errors"
    16  )
    17  
    18  func TestCanonicalize(t *testing.T) {
    19  	tests := map[string]struct {
    20  		inputFile    string
    21  		expectedFile string
    22  		err          error
    23  	}{
    24  		"SuccessfulObjectConversion": {
    25  			inputFile:    "policy.json",
    26  			expectedFile: "policy_canonical.json",
    27  		},
    28  		"SuccessfulArrayConversion": {
    29  			inputFile:    "array.json",
    30  			expectedFile: "array_canonical.json",
    31  		},
    32  		"NoopConversion": {
    33  			inputFile:    "policy_canonical.json",
    34  			expectedFile: "policy_canonical.json",
    35  		},
    36  		"InvalidJSON": {
    37  			inputFile: "invalid.json",
    38  			err:       errors.Wrap(errors.New(`ReadString: expects " or n, but found }, error found in #10 byte of ...|"a": "b",}|..., bigger context ...|{"a": "b",}|...`), `failed to unmarshal the JSON document: {"a": "b",}`),
    39  		},
    40  	}
    41  
    42  	for name, tc := range tests {
    43  		t.Run(name, func(t *testing.T) {
    44  			input, err := os.ReadFile(filepath.Join("testdata", tc.inputFile))
    45  			if err != nil {
    46  				t.Fatalf("Failed to read the input file: %v", err)
    47  			}
    48  
    49  			expectedOutput := ""
    50  			if tc.expectedFile != "" {
    51  				output, err := os.ReadFile(filepath.Join("testdata", tc.expectedFile))
    52  				if err != nil {
    53  					t.Fatalf("Failed to read expected the output file: %v", err)
    54  				}
    55  				expectedOutput = strings.TrimSpace(string(output))
    56  			}
    57  
    58  			inputJSON := strings.TrimSpace(string(input))
    59  			canonicalJSON, err := Canonicalize(inputJSON)
    60  			if err != nil {
    61  				if diff := cmp.Diff(tc.err, err, test.EquateErrors()); diff != "" {
    62  					t.Fatalf("Canonicalize(...): -wantErr, +gotErr: %s", diff)
    63  				}
    64  				return
    65  			}
    66  			if diff := cmp.Diff(expectedOutput, canonicalJSON); diff != "" {
    67  				t.Errorf("Canonicalize(...): -want, +got: \n%s", diff)
    68  			}
    69  		})
    70  	}
    71  }