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