github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/graphql/json_test.go (about)

     1  package graphql
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  
     7  	"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
     8  
     9  	"github.com/pkg/errors"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestJSON_UnmarshalGQL(t *testing.T) {
    15  	for name, tc := range map[string]struct {
    16  		input         interface{}
    17  		expected      JSON
    18  		expectedError error
    19  	}{
    20  		//given
    21  		"correct input: object": {
    22  			input:         `{"schema":"schema"}`,
    23  			expected:      JSON(`{"schema":"schema"}`),
    24  			expectedError: nil,
    25  		},
    26  		"correct input: string": {
    27  			input:         `"test"`,
    28  			expected:      JSON(`"test"`),
    29  			expectedError: nil,
    30  		},
    31  		"correct input: number": {
    32  			input:         `11`,
    33  			expected:      JSON(`11`),
    34  			expectedError: nil,
    35  		},
    36  		"error: input is nil": {
    37  			input:         nil,
    38  			expected:      "",
    39  			expectedError: apperrors.NewInvalidDataError("input should not be nil"),
    40  		},
    41  		"error: invalid input": {
    42  			input:         123,
    43  			expected:      "",
    44  			expectedError: errors.New("unexpected input type: int, should be string"),
    45  		},
    46  	} {
    47  		t.Run(name, func(t *testing.T) {
    48  			// WHEN
    49  			var j JSON
    50  			err := j.UnmarshalGQL(tc.input)
    51  
    52  			if tc.expectedError == nil {
    53  				require.NoError(t, err)
    54  			} else {
    55  				require.EqualError(t, err, tc.expectedError.Error())
    56  			}
    57  			assert.Equal(t, tc.expected, j)
    58  		})
    59  	}
    60  }
    61  
    62  func TestJSON_MarshalGQL(t *testing.T) {
    63  	for name, tc := range map[string]struct {
    64  		input    JSON
    65  		expected string
    66  	}{
    67  		//given
    68  		"object": {
    69  			input:    JSON(`{"schema":"schema"}`),
    70  			expected: `"{\"schema\":\"schema\"}"`,
    71  		},
    72  		"number": {
    73  			input:    JSON(`11`),
    74  			expected: "\"11\"",
    75  		},
    76  	} {
    77  		t.Run(name, func(t *testing.T) {
    78  			buf := bytes.Buffer{}
    79  
    80  			tc.input.MarshalGQL(&buf)
    81  
    82  			require.Equal(t, tc.expected, buf.String())
    83  		})
    84  	}
    85  }