Debian Codegraph @

tests/schema_registry/_async/test_avro.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2020 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 import pytest
19
20 from confluent_kafka.schema_registry import (record_subject_name_strategy,
21 AsyncSchemaRegistryClient,
22 topic_record_subject_name_strategy)
23 from confluent_kafka.schema_registry.avro import AsyncAvroSerializer, AsyncAvroDeserializer
24 from confluent_kafka.serialization import (MessageField,
25 SerializationContext)
26 from tests.schema_registry.conftest import COUNTER
27
28 # Mock AsyncSchemaRegistryClient, see ./conftest.py for additional details.
29 TEST_URL = 'http://SchemaRegistry:65534'
30
31
32 @pytest.fixture(autouse=True)
33 def reset_global_rule_registry(request):
34 import confluent_kafka.schema_registry.rule_registry as rule_registry
35
36 rule_registry._global_instance.clear()
37
38
39 async def test_avro_serializer_config_auto_register_schemas():
40 """
41 Ensures auto.register.schemas is applied
42 """
43 conf = {'url': TEST_URL}
44 test_client = AsyncSchemaRegistryClient(conf)
45 test_serializer = await AsyncAvroSerializer(
46 test_client, '"string"',
47 conf={'auto.register.schemas': False}
48 )
49 assert not test_serializer._auto_register
50
51
52 async def test_avro_serializer_config_auto_register_schemas_invalid():
53 """
54 Ensures auto.register.schemas is applied
55 """
56 conf = {'url': TEST_URL}
57 test_client = AsyncSchemaRegistryClient(conf)
58
59 with pytest.raises(ValueError, match="must be a boolean"):
60 await AsyncAvroSerializer(
61 test_client, 'string',
62 conf={'auto.register.schemas': dict()})
63
64
65 async def test_avro_serializer_config_auto_register_schemas_false(mock_schema_registry):
66 """
67 Ensures auto.register.schemas=False does not register schema
68 """
69 conf = {'url': TEST_URL}
70 test_client = AsyncSchemaRegistryClient(conf)
71 topic = "test-auto-register"
72 subject = topic + '-key'
73 before = COUNTER['POST'].get('/subjects/{}'.format(subject), 0)
74 test_serializer = await AsyncAvroSerializer(
75 test_client, '"string"',
76 conf={'auto.register.schemas': False})
77
78 await test_serializer(
79 "test",
80 SerializationContext("test-auto-register", MessageField.KEY)
81 )
82
83 register_count = COUNTER['POST'].get('/subjects/{}/versions'.format(subject), 0)
84 assert register_count == 0
85 # Ensure lookup_schema was invoked instead
86 assert COUNTER['POST'].get('/subjects/{}'.format(subject)) - before == 1
87
88
89 async def test_avro_serializer_config_use_latest_version(mock_schema_registry):
90 """
91 Ensures auto.register.schemas=False does not register schema
92 """
93 conf = {'url': TEST_URL}
94 test_client = AsyncSchemaRegistryClient(conf)
95 topic = "test-use-latest-version"
96 subject = topic + '-key'
97 before_versions = COUNTER['POST'].get('/subjects/{}/versions'.format(subject), 0)
98 before_latest = COUNTER['GET'].get('/subjects/{}/versions/latest'.format(subject), 0)
99 test_serializer = await AsyncAvroSerializer(
100 test_client, '"string"',
101 conf={'auto.register.schemas': False, 'use.latest.version': True})
102
103 await test_serializer(
104 {'name': 'Bob', 'age': 30},
105 SerializationContext("test-use-latest-version", MessageField.KEY)
106 )
107
108 register_count = COUNTER['POST'].get('/subjects/{}/versions'.format(subject), 0)
109 assert register_count - before_versions == 0
110 # Ensure latest was requested
111 assert COUNTER['GET'].get('/subjects/{}/versions/latest'.format(subject)) - before_latest == 1
112
113
114 async def test_avro_serializer_config_subject_name_strategy():
115 """
116 Ensures subject.name.strategy is applied
117 """
118
119 conf = {'url': TEST_URL}
120 test_client = AsyncSchemaRegistryClient(conf)
121 test_serializer = await AsyncAvroSerializer(
122 test_client, '"int"',
123 conf={'subject.name.strategy': record_subject_name_strategy})
124
125 assert test_serializer._subject_name_func is record_subject_name_strategy
126
127
128 async def test_avro_serializer_config_subject_name_strategy_invalid():
129 """
130 Ensures subject.name.strategy is applied
131 """
132
133 conf = {'url': TEST_URL}
134 test_client = AsyncSchemaRegistryClient(conf)
135 with pytest.raises(ValueError, match="must be callable"):
136 await AsyncAvroSerializer(
137 test_client, '"int"',
138 conf={'subject.name.strategy': dict()})
139
140
141 async def test_avro_serializer_record_subject_name_strategy(load_avsc):
142 """
143 Ensures record_subject_name_strategy returns the correct record name
144 """
145 conf = {'url': TEST_URL}
146 test_client = AsyncSchemaRegistryClient(conf)
147 test_serializer = await AsyncAvroSerializer(
148 test_client,
149 load_avsc('basic_schema.avsc'),
150 conf={'subject.name.strategy': record_subject_name_strategy})
151
152 ctx = SerializationContext('test_subj', MessageField.VALUE, [])
153 assert test_serializer._subject_name_func(ctx,
154 test_serializer._schema_name) == 'python.test.basic'
155 assert ctx is not None
156 assert not ctx.headers
157
158
159 async def test_avro_serializer_record_subject_name_strategy_primitive(load_avsc):
160 """
161 Ensures record_subject_name_strategy returns the correct record name.
162 Also verifies transformation from Avro canonical form.
163 """
164 conf = {'url': TEST_URL}
165 test_client = AsyncSchemaRegistryClient(conf)
166 test_serializer = await AsyncAvroSerializer(
167 test_client, '"int"',
168 conf={'subject.name.strategy': record_subject_name_strategy})
169
170 ctx = SerializationContext('test_subj', MessageField.VALUE, [('header1', 'header value 1'), ])
171 assert test_serializer._subject_name_func(ctx,
172 test_serializer._schema_name) == 'int'
173 assert ('header1', 'header value 1') in ctx.headers
174
175
176 async def test_avro_serializer_topic_record_subject_name_strategy(load_avsc):
177 """
178 Ensures record_subject_name_strategy returns the correct record name
179 """
180 conf = {'url': TEST_URL}
181 test_client = AsyncSchemaRegistryClient(conf)
182 test_serializer = await AsyncAvroSerializer(
183 test_client,
184 load_avsc('basic_schema.avsc'),
185 conf={'subject.name.strategy': topic_record_subject_name_strategy})
186
187 ctx = SerializationContext('test_subj', MessageField.VALUE)
188 assert test_serializer._subject_name_func(
189 ctx, test_serializer._schema_name) == 'test_subj-python.test.basic'
190
191
192 async def test_avro_serializer_topic_record_subject_name_strategy_primitive(load_avsc):
193 """
194 Ensures record_subject_name_strategy returns the correct record name.
195 Also verifies transformation from Avro canonical form.
196 """
197 conf = {'url': TEST_URL}
198 test_client = AsyncSchemaRegistryClient(conf)
199 test_serializer = await AsyncAvroSerializer(
200 test_client, '"int"',
201 conf={'subject.name.strategy': topic_record_subject_name_strategy})
202
203 ctx = SerializationContext('test_subj', MessageField.VALUE)
204 assert test_serializer._subject_name_func(
205 ctx, test_serializer._schema_name) == 'test_subj-int'
206 assert ctx is not None
207 assert ctx.headers is None
208
209
210 async def test_avro_serializer_subject_name_strategy_default(load_avsc):
211 """
212 Ensures record_subject_name_strategy returns the correct record name
213 """
214 conf = {'url': TEST_URL}
215 test_client = AsyncSchemaRegistryClient(conf)
216 test_serializer = await AsyncAvroSerializer(
217 test_client, load_avsc('basic_schema.avsc'))
218
219 ctx = SerializationContext('test_subj', MessageField.VALUE)
220 assert test_serializer._subject_name_func(
221 ctx, test_serializer._schema_name) == 'test_subj-value'
222
223
224 async def test_avro_serializer_schema_loads_union(load_avsc):
225 """
226 Ensures union types are correctly parsed
227 """
228 conf = {'url': TEST_URL}
229 test_client = AsyncSchemaRegistryClient(conf)
230 test_serializer = await AsyncAvroSerializer(
231 test_client,
232 load_avsc('union_schema.avsc'))
233
234 assert test_serializer._schema_name is None
235
236 schema = test_serializer._parsed_schema
237 assert isinstance(schema, list)
238 assert schema[0]["name"] == "RecordOne"
239 assert schema[1]["name"] == "RecordTwo"
240
241
242 async def test_avro_deserializer_invalid_schema_type():
243 """
244 Ensures invalid schema types are rejected
245 """
246 conf = {'url': TEST_URL}
247 test_client = AsyncSchemaRegistryClient(conf)
248 with pytest.raises(TypeError, match="You must pass either schema string or schema object"):
249 await AsyncAvroDeserializer(test_client, 1)