|
17 | 17 | package jsonschema
|
18 | 18 |
|
19 | 19 | import (
|
| 20 | + "encoding/json" |
| 21 | + "github.com/invopop/jsonschema" |
| 22 | + "strings" |
20 | 23 | "testing"
|
21 | 24 |
|
22 | 25 | "github.com/confluentinc/confluent-kafka-go/v2/schemaregistry"
|
@@ -85,6 +88,63 @@ func TestJSONSchemaSerdeWithNested(t *testing.T) {
|
85 | 88 | serde.MaybeFail("deserialization", err, serde.Expect(newobj, obj))
|
86 | 89 | }
|
87 | 90 |
|
| 91 | +func TestFailingJSONSchemaValidationWithSimple(t *testing.T) { |
| 92 | + serde.MaybeFail = serde.InitFailFunc(t) |
| 93 | + var err error |
| 94 | + conf := schemaregistry.NewConfig("mock://") |
| 95 | + |
| 96 | + client, err := schemaregistry.NewClient(conf) |
| 97 | + serde.MaybeFail("Schema Registry configuration", err) |
| 98 | + |
| 99 | + serConfig := NewSerializerConfig() |
| 100 | + serConfig.EnableValidation = true |
| 101 | + // We don't want to risk registering one instead of using the already registered one |
| 102 | + serConfig.AutoRegisterSchemas = false |
| 103 | + serConfig.UseLatestVersion = true |
| 104 | + ser, err := NewSerializer(client, serde.ValueSerde, serConfig) |
| 105 | + serde.MaybeFail("Serializer configuration", err) |
| 106 | + |
| 107 | + obj := JSONDemoSchema{} |
| 108 | + jschema := jsonschema.Reflect(obj) |
| 109 | + raw, err := json.Marshal(jschema) |
| 110 | + serde.MaybeFail("Schema marshalling", err) |
| 111 | + info := schemaregistry.SchemaInfo{ |
| 112 | + Schema: string(raw), |
| 113 | + SchemaType: "JSON", |
| 114 | + } |
| 115 | + |
| 116 | + id, err := client.Register("topic1-value", info, false) |
| 117 | + serde.MaybeFail("Schema registration", err) |
| 118 | + if id <= 0 { |
| 119 | + t.Errorf("Expected valid schema id, found %d", id) |
| 120 | + } |
| 121 | + |
| 122 | + _, err = ser.Serialize("topic1", &obj) |
| 123 | + if err != nil { |
| 124 | + t.Errorf("Expected no validation error, found %s", err) |
| 125 | + } |
| 126 | + |
| 127 | + diffObj := DifferentJSONDemoSchema{} |
| 128 | + _, err = ser.Serialize("topic1", &diffObj) |
| 129 | + if err == nil || !strings.Contains(err.Error(), "jsonschema") { |
| 130 | + t.Errorf("Expected validation error, found %s", err) |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +type DifferentJSONDemoSchema struct { |
| 135 | + IntField int32 `json:"IntField"` |
| 136 | + |
| 137 | + ExtraStringField string `json:"ExtraStringField"` |
| 138 | + |
| 139 | + DoubleField float64 `json:"DoubleField"` |
| 140 | + |
| 141 | + StringField string `json:"StringField"` |
| 142 | + |
| 143 | + BoolFieldThatsActuallyString string `json:"BoolField"` |
| 144 | + |
| 145 | + BytesField test.Bytes `json:"BytesField"` |
| 146 | +} |
| 147 | + |
88 | 148 | type JSONDemoSchema struct {
|
89 | 149 | IntField int32 `json:"IntField"`
|
90 | 150 |
|
|
0 commit comments