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