Debian Codegraph @

helpers/schema_compiler_test.go

raw
1 package helpers
2
3 import (
4 "encoding/json"
5 "fmt"
6 "testing"
7 "unicode"
8
9 "github.com/stretchr/testify/assert"
10 "github.com/stretchr/testify/require"
11
12 "github.com/pb33f/libopenapi-validator/config"
13 )
14
15 // A few simple JSON Schemas
16 const stringSchema = `{
17 "type": "string",
18 "format": "date",
19 "minLength": 10
20 }`
21
22 const objectSchema = `{
23 "type": "object",
24 "title" : "Fish",
25 "properties" : {
26 "name" : {
27 "type": "string",
28 "description": "The given name of the fish"
29 },
30 "name" : {
31 "type": "string",
32 "format": "capital",
33 "description": "The given name of the fish"
34 },
35 "species" : {
36 "type" : "string",
37 "enum" : [ "OTHER", "GUPPY", "PIKE", "BASS" ]
38 }
39 }
40 }`
41
42 func Test_SchemaWithNilOptions(t *testing.T) {
43 jsch, err := NewCompiledSchema("test", []byte(stringSchema), nil)
44
45 require.NoError(t, err, "Failed to compile Schema")
46 require.NotNil(t, jsch, "Did not return a compiled schema")
47 }
48
49 func Test_SchemaWithDefaultOptions(t *testing.T) {
50 valOptions := config.NewValidationOptions()
51 jsch, err := NewCompiledSchema("test", []byte(stringSchema), valOptions)
52
53 require.NoError(t, err, "Failed to compile Schema")
54 require.NotNil(t, jsch, "Did not return a compiled schema")
55 }
56
57 func Test_SchemaWithOptions(t *testing.T) {
58 valOptions := config.NewValidationOptions(
59 config.WithFormatAssertions(),
60 config.WithContentAssertions(),
61 config.WithCustomFormat("capital", func(v any) error {
62 s, ok := v.(string)
63 if !ok {
64 return fmt.Errorf("expected string")
65 }
66
67 if s == "" {
68 return nil
69 }
70
71 r := []rune(s)[0]
72
73 if !unicode.IsUpper(r) {
74 return fmt.Errorf("expected first latter to be uppercase")
75 }
76
77 return nil
78 }),
79 )
80
81 jsch, err := NewCompiledSchema("test", []byte(stringSchema), valOptions)
82
83 require.NoError(t, err, "Failed to compile Schema")
84 require.NotNil(t, jsch, "Did not return a compiled schema")
85 }
86
87 func Test_ObjectSchema(t *testing.T) {
88 valOptions := config.NewValidationOptions()
89 jsch, err := NewCompiledSchema("test", []byte(objectSchema), valOptions)
90
91 require.NoError(t, err, "Failed to compile Schema")
92 require.NotNil(t, jsch, "Did not return a compiled schema")
93 }
94
95 func Test_ValidJSONSchemaWithInvalidContent(t *testing.T) {
96 // An example of a dubious JSON Schema
97 const badSchema = `{
98 "type": "you-dont-know-me",
99 "format": "date",
100 "minLength": 10
101 }`
102
103 jsch, err := NewCompiledSchema("test", []byte(badSchema), nil)
104
105 assert.Error(t, err, "Expected an error to be thrown")
106 assert.Nil(t, jsch, "invalid schema compiled!")
107 }
108
109 func Test_MalformedSONSchema(t *testing.T) {
110 // An example of a JSON schema with malformed JSON
111 const badSchema = `{
112 "type": "you-dont-know-me",
113 "format": "date"
114 "minLength": 10
115 }`
116
117 jsch, err := NewCompiledSchema("test", []byte(badSchema), nil)
118
119 assert.Error(t, err, "Expected an error to be thrown")
120 assert.Nil(t, jsch, "invalid schema compiled!")
121 }
122
123 func Test_ValidJSONSchemaWithIncompleteContent(t *testing.T) {
124 // An example of a dJSON schema with references to non-existent stuff
125 const incompleteSchema = `{
126 "type": "object",
127 "title" : "unresolvable",
128 "properties" : {
129 "name" : {
130 "type": "string",
131 },
132 "species" : {
133 "$ref": "#/$defs/speciesEnum"
134 }
135 }
136 }`
137
138 jsch, err := NewCompiledSchema("test", []byte(incompleteSchema), nil)
139
140 assert.Error(t, err, "Expected an error to be thrown")
141 assert.Nil(t, jsch, "invalid schema compiled!")
142 }
143
144 // Additional comprehensive tests for version-aware schema compilation
145
146 func TestNewCompiledSchemaWithVersion_OpenAPIMode_Version30(t *testing.T) {
147 schemaJSON := `{
148 "type": "string",
149 "nullable": true
150 }`
151
152 options := config.NewValidationOptions(
153 config.WithOpenAPIMode(),
154 )
155
156 // Test version 3.0 (< 3.05)
157 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.0)
158 require.NoError(t, err, "Should compile OpenAPI 3.0 schema with nullable")
159 require.NotNil(t, jsch, "Should return compiled schema")
160 }
161
162 func TestNewCompiledSchemaWithVersion_OpenAPIMode_Version31(t *testing.T) {
163 schemaJSON := `{
164 "type": "string"
165 }`
166
167 options := config.NewValidationOptions(
168 config.WithOpenAPIMode(),
169 )
170
171 // Test version 3.1 (>= 3.05)
172 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.1)
173 require.NoError(t, err, "Should compile OpenAPI 3.1 schema")
174 require.NotNil(t, jsch, "Should return compiled schema")
175 }
176
177 func TestNewCompiledSchemaWithVersion_OpenAPIMode_Version32(t *testing.T) {
178 schemaJSON := `{
179 "type": "string"
180 }`
181
182 options := config.NewValidationOptions(
183 config.WithOpenAPIMode(),
184 )
185
186 // Test version 3.2 (>= 3.15)
187 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.2)
188 require.NoError(t, err, "Should compile OpenAPI 3.2 schema")
189 require.NotNil(t, jsch, "Should return compiled schema")
190 }
191
192 func TestNewCompiledSchemaWithVersion_OpenAPIMode_Version32_NullableRejected(t *testing.T) {
193 schemaJSON := `{
194 "type": "string",
195 "nullable": true
196 }`
197
198 options := config.NewValidationOptions(
199 config.WithOpenAPIMode(),
200 )
201
202 // Test version 3.2 (>= 3.15) with nullable should fail (same as 3.1+)
203 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.2)
204 assert.Error(t, err, "Should fail for nullable in OpenAPI 3.2")
205 assert.Nil(t, jsch, "Should not return compiled schema")
206 assert.Contains(t, err.Error(), "The `nullable` keyword is not supported in OpenAPI 3.1+")
207 }
208
209 func TestNewCompiledSchemaWithVersion_OpenAPIMode_Version31_NullableRejected(t *testing.T) {
210 schemaJSON := `{
211 "type": "string",
212 "nullable": true
213 }`
214
215 options := config.NewValidationOptions(
216 config.WithOpenAPIMode(),
217 )
218
219 // Test version 3.1 (>= 3.05) with nullable should fail
220 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.1)
221 assert.Error(t, err, "Should fail for nullable in OpenAPI 3.1")
222 assert.Nil(t, jsch, "Should not return compiled schema")
223 assert.Contains(t, err.Error(), "The `nullable` keyword is not supported in OpenAPI 3.1+")
224 }
225
226 func TestNewCompiledSchemaWithVersion_OpenAPIMode_ScalarCoercion(t *testing.T) {
227 schemaJSON := `{
228 "type": "boolean"
229 }`
230
231 options := config.NewValidationOptions(
232 config.WithOpenAPIMode(),
233 config.WithScalarCoercion(),
234 )
235
236 // Test with scalar coercion enabled
237 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.0)
238 require.NoError(t, err, "Should compile with scalar coercion")
239 require.NotNil(t, jsch, "Should return compiled schema")
240
241 // Test that coercion works
242 err = jsch.Validate("true")
243 assert.NoError(t, err, "Should allow string 'true' for boolean with coercion")
244
245 err = jsch.Validate("invalid")
246 assert.Error(t, err, "Should reject invalid boolean string")
247 }
248
249 func TestNewCompiledSchemaWithVersion_OpenAPIMode_NoScalarCoercion(t *testing.T) {
250 schemaJSON := `{
251 "type": "boolean"
252 }`
253
254 options := config.NewValidationOptions(
255 config.WithOpenAPIMode(),
256 )
257
258 // Test with scalar coercion disabled (default)
259 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.0)
260 require.NoError(t, err, "Should compile without scalar coercion")
261 require.NotNil(t, jsch, "Should return compiled schema")
262
263 // Test that coercion doesn't work
264 err = jsch.Validate("true")
265 assert.Error(t, err, "Should reject string 'true' for boolean without coercion")
266
267 err = jsch.Validate(true)
268 assert.NoError(t, err, "Should accept actual boolean value")
269 }
270
271 func TestNewCompiledSchemaWithVersion_NonOpenAPIMode(t *testing.T) {
272 schemaJSON := `{
273 "type": "string",
274 "nullable": true
275 }`
276
277 options := config.NewValidationOptions()
278 // OpenAPIMode is false by default
279
280 // Test that OpenAPI keywords are ignored when not in OpenAPI mode
281 jsch, err := NewCompiledSchemaWithVersion("test", []byte(schemaJSON), options, 3.0)
282 require.NoError(t, err, "Should compile in non-OpenAPI mode")
283 require.NotNil(t, jsch, "Should return compiled schema")
284
285 // String values should pass when OpenAPI mode is disabled
286 err = jsch.Validate("test")
287 assert.NoError(t, err, "Should accept string values")
288
289 // When OpenAPI mode is disabled, nullable is ignored by JSON Schema
290 // The behavior with null depends on the JSON Schema version and mode
291 }
292
293 func TestTransformOpenAPI30Schema_ValidJSON(t *testing.T) {
294 input := []byte(`{
295 "type": "string",
296 "nullable": true
297 }`)
298
299 result := transformOpenAPI30Schema(input)
300
301 var schema map[string]interface{}
302 err := json.Unmarshal(result, &schema)
303 require.NoError(t, err, "Result should be valid JSON")
304
305 // Check that nullable was transformed
306 schemaType, ok := schema["type"]
307 assert.True(t, ok, "Should have type field")
308
309 typeArray, ok := schemaType.([]interface{})
310 assert.True(t, ok, "Type should be an array")
311 assert.Contains(t, typeArray, "string")
312 assert.Contains(t, typeArray, "null")
313
314 _, hasNullable := schema["nullable"]
315 assert.False(t, hasNullable, "Should not have nullable field after transformation")
316 }
317
318 func TestTransformOpenAPI30Schema_InvalidJSON(t *testing.T) {
319 input := []byte(`{invalid json}`)
320
321 result := transformOpenAPI30Schema(input)
322
323 // Should return original when invalid
324 assert.Equal(t, input, result)
325 }
326
327 func TestTransformNullableInSchema_MapWithNullableTrue(t *testing.T) {
328 schema := map[string]interface{}{
329 "type": "string",
330 "nullable": true,
331 }
332
333 result := transformOAS30Keywords(schema)
334
335 resultMap, ok := result.(map[string]interface{})
336 require.True(t, ok)
337
338 schemaType, ok := resultMap["type"]
339 require.True(t, ok)
340
341 typeArray, ok := schemaType.([]interface{})
342 require.True(t, ok)
343 assert.Contains(t, typeArray, "string")
344 assert.Contains(t, typeArray, "null")
345
346 _, hasNullable := resultMap["nullable"]
347 assert.False(t, hasNullable)
348 }
349
350 func TestTransformNullableInSchema_MapWithNullableFalse(t *testing.T) {
351 schema := map[string]interface{}{
352 "type": "string",
353 "nullable": false,
354 }
355
356 result := transformOAS30Keywords(schema)
357
358 resultMap, ok := result.(map[string]interface{})
359 require.True(t, ok)
360
361 // nullable: false should just remove nullable, keep type as is
362 schemaType, ok := resultMap["type"]
363 require.True(t, ok)
364 assert.Equal(t, "string", schemaType)
365
366 _, hasNullable := resultMap["nullable"]
367 assert.False(t, hasNullable)
368 }
369
370 func TestTransformNullableInSchema_Array(t *testing.T) {
371 schema := []interface{}{
372 map[string]interface{}{
373 "type": "string",
374 "nullable": true,
375 },
376 "other-item",
377 }
378
379 result := transformOAS30Keywords(schema)
380
381 resultArray, ok := result.([]interface{})
382 require.True(t, ok)
383 assert.Len(t, resultArray, 2)
384
385 firstItem, ok := resultArray[0].(map[string]interface{})
386 require.True(t, ok)
387
388 schemaType := firstItem["type"].([]interface{})
389 assert.Contains(t, schemaType, "string")
390 assert.Contains(t, schemaType, "null")
391
392 _, hasNullable := firstItem["nullable"]
393 assert.False(t, hasNullable)
394 }
395
396 func TestTransformNullableInSchema_OtherTypes(t *testing.T) {
397 stringSchema := "string-value"
398 result := transformOAS30Keywords(stringSchema)
399 assert.Equal(t, stringSchema, result)
400
401 numberSchema := 123
402 result = transformOAS30Keywords(numberSchema)
403 assert.Equal(t, numberSchema, result)
404
405 var nilSchema interface{} = nil
406 result = transformOAS30Keywords(nilSchema)
407 assert.Equal(t, nilSchema, result)
408 }
409
410 func TestTransformExclusiveBound_TrueWithBound(t *testing.T) {
411 schema := map[string]interface{}{
412 "type": "number",
413 "minimum": float64(10),
414 "exclusiveMinimum": true,
415 }
416 transformExclusiveBound(schema, "exclusiveMinimum", "minimum")
417
418 assert.Equal(t, float64(10), schema["exclusiveMinimum"])
419 _, hasMin := schema["minimum"]
420 assert.False(t, hasMin)
421 }
422
423 func TestTransformExclusiveBound_TrueWithoutBound(t *testing.T) {
424 schema := map[string]interface{}{
425 "type": "number",
426 "exclusiveMinimum": true,
427 }
428 transformExclusiveBound(schema, "exclusiveMinimum", "minimum")
429
430 _, hasExMin := schema["exclusiveMinimum"]
431 assert.False(t, hasExMin)
432 }
433
434 func TestTransformExclusiveBound_False(t *testing.T) {
435 schema := map[string]interface{}{
436 "type": "number",
437 "minimum": float64(10),
438 "exclusiveMinimum": false,
439 }
440 transformExclusiveBound(schema, "exclusiveMinimum", "minimum")
441
442 _, hasExMin := schema["exclusiveMinimum"]
443 assert.False(t, hasExMin)
444 assert.Equal(t, float64(10), schema["minimum"])
445 }
446
447 func TestTransformExclusiveBound_NotPresent(t *testing.T) {
448 schema := map[string]interface{}{
449 "type": "number",
450 "minimum": float64(10),
451 }
452 transformExclusiveBound(schema, "exclusiveMinimum", "minimum")
453
454 assert.Equal(t, float64(10), schema["minimum"])
455 }
456
457 func TestTransformExclusiveBound_AlreadyNumeric(t *testing.T) {
458 schema := map[string]interface{}{
459 "type": "number",
460 "exclusiveMinimum": float64(10),
461 }
462 transformExclusiveBound(schema, "exclusiveMinimum", "minimum")
463
464 assert.Equal(t, float64(10), schema["exclusiveMinimum"])
465 }
466
467 func TestTransformExclusiveBound_Maximum(t *testing.T) {
468 schema := map[string]interface{}{
469 "type": "number",
470 "maximum": float64(100),
471 "exclusiveMaximum": true,
472 }
473 transformExclusiveBound(schema, "exclusiveMaximum", "maximum")
474
475 assert.Equal(t, float64(100), schema["exclusiveMaximum"])
476 _, hasMax := schema["maximum"]
477 assert.False(t, hasMax)
478 }
479
480 func TestTransformOAS30Keywords_ExclusiveMinMaxRecursive(t *testing.T) {
481 schema := map[string]interface{}{
482 "type": "object",
483 "properties": map[string]interface{}{
484 "price": map[string]interface{}{
485 "type": "number",
486 "minimum": float64(0),
487 "exclusiveMinimum": true,
488 "maximum": float64(1000),
489 "exclusiveMaximum": true,
490 },
491 },
492 }
493
494 result := transformOAS30Keywords(schema)
495 resultMap := result.(map[string]interface{})
496 props := resultMap["properties"].(map[string]interface{})
497 price := props["price"].(map[string]interface{})
498
499 assert.Equal(t, float64(0), price["exclusiveMinimum"])
500 assert.Equal(t, float64(1000), price["exclusiveMaximum"])
501 _, hasMin := price["minimum"]
502 assert.False(t, hasMin)
503 _, hasMax := price["maximum"]
504 assert.False(t, hasMax)
505 }
506
507 func TestTransformNullableSchema_ArrayType(t *testing.T) {
508 schema := map[string]interface{}{
509 "type": []interface{}{"string", "number"},
510 "nullable": true,
511 }
512
513 result := transformNullableSchema(schema)
514
515 schemaType, ok := result["type"]
516 require.True(t, ok)
517
518 typeArray, ok := schemaType.([]interface{})
519 require.True(t, ok)
520 assert.Contains(t, typeArray, "string")
521 assert.Contains(t, typeArray, "number")
522 assert.Contains(t, typeArray, "null")
523
524 _, hasNullable := result["nullable"]
525 assert.False(t, hasNullable)
526 }
527
528 func TestTransformNullableSchema_ArrayTypeWithNull(t *testing.T) {
529 schema := map[string]interface{}{
530 "type": []interface{}{"string", "null"},
531 "nullable": true,
532 }
533
534 result := transformNullableSchema(schema)
535
536 schemaType, ok := result["type"]
537 require.True(t, ok)
538
539 typeArray, ok := schemaType.([]interface{})
540 require.True(t, ok)
541 assert.Contains(t, typeArray, "string")
542 assert.Contains(t, typeArray, "null")
543 // Should not have duplicate "null"
544 nullCount := 0
545 for _, item := range typeArray {
546 if item == "null" {
547 nullCount++
548 }
549 }
550 assert.Equal(t, 1, nullCount)
551
552 _, hasNullable := result["nullable"]
553 assert.False(t, hasNullable)
554 }
555
556 func TestTransformNullableSchema_NullableAllOf(t *testing.T) {
557 schema := map[string]interface{}{
558 "type": []interface{}{"object"},
559 "allOf": []interface{}{
560 map[string]interface{}{
561 "type": "object",
562 "properties": map[string]interface{}{
563 "id": map[string]interface{}{
564 "type": "string",
565 },
566 },
567 },
568 },
569 "nullable": true,
570 }
571
572 result := transformNullableSchema(schema)
573
574 schemaType, ok := result["type"]
575 require.True(t, ok)
576
577 typeArray, ok := schemaType.([]interface{})
578 require.True(t, ok)
579 assert.Contains(t, typeArray, "object")
580 assert.Contains(t, typeArray, "null")
581
582 oneOf, ok := result["oneOf"]
583 require.True(t, ok)
584
585 oneOfSlice, ok := oneOf.([]interface{})
586 require.True(t, ok)
587
588 assert.Len(t, oneOfSlice, 2)
589 assert.Contains(t, oneOfSlice, map[string]interface{}{
590 "allOf": []interface{}{
591 map[string]interface{}{
592 "type": "object",
593 "properties": map[string]interface{}{
594 "id": map[string]interface{}{
595 "type": "string",
596 },
597 },
598 },
599 },
600 })
601 assert.Contains(t, oneOfSlice, map[string]interface{}{
602 "type": "null",
603 })
604
605 _, hasNullable := result["nullable"]
606 assert.False(t, hasNullable)
607 }
608
609 func TestTransformNullableSchema_NullableAllOfWithExistingOneOf(t *testing.T) {
610 schema := map[string]interface{}{
611 "type": []interface{}{"object"},
612 "allOf": []interface{}{
613 map[string]interface{}{
614 "type": "object",
615 "properties": map[string]interface{}{
616 "id": map[string]interface{}{
617 "type": "string",
618 },
619 },
620 },
621 },
622 "oneOf": []interface{}{
623 map[string]interface{}{
624 "type": "object",
625 "properties": map[string]interface{}{
626 "id": map[string]interface{}{
627 "type": "string",
628 "const": []any{"val"},
629 },
630 },
631 },
632 },
633 "nullable": true,
634 }
635
636 result := transformNullableSchema(schema)
637
638 schemaType, ok := result["type"]
639 require.True(t, ok)
640
641 typeArray, ok := schemaType.([]interface{})
642 require.True(t, ok)
643 assert.Contains(t, typeArray, "object")
644 assert.Contains(t, typeArray, "null")
645
646 oneOf, ok := result["oneOf"]
647 require.True(t, ok)
648
649 oneOfSlice, ok := oneOf.([]interface{})
650 require.True(t, ok)
651
652 assert.Len(t, oneOfSlice, 3)
653 assert.Contains(t, oneOfSlice, map[string]interface{}{
654 "allOf": []interface{}{
655 map[string]interface{}{
656 "type": "object",
657 "properties": map[string]interface{}{
658 "id": map[string]interface{}{
659 "type": "string",
660 },
661 },
662 },
663 },
664 })
665 assert.Contains(t, oneOfSlice, map[string]interface{}{
666 "type": "null",
667 })
668 assert.Contains(t, oneOfSlice, map[string]interface{}{
669 "type": "object",
670 "properties": map[string]interface{}{
671 "id": map[string]interface{}{
672 "type": "string",
673 "const": []any{"val"},
674 },
675 },
676 })
677
678 _, hasNullable := result["nullable"]
679 assert.False(t, hasNullable)
680 }
681
682 func TestTransformSchemaForCoercion_ValidJSON(t *testing.T) {
683 input := []byte(`{
684 "type": "boolean"
685 }`)
686
687 result := transformSchemaForCoercion(input)
688
689 var schema map[string]interface{}
690 err := json.Unmarshal(result, &schema)
691 require.NoError(t, err, "Result should be valid JSON")
692
693 // Check that type was transformed to include string
694 schemaType, ok := schema["type"]
695 assert.True(t, ok, "Should have type field")
696
697 typeArray, ok := schemaType.([]interface{})
698 assert.True(t, ok, "Type should be an array")
699 assert.Contains(t, typeArray, "boolean")
700 assert.Contains(t, typeArray, "string")
701 }
702
703 func TestTransformSchemaForCoercion_InvalidJSON(t *testing.T) {
704 input := []byte(`{invalid json}`)
705
706 result := transformSchemaForCoercion(input)
707
708 // Should return original when invalid
709 assert.Equal(t, input, result)
710 }
711
712 func TestTransformOpenAPI30Schema_MarshalError(t *testing.T) {
713 // Create a transformation that could potentially cause marshal issues
714 // This is hard to test because Go's json.Marshal rarely fails
715 // The error path exists for defensive programming
716 input := []byte(`{
717 "type": "string",
718 "nullable": true
719 }`)
720
721 result := transformOpenAPI30Schema(input)
722
723 // Should return valid transformed JSON even if marshal could theoretically fail
724 var schema map[string]interface{}
725 err := json.Unmarshal(result, &schema)
726 assert.NoError(t, err)
727 }
728
729 func TestTransformSchemaForCoercion_MarshalError(t *testing.T) {
730 // Create a transformation that could potentially cause marshal issues
731 // This is hard to test because Go's json.Marshal rarely fails
732 // The error path exists for defensive programming
733 input := []byte(`{
734 "type": "boolean"
735 }`)
736
737 result := transformSchemaForCoercion(input)
738
739 // Should return valid transformed JSON even if marshal could theoretically fail
740 var schema map[string]interface{}
741 err := json.Unmarshal(result, &schema)
742 assert.NoError(t, err)
743 }
744
745 func TestTransformCoercionInSchema_Array(t *testing.T) {
746 schema := []interface{}{
747 map[string]interface{}{
748 "type": "number",
749 },
750 "other-item",
751 }
752
753 result := transformCoercionInSchema(schema)
754
755 resultArray, ok := result.([]interface{})
756 require.True(t, ok)
757 assert.Len(t, resultArray, 2)
758
759 firstItem, ok := resultArray[0].(map[string]interface{})
760 require.True(t, ok)
761
762 schemaType := firstItem["type"].([]interface{})
763 assert.Contains(t, schemaType, "number")
764 assert.Contains(t, schemaType, "string")
765 }
766
767 func TestTransformCoercionInSchema_OtherTypes(t *testing.T) {
768 stringSchema := "string-value"
769 result := transformCoercionInSchema(stringSchema)
770 assert.Equal(t, stringSchema, result)
771 }
772
773 func TestTransformTypeForCoercion_ArrayWithNonStringItems(t *testing.T) {
774 input := []interface{}{"boolean", 123, "null"}
775
776 result := transformTypeForCoercion(input)
777
778 typeArray, ok := result.([]interface{})
779 require.True(t, ok)
780 assert.Contains(t, typeArray, "boolean")
781 assert.Contains(t, typeArray, 123)
782 assert.Contains(t, typeArray, "null")
783 assert.Contains(t, typeArray, "string")
784 }
785
786 func TestTransformTypeForCoercion_OtherTypes(t *testing.T) {
787 result := transformTypeForCoercion(123)
788 assert.Equal(t, 123, result)
789
790 result = transformTypeForCoercion(nil)
791 assert.Equal(t, nil, result)
792
793 result = transformTypeForCoercion(map[string]interface{}{})
794 assert.Equal(t, map[string]interface{}{}, result)
795 }
796
797 func TestTransformTypeForCoercion_EdgeCases(t *testing.T) {
798 result := transformTypeForCoercion("fudge")
799 assert.Equal(t, "fudge", result)
800
801 result = transformTypeForCoercion([]interface{}{"string"})
802 assert.Equal(t, []interface{}{"string"}, result)
803 }
804
805 func TestTransformNullableSchema_EnumWithoutNull(t *testing.T) {
806 // Test case: nullable: true with enum that doesn't contain null
807 // Expected: null should be automatically added to the enum
808 schema := map[string]interface{}{
809 "type": "string",
810 "enum": []interface{}{
811 "active",
812 "inactive",
813 "pending",
814 "archived",
815 },
816 "nullable": true,
817 }
818
819 result := transformNullableSchema(schema)
820
821 // nullable keyword should be removed
822 _, hasNullable := result["nullable"]
823 assert.False(t, hasNullable)
824
825 // type should be converted to array including null
826 schemaType, ok := result["type"]
827 require.True(t, ok)
828
829 typeArray, ok := schemaType.([]interface{})
830 require.True(t, ok)
831 assert.Contains(t, typeArray, "string")
832 assert.Contains(t, typeArray, "null")
833
834 // enum should contain null
835 enum, ok := result["enum"]
836 require.True(t, ok)
837
838 enumSlice, ok := enum.([]interface{})
839 require.True(t, ok)
840 assert.Len(t, enumSlice, 5) // original 4 values + null
841 assert.Contains(t, enumSlice, "active")
842 assert.Contains(t, enumSlice, "inactive")
843 assert.Contains(t, enumSlice, "pending")
844 assert.Contains(t, enumSlice, "archived")
845 assert.Contains(t, enumSlice, nil)
846 }
847
848 func TestTransformNullableSchema_EnumWithNull(t *testing.T) {
849 // Test case: nullable: true with enum that already contains null
850 // Expected: null should NOT be added twice
851 schema := map[string]interface{}{
852 "type": "string",
853 "enum": []interface{}{
854 "active",
855 "inactive",
856 "pending",
857 "archived",
858 nil,
859 },
860 "nullable": true,
861 }
862
863 result := transformNullableSchema(schema)
864
865 // nullable keyword should be removed
866 _, hasNullable := result["nullable"]
867 assert.False(t, hasNullable)
868
869 // type should be converted to array including null
870 schemaType, ok := result["type"]
871 require.True(t, ok)
872
873 typeArray, ok := schemaType.([]interface{})
874 require.True(t, ok)
875 assert.Contains(t, typeArray, "string")
876 assert.Contains(t, typeArray, "null")
877
878 // enum should still contain only one null (not duplicated)
879 enum, ok := result["enum"]
880 require.True(t, ok)
881
882 enumSlice, ok := enum.([]interface{})
883 require.True(t, ok)
884 assert.Len(t, enumSlice, 5) // original 5 values (no duplication)
885 assert.Contains(t, enumSlice, "active")
886 assert.Contains(t, enumSlice, "inactive")
887 assert.Contains(t, enumSlice, "pending")
888 assert.Contains(t, enumSlice, "archived")
889
890 // Count how many nulls are in the enum
891 nullCount := 0
892 for _, v := range enumSlice {
893 if v == nil {
894 nullCount++
895 }
896 }
897 assert.Equal(t, 1, nullCount, "enum should contain exactly one null value")
898 }