github.com/kaptinlin/jsonschema@v0.4.6/tests/id_test.go (about) 1 package tests 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 "github.com/stretchr/testify/require" 8 9 "github.com/goccy/go-json" 10 "github.com/kaptinlin/jsonschema" 11 ) 12 13 // TestIDForTestSuite executes the id validation tests for Schema Test Suite. 14 func TestIDForTestSuite(t *testing.T) { 15 testJSONSchemaTestSuiteWithFilePath(t, "../testdata/JSON-Schema-Test-Suite/tests/draft2020-12/optional/id.json") 16 } 17 18 func TestSchemaWithID(t *testing.T) { 19 testCases := []struct { 20 name string 21 schemaJSON string 22 expectedSchema jsonschema.Schema 23 }{ 24 { 25 name: "Basic Schema with $id and $schema", 26 schemaJSON: `{ 27 "$id": "http://yourdomain.com/schemas/myschema.json", 28 "$schema": "https://json-schema.org/draft/2020-12/schema", 29 "type": "object" 30 }`, 31 expectedSchema: jsonschema.Schema{ 32 ID: "http://yourdomain.com/schemas/myschema.json", 33 Schema: "https://json-schema.org/draft/2020-12/schema", 34 Type: jsonschema.SchemaType{"object"}, 35 }, 36 }, 37 { 38 name: "Nested Schema with Properties and $id", 39 schemaJSON: `{ 40 "$id": "http://yourdomain.com/schemas/nested.json", 41 "$schema": "https://json-schema.org/draft/2020-12/schema", 42 "type": "object", 43 "properties": { 44 "name": {"type": "string"} 45 } 46 }`, 47 expectedSchema: jsonschema.Schema{ 48 ID: "http://yourdomain.com/schemas/nested.json", 49 Schema: "https://json-schema.org/draft/2020-12/schema", 50 Type: jsonschema.SchemaType{"object"}, 51 Properties: &jsonschema.SchemaMap{ 52 "name": &jsonschema.Schema{ 53 Type: jsonschema.SchemaType{"string"}, 54 }, 55 }, 56 }, 57 }, 58 } 59 60 for _, tc := range testCases { 61 t.Run(tc.name, func(t *testing.T) { 62 var schema jsonschema.Schema 63 err := json.Unmarshal([]byte(tc.schemaJSON), &schema) 64 require.NoError(t, err, "Unmarshalling failed unexpectedly") 65 assert.Equal(t, tc.expectedSchema.ID, schema.ID) 66 assert.Equal(t, tc.expectedSchema.Schema, schema.Schema) 67 assert.Equal(t, tc.expectedSchema.Type, schema.Type) 68 69 // Now test marshaling back to JSON 70 marshaledJSON, err := json.Marshal(schema) 71 require.NoError(t, err, "Marshalling failed unexpectedly") 72 73 // Unmarshal marshaled JSON to verify it matches the original schema object 74 var reUnmarshaledSchema jsonschema.Schema 75 err = json.Unmarshal(marshaledJSON, &reUnmarshaledSchema) 76 require.NoError(t, err, "Unmarshalling the marshaled JSON failed") 77 assert.Equal(t, schema, reUnmarshaledSchema, "Re-unmarshaled schema does not match the original") 78 79 // Check if the marshaled JSON matches the original JSON input 80 assert.JSONEq(t, tc.schemaJSON, string(marshaledJSON), "The marshaled JSON should match the original input JSON") 81 }) 82 } 83 }