github.com/kaptinlin/jsonschema@v0.4.6/tests/minLength_test.go (about)

     1  package tests
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/goccy/go-json"
     7  	"github.com/kaptinlin/jsonschema"
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestSchemaWithMinLength(t *testing.T) {
    13  	testCases := []struct {
    14  		name           string
    15  		schemaJSON     string
    16  		expectedSchema jsonschema.Schema
    17  	}{
    18  		{
    19  			name: "MinLength validation",
    20  			schemaJSON: `{
    21  				"type": "string",
    22  				"minLength": 2
    23  			}`,
    24  			expectedSchema: jsonschema.Schema{
    25  				Type:      jsonschema.SchemaType{"string"},
    26  				MinLength: ptrFloat64(2),
    27  			},
    28  		},
    29  		{
    30  			name: "MinLength validation with decimal",
    31  			schemaJSON: `{
    32  				"type": "string",
    33  				"minLength": 2.0
    34  			}`,
    35  			expectedSchema: jsonschema.Schema{
    36  				Type:      jsonschema.SchemaType{"string"},
    37  				MinLength: ptrFloat64(2.0),
    38  			},
    39  		},
    40  	}
    41  
    42  	for _, tc := range testCases {
    43  		t.Run(tc.name, func(t *testing.T) {
    44  			var schema jsonschema.Schema
    45  			err := json.Unmarshal([]byte(tc.schemaJSON), &schema)
    46  			require.NoError(t, err, "Unmarshalling failed unexpectedly")
    47  			assert.Equal(t, tc.expectedSchema.ID, schema.ID)
    48  			assert.Equal(t, tc.expectedSchema.Schema, schema.Schema)
    49  			assert.Equal(t, tc.expectedSchema.Type, schema.Type)
    50  
    51  			// Now test marshaling back to JSON
    52  			marshaledJSON, err := json.Marshal(schema)
    53  			require.NoError(t, err, "Marshalling failed unexpectedly")
    54  
    55  			// Unmarshal marshaled JSON to verify it matches the original schema object
    56  			var reUnmarshaledSchema jsonschema.Schema
    57  			err = json.Unmarshal(marshaledJSON, &reUnmarshaledSchema)
    58  			require.NoError(t, err, "Unmarshalling the marshaled JSON failed")
    59  			assert.Equal(t, schema, reUnmarshaledSchema, "Re-unmarshaled schema does not match the original")
    60  
    61  			// Check if the marshaled JSON matches the original JSON input
    62  			assert.JSONEq(t, tc.schemaJSON, string(marshaledJSON), "The marshaled JSON should match the original input JSON")
    63  		})
    64  	}
    65  }
    66  
    67  // TestMinLengthForTestSuite executes the minLength validation tests for Schema Test Suite.
    68  func TestMinLengthForTestSuite(t *testing.T) {
    69  	testJSONSchemaTestSuiteWithFilePath(t, "../testdata/JSON-Schema-Test-Suite/tests/draft2020-12/minLength.json")
    70  }