Debian Codegraph @

tests/schema_registry/_sync/test_json.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2023 Confluent Inc.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18
19 import json
20 from unittest.mock import Mock
21
22 import orjson
23 import pytest
24
25 from confluent_kafka.schema_registry import (
26 Schema,
27 SchemaReference,
28 SchemaRegistryClient, RegisteredSchema,
29 )
30 from confluent_kafka.schema_registry.json_schema import JSONDeserializer, JSONSerializer
31 from confluent_kafka.schema_registry.rule_registry import RuleRegistry
32 from confluent_kafka.serialization import SerializationContext
33
34
35 def test_json_deserializer_referenced_schema_no_schema_registry_client(load_avsc):
36 """
37 Ensures that the deserializer raises a ValueError if a referenced schema is provided but no schema registry
38 client is provided.
39 """
40 schema = Schema(load_avsc("order_details.json"), 'JSON',
41 [SchemaReference("http://example.com/customer.schema.json", "customer", 1)])
42 with pytest.raises(
43 ValueError,
44 match="""schema_registry_client must be provided if "schema_str" is a Schema instance with references"""):
45 JSONDeserializer(schema, schema_registry_client=None)
46
47
48 def test_json_deserializer_invalid_schema_type():
49 """
50 Ensures that the deserializer raises a ValueError if an invalid schema type is provided.
51 """
52 with pytest.raises(TypeError, match="You must pass either str or Schema"):
53 JSONDeserializer(1)
54
55
56 def test_custom_json_encoder():
57 """Test custom JSON encoder using orjson for better performance"""
58 schema_str = """
59 {
60 "type": "object",
61 "properties": {
62 "name": {"type": "string"},
63 "age": {"type": "integer"}
64 }
65 }"""
66
67 test_data = {"name": "John", "age": 30}
68 ctx = SerializationContext("topic-name", "value")
69
70 # Create mock SchemaRegistryClient
71 mock_schema_registry_client = Mock(spec=SchemaRegistryClient)
72 mock_schema_registry_client.register_schema_full_response.return_value = RegisteredSchema(
73 schema_id=1,
74 guid=None,
75 schema=Schema(schema_str),
76 subject="topic-name-value",
77 version=1)
78
79 # Use orjson.dumps as the custom encoder
80 serializer = JSONSerializer(
81 schema_str, mock_schema_registry_client, json_encode=orjson.dumps,
82 rule_registry=RuleRegistry()
83 )
84
85 result = serializer(test_data, ctx)
86
87 # Since result includes schema registry framing (5 bytes prefix),
88 # we need to decode from bytes starting after the prefix
89 decoded = orjson.loads(result[5:])
90 assert decoded["name"] == "John"
91 assert decoded["age"] == 30
92
93
94 def test_custom_json_decoder():
95 """Test custom JSON decoder using orjson for better performance"""
96 schema_str = """
97 {
98 "type": "object",
99 "properties": {
100 "name": {"type": "string"},
101 "age": {"type": "integer"}
102 }
103 }"""
104
105 test_data = b'\x00\x00\x00\x00\x01{"name": "John", "age": 30}'
106
107 # Use orjson for decoding with custom transformation
108 def custom_decoder(data):
109 decoded = orjson.loads(data)
110 return {k.upper(): v for k, v in decoded.items()}
111
112 deserializer = JSONDeserializer(
113 schema_str, json_decode=custom_decoder,
114 rule_registry=RuleRegistry())
115 ctx = SerializationContext("topic-name", "value")
116 result = deserializer(test_data, ctx)
117
118 # Verify custom decoder transformed keys to uppercase
119 assert result["NAME"] == "John"
120 assert result["AGE"] == 30
121
122
123 def test_custom_encoder_decoder_chain():
124 """Test serialization/deserialization chain with custom encoding"""
125 schema_str = """
126 {
127 "type": "object",
128 "properties": {
129 "data": {"type": "string"}
130 }
131 }"""
132
133 test_data = {"data": "test value"}
134 ctx = SerializationContext("topic-name", "value")
135
136 mock_schema_registry_client = Mock(spec=SchemaRegistryClient)
137 mock_schema_registry_client.register_schema_full_response.return_value = RegisteredSchema(
138 schema_id=1,
139 guid=None,
140 schema=Schema(schema_str),
141 subject="topic-name-value",
142 version=1)
143
144 def custom_encoder(obj):
145 return orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)
146
147 def custom_decoder(data):
148 return orjson.loads(data)
149
150 serializer = JSONSerializer(
151 schema_str,
152 mock_schema_registry_client,
153 json_encode=custom_encoder,
154 rule_registry=RuleRegistry()
155 )
156 deserializer = JSONDeserializer(
157 schema_str, json_decode=custom_decoder,
158 rule_registry=RuleRegistry())
159
160 # Serialize then deserialize
161 encoded = serializer(test_data, ctx)
162 decoded = deserializer(encoded, ctx)
163
164 assert decoded == test_data
165
166
167 def test_custom_encoding_with_complex_data():
168 """Test custom encoding with nested structures"""
169 schema_str = """
170 {
171 "type": "object",
172 "properties": {
173 "nested": {
174 "type": "object",
175 "properties": {
176 "array": {"type": "array", "items": {"type": "integer"}},
177 "string": {"type": "string"}
178 }
179 }
180 }
181 }"""
182
183 test_data = {"nested": {"array": [1, 2, 3], "string": "test"}}
184 mock_schema_registry_client = Mock(spec=SchemaRegistryClient)
185 mock_schema_registry_client.register_schema_full_response.return_value = RegisteredSchema(
186 schema_id=1,
187 guid=None,
188 schema=Schema(schema_str),
189 subject="topic-name-value",
190 version=1)
191
192 def custom_encoder(obj):
193 return json.dumps(obj, indent=2)
194
195 def custom_decoder(data):
196 return json.loads(data)
197
198 serializer = JSONSerializer(
199 schema_str,
200 mock_schema_registry_client,
201 json_encode=custom_encoder,
202 rule_registry=RuleRegistry()
203 )
204 deserializer = JSONDeserializer(
205 schema_str, json_decode=custom_decoder,
206 rule_registry=RuleRegistry())
207 ctx = SerializationContext("topic-name", "value")
208 encoded = serializer(test_data, ctx)
209 decoded = deserializer(encoded, ctx)
210
211 assert decoded == test_data