File: test_api_client.py

package info (click to toggle)
python-confluent-kafka 1.7.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,900 kB
  • sloc: python: 8,335; ansic: 6,065; sh: 1,203; makefile: 178
file content (420 lines) | stat: -rw-r--r-- 13,335 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!/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 concurrent.futures import ThreadPoolExecutor, wait

from confluent_kafka.schema_registry.error import SchemaRegistryError
from confluent_kafka.schema_registry.schema_registry_client import Schema

"""
    Basic SchemaRegistryClient API functionality tests.

    These tests cover the following criteria using the MockSchemaRegistryClient:
        - Proper request/response handling:
            The right data sent to the right place in the right format
        - Error handling: (SR error codes are converted to a
            SchemaRegistryError correctly)
        - Caching: Caching of schema_ids and schemas works as expected.

    See ./conftest.py for details on MockSchemaRegistryClient usage.
"""
TEST_URL = 'http://SchemaRegistry:65534'
TEST_USERNAME = 'sr_user'
TEST_USER_PASSWORD = 'sr_user_secret'


def cmp_schema(schema1, schema2):
    """
    Compare to Schemas for equivalence

    Args:
        schema1 (Schema): Schema instance to compare
        schema2 (Schema): Schema instance to compare against

    Returns:
        bool: True if the schema's match else False

    """
    return all([schema1.schema_str == schema2.schema_str,
                schema1.schema_type == schema2.schema_type])


def test_basic_auth_unauthorized(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL,
            'basic.auth.user.info': "user:secret"}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="401 Unauthorized"):
        sr.get_subjects()


def test_basic_auth_authorized(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL,
            'basic.auth.user.info': mock_schema_registry.USERINFO}
    sr = mock_schema_registry(conf)

    result = sr.get_subjects()

    assert result == mock_schema_registry.SUBJECTS


def test_register_schema(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    schema = Schema(load_avsc('basic_schema.avsc'), schema_type='AVRO')

    result = sr.register_schema('test-key', schema)
    assert result == mock_schema_registry.SCHEMA_ID


def test_register_schema_incompatible(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    schema = Schema(load_avsc('basic_schema.avsc'), schema_type='AVRO')

    with pytest.raises(SchemaRegistryError, match="Incompatible Schema") as e:
        sr.register_schema('conflict', schema)

    assert e.value.http_status_code == 409
    assert e.value.error_code == -1


def test_register_schema_invalid(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    schema = Schema(load_avsc('invalid_schema.avsc'), schema_type='AVRO')

    with pytest.raises(SchemaRegistryError, match="Invalid Schema") as e:
        sr.register_schema('invalid', schema)

    assert e.value.http_status_code == 422
    assert e.value.error_code == 42201


def test_register_schema_cache(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    schema = load_avsc('basic_schema.avsc')

    count_before = sr.counter['POST'].get(
        '/subjects/test-cache/versions', 0)

    # Caching only starts after the first response is handled.
    # A possible improvement would be to add request caching to the http client
    # to catch in-flight requests as well.
    sr.register_schema('test-cache', Schema(schema, 'AVRO'))

    fs = []
    with ThreadPoolExecutor(max_workers=10) as executor:
        for _ in range(0, 1000):
            fs.append(executor.submit(sr.register_schema,
                                      'test-cache', schema))
    wait(fs)

    count_after = sr.counter['POST'].get(
        '/subjects/test-cache/versions')

    assert count_after - count_before == 1


def test_get_schema(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    schema = Schema(load_avsc(mock_schema_registry.SCHEMA), schema_type='AVRO')
    schema2 = sr.get_schema(47)

    assert cmp_schema(schema, schema2)


def test_get_schema_not_found(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="Schema not found") as e:
        sr.get_schema(404)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40403


def test_get_schema_cache(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    count_before = mock_schema_registry.counter['GET'].get(
        '/schemas/ids/47', 0)

    # Caching only starts after the first response is handled.
    # A possible improvement would be to add request caching to the http client
    # to catch in-flight requests as well.
    sr.get_schema(47)

    fs = []
    with ThreadPoolExecutor(max_workers=10) as executor:
        for _ in range(0, 1000):
            fs.append(executor.submit(sr.get_schema, 47))
    wait(fs)

    count_after = mock_schema_registry.counter['GET'].get(
        '/schemas/ids/47')

    assert count_after - count_before == 1


def test_get_registration(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = 'get_registration'
    schema = Schema(load_avsc(mock_schema_registry.SCHEMA), schema_type='AVRO')

    response = sr.lookup_schema(subject, schema)

    assert response.subject == subject
    assert response.version == mock_schema_registry.VERSION
    assert response.schema_id == mock_schema_registry.SCHEMA_ID
    assert cmp_schema(response.schema, schema)


def test_get_registration_subject_not_found(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = 'notfound'
    schema = Schema(load_avsc(mock_schema_registry.SCHEMA), schema_type='AVRO')

    with pytest.raises(SchemaRegistryError, match="Subject not found") as e:
        sr.lookup_schema(subject, schema)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40401


def test_get_registration_schema_not_found(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = 'schemanotfound'
    schema = Schema(load_avsc(mock_schema_registry.SCHEMA), schema_type='AVRO')

    with pytest.raises(SchemaRegistryError, match="Schema not found") as e:
        sr.lookup_schema(subject, schema)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40403


def test_get_subjects(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    result = sr.get_subjects()

    assert result == mock_schema_registry.SUBJECTS


def test_delete(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    result = sr.delete_subject("delete_subject")
    assert result == mock_schema_registry.VERSIONS


def test_delete_subject_not_found(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="Subject not found") as e:
        sr.delete_subject("notfound")
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40401


def test_get_version(mock_schema_registry, load_avsc):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = "get_version"
    version = 3
    schema = Schema(load_avsc(mock_schema_registry.SCHEMA), schema_type='AVRO')

    result = sr.get_version(subject, version)
    assert result.subject == subject
    assert result.version == version
    assert cmp_schema(result.schema, schema)
    assert result.schema_id == mock_schema_registry.SCHEMA_ID


def test_get_version_no_version(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = "get_version"
    version = 404

    with pytest.raises(SchemaRegistryError, match="Version not found") as e:
        sr.get_version(subject, version)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40402


def test_get_version_invalid(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = "get_version"
    version = 422

    with pytest.raises(SchemaRegistryError, match="Invalid version") as e:
        sr.get_version(subject, version)
    assert e.value.http_status_code == 422
    assert e.value.error_code == 42202


def test_get_version_subject_not_found(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    subject = "notfound"
    version = 3

    with pytest.raises(SchemaRegistryError, match="Subject not found") as e:
        sr.get_version(subject, version)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40401


def test_delete_version(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    result = sr.delete_version("delete_version", 3)

    assert result == 3


def test_delete_version_not_found(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="Version not found") as e:
        sr.delete_version("delete_version", 404)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40402


def test_delete_version_subject_not_found(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="Subject not found") as e:
        sr.delete_version("notfound", 3)
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40401


def test_delete_version_invalid(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="Invalid version") as e:
        sr.delete_version("invalid_version", 422)
    assert e.value.http_status_code == 422
    assert e.value.error_code == 42202


def test_set_compatibility(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    result = sr.set_compatibility(level="FULL")
    assert result == {'compatibility': 'FULL'}


def test_set_compatibility_invalid(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    with pytest.raises(SchemaRegistryError, match="Invalid compatibility level") as e:
        sr.set_compatibility(level="INVALID")
    e.value.http_status_code = 422
    e.value.error_code = 42203


def test_get_compatibility_subject_not_found(mock_schema_registry):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)

    with pytest.raises(SchemaRegistryError, match="Subject not found") as e:
        sr.get_compatibility("notfound")
    assert e.value.http_status_code == 404
    assert e.value.error_code == 40401


def test_schema_equivilence(load_avsc):
    schema_str1 = load_avsc('basic_schema.avsc')
    schema_str2 = load_avsc('basic_schema.avsc')

    schema = Schema(schema_str1, 'AVRO')
    schema2 = Schema(schema_str2, 'AVRO')

    assert schema.__eq__(schema2)
    assert schema == schema2
    assert schema_str1.__eq__(schema_str2)
    assert schema_str1 == schema_str2


@pytest.mark.parametrize(
    'subject_name,version,expected_compatibility',
    [
        ('conflict', 'latest', False),
        ('conflict', 1, False),
        ('test-key', 'latest', True),
        ('test-key', 1, True),
    ]
)
def test_test_compatibility_no_error(
    mock_schema_registry, load_avsc, subject_name, version, expected_compatibility
):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    schema = Schema(load_avsc('basic_schema.avsc'), schema_type='AVRO')

    is_compatible = sr.test_compatibility(subject_name, schema)
    assert is_compatible is expected_compatibility


@pytest.mark.parametrize(
    'subject_name,version,match_str,status_code,error_code',
    [
        ('notfound', 'latest', 'Subject not found', 404, 40401),
        ('invalid', 'latest', 'Invalid Schema', 422, 42201),
        ('invalid', '422', 'Invalid version', 422, 42202),
        ('notfound', 404, 'Version not found', 404, 40402),
    ]
)
def test_test_compatibility_with_error(
    mock_schema_registry, load_avsc, subject_name, version, match_str, status_code, error_code
):
    conf = {'url': TEST_URL}
    sr = mock_schema_registry(conf)
    schema = Schema(load_avsc('basic_schema.avsc'), schema_type='AVRO')

    with pytest.raises(SchemaRegistryError, match=match_str) as e:
        sr.test_compatibility(subject_name, schema, version)
    assert e.value.http_status_code == status_code
    assert e.value.error_code == error_code