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