File: test_avro.py

package info (click to toggle)
python-confluent-kafka 2.11.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,660 kB
  • sloc: python: 30,428; ansic: 9,487; sh: 1,477; makefile: 192
file content (249 lines) | stat: -rw-r--r-- 8,837 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pytest

from confluent_kafka.schema_registry import (record_subject_name_strategy,
                                             SchemaRegistryClient,
                                             topic_record_subject_name_strategy)
from confluent_kafka.schema_registry.avro import AvroSerializer, AvroDeserializer
from confluent_kafka.serialization import (MessageField,
                                           SerializationContext)
from tests.schema_registry.conftest import COUNTER

# Mock SchemaRegistryClient, see ./conftest.py for additional details.
TEST_URL = 'http://SchemaRegistry:65534'


@pytest.fixture(autouse=True)
def reset_global_rule_registry(request):
    import confluent_kafka.schema_registry.rule_registry as rule_registry

    rule_registry._global_instance.clear()


def test_avro_serializer_config_auto_register_schemas():
    """
    Ensures auto.register.schemas is applied
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client, '"string"',
        conf={'auto.register.schemas': False}
    )
    assert not test_serializer._auto_register


def test_avro_serializer_config_auto_register_schemas_invalid():
    """
    Ensures auto.register.schemas is applied
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)

    with pytest.raises(ValueError, match="must be a boolean"):
        AvroSerializer(
            test_client, 'string',
            conf={'auto.register.schemas': dict()})


def test_avro_serializer_config_auto_register_schemas_false(mock_schema_registry):
    """
    Ensures auto.register.schemas=False does not register schema
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    topic = "test-auto-register"
    subject = topic + '-key'
    before = COUNTER['POST'].get('/subjects/{}'.format(subject), 0)
    test_serializer = AvroSerializer(
        test_client, '"string"',
        conf={'auto.register.schemas': False})

    test_serializer(
        "test",
        SerializationContext("test-auto-register", MessageField.KEY)
    )

    register_count = COUNTER['POST'].get('/subjects/{}/versions'.format(subject), 0)
    assert register_count == 0
    # Ensure lookup_schema was invoked instead
    assert COUNTER['POST'].get('/subjects/{}'.format(subject)) - before == 1


def test_avro_serializer_config_use_latest_version(mock_schema_registry):
    """
    Ensures auto.register.schemas=False does not register schema
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    topic = "test-use-latest-version"
    subject = topic + '-key'
    before_versions = COUNTER['POST'].get('/subjects/{}/versions'.format(subject), 0)
    before_latest = COUNTER['GET'].get('/subjects/{}/versions/latest'.format(subject), 0)
    test_serializer = AvroSerializer(
        test_client, '"string"',
        conf={'auto.register.schemas': False, 'use.latest.version': True})

    test_serializer(
        {'name': 'Bob', 'age': 30},
        SerializationContext("test-use-latest-version", MessageField.KEY)
    )

    register_count = COUNTER['POST'].get('/subjects/{}/versions'.format(subject), 0)
    assert register_count - before_versions == 0
    # Ensure latest was requested
    assert COUNTER['GET'].get('/subjects/{}/versions/latest'.format(subject)) - before_latest == 1


def test_avro_serializer_config_subject_name_strategy():
    """
    Ensures subject.name.strategy is applied
    """

    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client, '"int"',
        conf={'subject.name.strategy': record_subject_name_strategy})

    assert test_serializer._subject_name_func is record_subject_name_strategy


def test_avro_serializer_config_subject_name_strategy_invalid():
    """
    Ensures subject.name.strategy is applied
    """

    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    with pytest.raises(ValueError, match="must be callable"):
        AvroSerializer(
            test_client, '"int"',
            conf={'subject.name.strategy': dict()})


def test_avro_serializer_record_subject_name_strategy(load_avsc):
    """
    Ensures record_subject_name_strategy returns the correct record name
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client,
        load_avsc('basic_schema.avsc'),
        conf={'subject.name.strategy': record_subject_name_strategy})

    ctx = SerializationContext('test_subj', MessageField.VALUE, [])
    assert test_serializer._subject_name_func(ctx,
                                              test_serializer._schema_name) == 'python.test.basic'
    assert ctx is not None
    assert not ctx.headers


def test_avro_serializer_record_subject_name_strategy_primitive(load_avsc):
    """
    Ensures record_subject_name_strategy returns the correct record name.
    Also verifies transformation from Avro canonical form.
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client, '"int"',
        conf={'subject.name.strategy': record_subject_name_strategy})

    ctx = SerializationContext('test_subj', MessageField.VALUE, [('header1', 'header value 1'), ])
    assert test_serializer._subject_name_func(ctx,
                                              test_serializer._schema_name) == 'int'
    assert ('header1', 'header value 1') in ctx.headers


def test_avro_serializer_topic_record_subject_name_strategy(load_avsc):
    """
    Ensures record_subject_name_strategy returns the correct record name
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client,
        load_avsc('basic_schema.avsc'),
        conf={'subject.name.strategy': topic_record_subject_name_strategy})

    ctx = SerializationContext('test_subj', MessageField.VALUE)
    assert test_serializer._subject_name_func(
        ctx, test_serializer._schema_name) == 'test_subj-python.test.basic'


def test_avro_serializer_topic_record_subject_name_strategy_primitive(load_avsc):
    """
    Ensures record_subject_name_strategy returns the correct record name.
    Also verifies transformation from Avro canonical form.
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client, '"int"',
        conf={'subject.name.strategy': topic_record_subject_name_strategy})

    ctx = SerializationContext('test_subj', MessageField.VALUE)
    assert test_serializer._subject_name_func(
        ctx, test_serializer._schema_name) == 'test_subj-int'
    assert ctx is not None
    assert ctx.headers is None


def test_avro_serializer_subject_name_strategy_default(load_avsc):
    """
    Ensures record_subject_name_strategy returns the correct record name
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client, load_avsc('basic_schema.avsc'))

    ctx = SerializationContext('test_subj', MessageField.VALUE)
    assert test_serializer._subject_name_func(
        ctx, test_serializer._schema_name) == 'test_subj-value'


def test_avro_serializer_schema_loads_union(load_avsc):
    """
    Ensures union types are correctly parsed
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    test_serializer = AvroSerializer(
        test_client,
        load_avsc('union_schema.avsc'))

    assert test_serializer._schema_name is None

    schema = test_serializer._parsed_schema
    assert isinstance(schema, list)
    assert schema[0]["name"] == "RecordOne"
    assert schema[1]["name"] == "RecordTwo"


def test_avro_deserializer_invalid_schema_type():
    """
    Ensures invalid schema types are rejected
    """
    conf = {'url': TEST_URL}
    test_client = SchemaRegistryClient(conf)
    with pytest.raises(TypeError, match="You must pass either schema string or schema object"):
        AvroDeserializer(test_client, 1)