File: conftest.py

package info (click to toggle)
python-confluent-kafka 2.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,232 kB
  • sloc: python: 36,571; ansic: 9,717; sh: 1,519; makefile: 198
file content (494 lines) | stat: -rw-r--r-- 20,494 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#!/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 json
import os
import re
from base64 import b64decode
from collections import defaultdict

import pytest
import respx
from httpx import Response

work_dir = os.path.dirname(os.path.realpath(__file__))


"""
Schema Registry mock.

The MockSchemaRegistry client uses special uri paths to invoke specific
behavior such as coercing an error. They are listed in the table below.
The paths are formed using special keywords referred to as triggers.

Triggers are used to inform the MockSchemaRegistry how to behave when
receiving a request. For instance the `notfound` trigger word when placed
in the subject field of the path will return a http status code of 404 and
the appropriate Schema Registry Error(40401 Schema not found).

Whenever the response includes content from the request body it will return
the same data from the request.

For example the following request will return 123:
    DELETE  /subjects/notfound/versions/123
    or
    SchemaRegistryClient.delete_version("delete_version", 123)

All response items which can't be fulfilled with the contents of the request
are populated with constants. Which may be referenced when validating the
response.

    - SCHEMA_ID = 47
    - VERSION = 3
    - VERSIONS = [1, 2, 3, 4]
    - SCHEMA = 'basic_schema.avsc'
    - SUBJECTS = ['subject1', 'subject2'].

Trigger keywords may also be used in the body of the requests. At this time
the only endpoint which supports this is /config which will return an
`Invalid compatibility level` error.

To coerce Authentication errors configure credentials to
not match MockSchemaRegistryClient.USERINFO.

Request paths to trigger exceptions:
+--------+-------------------------------------------------+-------+------------------------------+
| Method |         Request Path                            | Code  |      Description             |
+========+=================================================+=======+==============================+
| GET    | /schemas/ids/404                                | 40403 | Schema not found             |
+--------+-------------------------------------------------+-------+------------------------------+
| GET    | /subjects/notfound/versions                     | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| GET    | /subjects/notfound/versions/[0-9]               | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| GET    | /subjects/notfound/versions/404                 | 40402 | Version not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| GET    | /subjects/notfound/versions/422                 | 42202 | Invalid version              |
+--------+-------------------------------------------------+-------+------------------------------+
| DELETE | /subjects/notfound                              | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /subjects/conflict/versions                     | 409*  | Incompatible Schema          |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /subjects/invalid/versions                      | 42201 | Invalid Schema               |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /subjects/notfound                              | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /subjects/schemanotfound                        | 40403 | Schema not found             |
+--------+-------------------------------------------------+-------+------------------------------+
| DELETE | /subjects/notfound                              | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| DELETE | /subjects/notfound/versions/[0-9]               | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| DELETE | /subjects/notfound/versions/404                 | 40402 | Version not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| DELETE | /subjects/notfound/versions/422                 | 42202 | Invalid version              |
+--------+-------------------------------------------------+-------+------------------------------+
| GET    | /config/notfound                                | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| PUT    | /config**                                       | 42203 | Invalid compatibility level  |
+--------+-------------------------------------------------+-------+------------------------------+
| DELETE | /config/notfound                                | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /compatibility/subjects/notfound/versions/[0-9] | 40401 | Subject not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /compatibility/subjects/invalid/versions/[0-9]  | 42201 | Invalid Schema               |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /compatibility/subjects/notfound/versions/404   | 40402 | Version not found            |
+--------+-------------------------------------------------+-------+------------------------------+
| POST   | /compatibility/subjects/invalid/versions/bad    | 42202 | Invalid version              |
+--------+-------------------------------------------------+-------+------------------------------+
| PUT    | /mode/invalid_mode                              | 42204 | Invalid mode                 |
+--------+-------------------------------------------------+-------+------------------------------+
| PUT    | /mode/operation_not_permitted                   | 42205 | Operation not permitted      |
+--------+-------------------------------------------------+-------+------------------------------+
* POST /subjects/{}/versions does not follow the documented API error.
** PUT /config reacts to a trigger in the body: - {"compatibility": "FULL"}

When evaluating special paths with overlapping trigger words the right most
keyword will take precedence.

i.e. Version not found will be returned for the following path.
    /subjects/notfound/versions/404

The config endpoint has a special compatibility level "INVALID". This should
be used to verify the handling of in valid compatibility settings.

"""


@pytest.fixture()
def mock_schema_registry():
    with (respx.mock as respx_mock):
        respx_mock.route().mock(side_effect=_auth_matcher)

        respx_mock.post(COMPATIBILITY_SUBJECTS_VERSIONS_RE).mock(
            side_effect=post_compatibility_subjects_versions_callback)
        respx_mock.post(COMPATIBILITY_SUBJECTS_ALL_VERSIONS_RE).mock(
            side_effect=post_compatibility_subjects_all_versions_callback)

        respx_mock.get(CONFIG_RE).mock(side_effect=get_config_callback)
        respx_mock.put(CONFIG_RE).mock(side_effect=put_config_callback)
        respx_mock.delete(CONFIG_RE).mock(side_effect=delete_config_callback)

        respx_mock.get(CONTEXTS_RE).mock(side_effect=get_contexts_callback)

        respx_mock.get(MODE_GLOBAL_RE).mock(side_effect=get_global_mode_callback)
        respx_mock.put(MODE_GLOBAL_RE).mock(side_effect=put_global_mode_callback)
        respx_mock.get(MODE_RE).mock(side_effect=get_mode_callback)
        respx_mock.put(MODE_RE).mock(side_effect=put_mode_callback)
        respx_mock.delete(MODE_RE).mock(side_effect=delete_mode_callback)

        respx_mock.get(SCHEMAS_RE).mock(side_effect=get_schemas_callback)
        respx_mock.get(SCHEMAS_VERSIONS_RE).mock(side_effect=get_schema_versions_callback)
        respx_mock.get(SCHEMAS_SUBJECTS_RE).mock(side_effect=get_schema_subjects_callback)
        respx_mock.get(SCHEMAS_TYPES_RE).mock(side_effect=get_schema_types_callback)

        respx_mock.get(SUBJECTS_VERSIONS_REFERENCED_BY_RE).mock(side_effect=get_subject_version_referenced_by_callback)
        respx_mock.get(SUBJECTS_VERSIONS_RE).mock(side_effect=get_subject_version_callback)
        respx_mock.delete(SUBJECTS_VERSIONS_RE).mock(side_effect=delete_subject_version_callback)
        respx_mock.post(SUBJECTS_VERSIONS_RE).mock(side_effect=post_subject_version_callback)

        respx_mock.delete(SUBJECTS_RE).mock(side_effect=delete_subject_callback)
        respx_mock.get(SUBJECTS_RE).mock(side_effect=get_subject_callback)
        respx_mock.post(SUBJECTS_RE).mock(side_effect=post_subject_callback)

        yield respx_mock


# request paths
SCHEMAS_RE = re.compile("/schemas/ids/([0-9]*)$")
SCHEMAS_VERSIONS_RE = re.compile(r"/schemas/ids/([0-9]*)/versions(\?.*)?$")
SCHEMAS_SUBJECTS_RE = re.compile(r"/schemas/ids/([0-9]*)/subjects(\?.*)?$")
SCHEMAS_TYPES_RE = re.compile("/schemas/types$")

SUBJECTS_RE = re.compile("/subjects/?(.*)$")
SUBJECTS_VERSIONS_RE = re.compile("/subjects/(.*)/versions/?(.*)$")
SUBJECTS_VERSIONS_SCHEMA_RE = re.compile(r"/subjects/(.*)/versions/(.*)/schema(\?.*)?$")
SUBJECTS_VERSIONS_REFERENCED_BY_RE = re.compile(r"/subjects/(.*)/versions/(.*)/referencedby(\?.*)?$")

CONFIG_RE = re.compile("/config/?(.*)$")

COMPATIBILITY_SUBJECTS_VERSIONS_RE = re.compile("/compatibility/subjects/(.*)/versions/?(.*)$")
COMPATIBILITY_SUBJECTS_ALL_VERSIONS_RE = re.compile("/compatibility/subjects/(.*)/versions")

MODE_GLOBAL_RE = re.compile(r"/mode(\?.*)?$")
MODE_RE = re.compile("/mode/(.*)$")

CONTEXTS_RE = re.compile(r"/contexts(\?.*)?$")

# constants
SCHEMA_ID = 47
VERSION = 3
VERSIONS = [1, 2, 3, 4]
SCHEMA = 'basic_schema.avsc'
SUBJECTS = ['subject1', 'subject2']
USERINFO = 'mock_user:mock_password'

# Counts requests handled per path by HTTP method
# {HTTP method: { path : count}}
COUNTER = {'DELETE': defaultdict(int),
           'GET': defaultdict(int),
           'POST': defaultdict(int),
           'PUT': defaultdict(int)}


def _auth_matcher(request):
    headers = request.headers

    authinfo = headers.get('Authorization', None)
    # Pass request to downstream matchers
    if authinfo is None:
        return None

    # We only support the BASIC scheme today
    scheme, userinfo = authinfo.split(" ")
    if b64decode(userinfo).decode('utf-8') == USERINFO:
        return None

    unauthorized = {'error_code': 401,
                    'message': "401 Unauthorized"}
    return Response(401, json=unauthorized)


def _load_avsc(name) -> str:
    with open(os.path.join(work_dir, '..', 'integration', 'schema_registry',
                           'data', name)) as fd:
        return fd.read()


def get_config_callback(request, route):
    COUNTER['GET'][request.url.path] += 1

    path_match = re.match(CONFIG_RE, request.url.path)
    subject = path_match.group(1)

    if subject == "notfound":
        return Response(404, json={'error_code': 40401,
                                   'message': "Subject not found"})

    return Response(200, json={'compatibility': 'FULL'})


def put_config_callback(request, route):
    COUNTER['PUT'][request.url.path] += 1

    body = json.loads(request.content.decode('utf-8'))
    level = body.get('compatibility')

    if level == "INVALID":
        return Response(422, json={'error_code': 42203,
                                   'message': "Invalid compatibility level"})

    return Response(200, json=body)


def delete_config_callback(request, route):
    COUNTER['DELETE'][request.url.path] += 1

    path_match = re.match(CONFIG_RE, request.url.path)
    subject = path_match.group(1)

    if subject == "notfound":
        return Response(404, json={'error_code': 40401,
                                   'message': "Subject not found"})

    return Response(200, json={'compatibility': 'FULL'})


def get_contexts_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json=['context1', 'context2'])


def delete_subject_callback(request, route):
    COUNTER['DELETE'][request.url.path] += 1

    path_match = re.match(SUBJECTS_RE, request.url.path)
    subject = path_match.group(1)

    if subject == "notfound":
        return Response(404, json={'error_code': 40401,
                                   'message': "Subject not found"})

    return Response(200, json=VERSIONS)


def get_subject_callback(request, route):
    COUNTER['GET'][request.url.path] += 1

    return Response(200, json=SUBJECTS)


def post_subject_callback(request, route):
    COUNTER['POST'][request.url.path] += 1

    path_match = re.match(SUBJECTS_RE, request.url.path)
    subject = path_match.group(1)

    if subject == 'notfound':
        return Response(404, json={'error_code': 40401,
                                   'message': "Subject not found"})
    if subject == 'schemanotfound':
        return Response(404, json={'error_code': 40403,
                                   'message': "Schema not found"})

    body = json.loads(request.content.decode('utf-8'))
    return Response(200, json={'subject': subject,
                               "id": SCHEMA_ID,
                               "version": VERSION,
                               "schema": body['schema']})


def get_schemas_callback(request, route):
    COUNTER['GET'][request.url.path] += 1

    path_match = re.match(SCHEMAS_RE, request.url.path)
    schema_id = path_match.group(1)

    if int(schema_id) == 404:
        return Response(404, json={'error_code': 40403,
                                   'message': "Schema not found"})

    return Response(200, json={'schema': _load_avsc(SCHEMA)})


def get_schema_subjects_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json=SUBJECTS)


def get_schema_types_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json=['AVRO', 'JSON', 'PROTOBUF'])


def get_schema_versions_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json=[
        {'subject': 'subject1', 'version': 1},
        {'subject': 'subject2', 'version': 2}
    ])


def get_subject_version_callback(request, route):
    COUNTER['GET'][request.url.path] += 1

    path_match = re.match(SUBJECTS_VERSIONS_RE, request.url.path)
    subject = path_match.group(1)
    version = path_match.group(2)
    version_num = -1 if version == 'latest' else int(version)

    if version_num == 404:
        return Response(404, json={'error_code': 40402,
                                   'message': "Version not found"})
    if version_num == 422:
        return Response(422, json={'error_code': 42202,
                                   'message': "Invalid version"})
    if subject == 'notfound':
        return Response(404, json={'error_code': 40401,
                                   'message': "Subject not found"})
    return Response(200, json={'subject': subject,
                               'id': SCHEMA_ID,
                               'version': version_num,
                               'schema': _load_avsc(SCHEMA)})


def delete_subject_version_callback(request, route):
    COUNTER['DELETE'][request.url.path] += 1

    path_match = re.match(SUBJECTS_VERSIONS_RE, request.url.path)
    subject = path_match.group(1)
    version = path_match.group(2)
    version_num = -1 if version == 'latest' else int(version)

    if version_num == 404:
        return Response(404, json={'error_code': 40402,
                                   'message': "Version not found"})

    if version_num == 422:
        return Response(422, json={'error_code': 42202,
                                   'message': "Invalid version"})

    if subject == "notfound":
        return Response(404, json={'error_code': 40401,
                                   'message': "Subject not found"})

    return Response(200, json=version_num)


def post_subject_version_callback(request, route):
    COUNTER['POST'][request.url.path] += 1

    path_match = re.match(SUBJECTS_VERSIONS_RE, request.url.path)
    subject = path_match.group(1)
    if subject == "conflict":
        # oddly the Schema Registry does not send a proper error for this.
        return Response(409, json={'error_code': -1,
                                   'message': "Incompatible Schema"})

    if subject == "invalid":
        return Response(422, json={'error_code': 42201,
                                   'message': "Invalid Schema"})
    else:
        return Response(200, json={'id': SCHEMA_ID})


def get_subject_version_referenced_by_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json=[1, 2])


def post_compatibility_subjects_versions_callback(request, route):
    COUNTER['POST'][request.url.path] += 1

    path_match = re.match(COMPATIBILITY_SUBJECTS_VERSIONS_RE, request.url.path)
    subject = path_match.group(1)
    version = path_match.group(2)

    if version == '422':
        return Response(422, json={'error_code': 42202,
                                   'message': 'Invalid version'})

    if version == '404':
        return Response(404, json={'error_code': 40402,
                                   'message': 'Version not found'})

    if subject == 'conflict':
        return Response(200, json={'is_compatible': False})

    if subject == 'notfound':
        return Response(404, json={'error_code': 40401,
                                   'message': 'Subject not found'})

    if subject == 'invalid':
        return Response(422, json={'error_code': 42201,
                                   'message': 'Invalid Schema'})

    return Response(200, json={'is_compatible': True})


def post_compatibility_subjects_all_versions_callback(request, route):
    COUNTER['POST'][request.url.path] += 1
    return Response(200, json={'is_compatible': True})


def get_global_mode_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json={'mode': 'READWRITE'})


def put_global_mode_callback(request, route):
    COUNTER['PUT'][request.url.path] += 1
    body = json.loads(request.content.decode('utf-8'))
    return Response(200, json=body)


def get_mode_callback(request, route):
    COUNTER['GET'][request.url.path] += 1
    return Response(200, json={'mode': 'READWRITE'})


def put_mode_callback(request, route):
    COUNTER['PUT'][request.url.path] += 1

    path_match = re.match(MODE_RE, request.url.path)
    subject = path_match.group(1)
    body = json.loads(request.content.decode('utf-8'))
    mode = body.get('mode')

    if subject == 'invalid_mode':
        return Response(422, json={'error_code': 42204,
                                   'message': "Invalid mode"})
    if subject == 'operation_not_permitted':
        return Response(422, json={'error_code': 42205,
                                   'message': "Operation not permitted"})
    return Response(200, json={'mode': mode})


def delete_mode_callback(request, route):
    COUNTER['DELETE'][request.url.path] += 1
    return Response(200, json={'mode': 'READWRITE'})


@pytest.fixture(scope="package")
def load_avsc():
    def get_handle(name):
        with open(os.path.join(work_dir, '..', 'integration', 'schema_registry',
                               'data', name)) as fd:
            return fd.read()

    return get_handle