Debian Codegraph @

tests/schema_registry/conftest.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 json
19 import os
20 import re
21 from base64 import b64decode
22 from collections import defaultdict
23
24 import pytest
25 import respx
26 from httpx import Response
27
28 work_dir = os.path.dirname(os.path.realpath(__file__))
29
30
31 """
32 Schema Registry mock.
33
34 The MockSchemaRegistry client uses special uri paths to invoke specific
35 behavior such as coercing an error. They are listed in the table below.
36 The paths are formed using special keywords referred to as triggers.
37
38 Triggers are used to inform the MockSchemaRegistry how to behave when
39 receiving a request. For instance the `notfound` trigger word when placed
40 in the subject field of the path will return a http status code of 404 and
41 the appropriate Schema Registry Error(40401 Schema not found).
42
43 Whenever the response includes content from the request body it will return
44 the same data from the request.
45
46 For example the following request will return 123:
47 DELETE /subjects/notfound/versions/123
48 or
49 SchemaRegistryClient.delete_version("delete_version", 123)
50
51 All response items which can't be fulfilled with the contents of the request
52 are populated with constants. Which may be referenced when validating the
53 response.
54
55 - SCHEMA_ID = 47
56 - VERSION = 3
57 - VERSIONS = [1, 2, 3, 4]
58 - SCHEMA = 'basic_schema.avsc'
59 - SUBJECTS = ['subject1', 'subject2'].
60
61 Trigger keywords may also be used in the body of the requests. At this time
62 the only endpoint which supports this is /config which will return an
63 `Invalid compatibility level` error.
64
65 To coerce Authentication errors configure credentials to
66 not match MockSchemaRegistryClient.USERINFO.
67
68 Request paths to trigger exceptions:
69 +--------+-------------------------------------------------+-------+------------------------------+
70 | Method | Request Path | Code | Description |
71 +========+=================================================+=======+==============================+
72 | GET | /schemas/ids/404 | 40403 | Schema not found |
73 +--------+-------------------------------------------------+-------+------------------------------+
74 | GET | /subjects/notfound/versions | 40401 | Subject not found |
75 +--------+-------------------------------------------------+-------+------------------------------+
76 | GET | /subjects/notfound/versions/[0-9] | 40401 | Subject not found |
77 +--------+-------------------------------------------------+-------+------------------------------+
78 | GET | /subjects/notfound/versions/404 | 40402 | Version not found |
79 +--------+-------------------------------------------------+-------+------------------------------+
80 | GET | /subjects/notfound/versions/422 | 42202 | Invalid version |
81 +--------+-------------------------------------------------+-------+------------------------------+
82 | DELETE | /subjects/notfound | 40401 | Subject not found |
83 +--------+-------------------------------------------------+-------+------------------------------+
84 | POST | /subjects/conflict/versions | 409* | Incompatible Schema |
85 +--------+-------------------------------------------------+-------+------------------------------+
86 | POST | /subjects/invalid/versions | 42201 | Invalid Schema |
87 +--------+-------------------------------------------------+-------+------------------------------+
88 | POST | /subjects/notfound | 40401 | Subject not found |
89 +--------+-------------------------------------------------+-------+------------------------------+
90 | POST | /subjects/schemanotfound | 40403 | Schema not found |
91 +--------+-------------------------------------------------+-------+------------------------------+
92 | DELETE | /subjects/notfound | 40401 | Subject not found |
93 +--------+-------------------------------------------------+-------+------------------------------+
94 | DELETE | /subjects/notfound/versions/[0-9] | 40401 | Subject not found |
95 +--------+-------------------------------------------------+-------+------------------------------+
96 | DELETE | /subjects/notfound/versions/404 | 40402 | Version not found |
97 +--------+-------------------------------------------------+-------+------------------------------+
98 | DELETE | /subjects/notfound/versions/422 | 42202 | Invalid version |
99 +--------+-------------------------------------------------+-------+------------------------------+
100 | GET | /config/notfound | 40401 | Subject not found |
101 +--------+-------------------------------------------------+-------+------------------------------+
102 | PUT | /config** | 42203 | Invalid compatibility level |
103 +--------+-------------------------------------------------+-------+------------------------------+
104 | DELETE | /config/notfound | 40401 | Subject not found |
105 +--------+-------------------------------------------------+-------+------------------------------+
106 | POST | /compatibility/subjects/notfound/versions/[0-9] | 40401 | Subject not found |
107 +--------+-------------------------------------------------+-------+------------------------------+
108 | POST | /compatibility/subjects/invalid/versions/[0-9] | 42201 | Invalid Schema |
109 +--------+-------------------------------------------------+-------+------------------------------+
110 | POST | /compatibility/subjects/notfound/versions/404 | 40402 | Version not found |
111 +--------+-------------------------------------------------+-------+------------------------------+
112 | POST | /compatibility/subjects/invalid/versions/bad | 42202 | Invalid version |
113 +--------+-------------------------------------------------+-------+------------------------------+
114 | PUT | /mode/invalid_mode | 42204 | Invalid mode |
115 +--------+-------------------------------------------------+-------+------------------------------+
116 | PUT | /mode/operation_not_permitted | 42205 | Operation not permitted |
117 +--------+-------------------------------------------------+-------+------------------------------+
118 * POST /subjects/{}/versions does not follow the documented API error.
119 ** PUT /config reacts to a trigger in the body: - {"compatibility": "FULL"}
120
121 When evaluating special paths with overlapping trigger words the right most
122 keyword will take precedence.
123
124 i.e. Version not found will be returned for the following path.
125 /subjects/notfound/versions/404
126
127 The config endpoint has a special compatibility level "INVALID". This should
128 be used to verify the handling of in valid compatibility settings.
129
130 """
131
132
133 @pytest.fixture()
134 def mock_schema_registry():
135 with (respx.mock as respx_mock):
136 respx_mock.route().mock(side_effect=_auth_matcher)
137
138 respx_mock.post(COMPATIBILITY_SUBJECTS_VERSIONS_RE).mock(
139 side_effect=post_compatibility_subjects_versions_callback)
140 respx_mock.post(COMPATIBILITY_SUBJECTS_ALL_VERSIONS_RE).mock(
141 side_effect=post_compatibility_subjects_all_versions_callback)
142
143 respx_mock.get(CONFIG_RE).mock(side_effect=get_config_callback)
144 respx_mock.put(CONFIG_RE).mock(side_effect=put_config_callback)
145 respx_mock.delete(CONFIG_RE).mock(side_effect=delete_config_callback)
146
147 respx_mock.get(CONTEXTS_RE).mock(side_effect=get_contexts_callback)
148
149 respx_mock.get(MODE_GLOBAL_RE).mock(side_effect=get_global_mode_callback)
150 respx_mock.put(MODE_GLOBAL_RE).mock(side_effect=put_global_mode_callback)
151 respx_mock.get(MODE_RE).mock(side_effect=get_mode_callback)
152 respx_mock.put(MODE_RE).mock(side_effect=put_mode_callback)
153 respx_mock.delete(MODE_RE).mock(side_effect=delete_mode_callback)
154
155 respx_mock.get(SCHEMAS_RE).mock(side_effect=get_schemas_callback)
156 respx_mock.get(SCHEMAS_VERSIONS_RE).mock(side_effect=get_schema_versions_callback)
157 respx_mock.get(SCHEMAS_SUBJECTS_RE).mock(side_effect=get_schema_subjects_callback)
158 respx_mock.get(SCHEMAS_TYPES_RE).mock(side_effect=get_schema_types_callback)
159
160 respx_mock.get(SUBJECTS_VERSIONS_REFERENCED_BY_RE).mock(side_effect=get_subject_version_referenced_by_callback)
161 respx_mock.get(SUBJECTS_VERSIONS_RE).mock(side_effect=get_subject_version_callback)
162 respx_mock.delete(SUBJECTS_VERSIONS_RE).mock(side_effect=delete_subject_version_callback)
163 respx_mock.post(SUBJECTS_VERSIONS_RE).mock(side_effect=post_subject_version_callback)
164
165 respx_mock.delete(SUBJECTS_RE).mock(side_effect=delete_subject_callback)
166 respx_mock.get(SUBJECTS_RE).mock(side_effect=get_subject_callback)
167 respx_mock.post(SUBJECTS_RE).mock(side_effect=post_subject_callback)
168
169 yield respx_mock
170
171
172 # request paths
173 SCHEMAS_RE = re.compile("/schemas/ids/([0-9]*)$")
174 SCHEMAS_VERSIONS_RE = re.compile(r"/schemas/ids/([0-9]*)/versions(\?.*)?$")
175 SCHEMAS_SUBJECTS_RE = re.compile(r"/schemas/ids/([0-9]*)/subjects(\?.*)?$")
176 SCHEMAS_TYPES_RE = re.compile("/schemas/types$")
177
178 SUBJECTS_RE = re.compile("/subjects/?(.*)$")
179 SUBJECTS_VERSIONS_RE = re.compile("/subjects/(.*)/versions/?(.*)$")
180 SUBJECTS_VERSIONS_SCHEMA_RE = re.compile(r"/subjects/(.*)/versions/(.*)/schema(\?.*)?$")
181 SUBJECTS_VERSIONS_REFERENCED_BY_RE = re.compile(r"/subjects/(.*)/versions/(.*)/referencedby(\?.*)?$")
182
183 CONFIG_RE = re.compile("/config/?(.*)$")
184
185 COMPATIBILITY_SUBJECTS_VERSIONS_RE = re.compile("/compatibility/subjects/(.*)/versions/?(.*)$")
186 COMPATIBILITY_SUBJECTS_ALL_VERSIONS_RE = re.compile("/compatibility/subjects/(.*)/versions")
187
188 MODE_GLOBAL_RE = re.compile(r"/mode(\?.*)?$")
189 MODE_RE = re.compile("/mode/(.*)$")
190
191 CONTEXTS_RE = re.compile(r"/contexts(\?.*)?$")
192
193 # constants
194 SCHEMA_ID = 47
195 VERSION = 3
196 VERSIONS = [1, 2, 3, 4]
197 SCHEMA = 'basic_schema.avsc'
198 SUBJECTS = ['subject1', 'subject2']
199 USERINFO = 'mock_user:mock_password'
200
201 # Counts requests handled per path by HTTP method
202 # {HTTP method: { path : count}}
203 COUNTER = {'DELETE': defaultdict(int),
204 'GET': defaultdict(int),
205 'POST': defaultdict(int),
206 'PUT': defaultdict(int)}
207
208
209 def _auth_matcher(request):
210 headers = request.headers
211
212 authinfo = headers.get('Authorization', None)
213 # Pass request to downstream matchers
214 if authinfo is None:
215 return None
216
217 # We only support the BASIC scheme today
218 scheme, userinfo = authinfo.split(" ")
219 if b64decode(userinfo).decode('utf-8') == USERINFO:
220 return None
221
222 unauthorized = {'error_code': 401,
223 'message': "401 Unauthorized"}
224 return Response(401, json=unauthorized)
225
226
227 def _load_avsc(name) -> str:
228 with open(os.path.join(work_dir, '..', 'integration', 'schema_registry',
229 'data', name)) as fd:
230 return fd.read()
231
232
233 def get_config_callback(request, route):
234 COUNTER['GET'][request.url.path] += 1
235
236 path_match = re.match(CONFIG_RE, request.url.path)
237 subject = path_match.group(1)
238
239 if subject == "notfound":
240 return Response(404, json={'error_code': 40401,
241 'message': "Subject not found"})
242
243 return Response(200, json={'compatibility': 'FULL'})
244
245
246 def put_config_callback(request, route):
247 COUNTER['PUT'][request.url.path] += 1
248
249 body = json.loads(request.content.decode('utf-8'))
250 level = body.get('compatibility')
251
252 if level == "INVALID":
253 return Response(422, json={'error_code': 42203,
254 'message': "Invalid compatibility level"})
255
256 return Response(200, json=body)
257
258
259 def delete_config_callback(request, route):
260 COUNTER['DELETE'][request.url.path] += 1
261
262 path_match = re.match(CONFIG_RE, request.url.path)
263 subject = path_match.group(1)
264
265 if subject == "notfound":
266 return Response(404, json={'error_code': 40401,
267 'message': "Subject not found"})
268
269 return Response(200, json={'compatibility': 'FULL'})
270
271
272 def get_contexts_callback(request, route):
273 COUNTER['GET'][request.url.path] += 1
274 return Response(200, json=['context1', 'context2'])
275
276
277 def delete_subject_callback(request, route):
278 COUNTER['DELETE'][request.url.path] += 1
279
280 path_match = re.match(SUBJECTS_RE, request.url.path)
281 subject = path_match.group(1)
282
283 if subject == "notfound":
284 return Response(404, json={'error_code': 40401,
285 'message': "Subject not found"})
286
287 return Response(200, json=VERSIONS)
288
289
290 def get_subject_callback(request, route):
291 COUNTER['GET'][request.url.path] += 1
292
293 return Response(200, json=SUBJECTS)
294
295
296 def post_subject_callback(request, route):
297 COUNTER['POST'][request.url.path] += 1
298
299 path_match = re.match(SUBJECTS_RE, request.url.path)
300 subject = path_match.group(1)
301
302 if subject == 'notfound':
303 return Response(404, json={'error_code': 40401,
304 'message': "Subject not found"})
305 if subject == 'schemanotfound':
306 return Response(404, json={'error_code': 40403,
307 'message': "Schema not found"})
308
309 body = json.loads(request.content.decode('utf-8'))
310 return Response(200, json={'subject': subject,
311 "id": SCHEMA_ID,
312 "version": VERSION,
313 "schema": body['schema']})
314
315
316 def get_schemas_callback(request, route):
317 COUNTER['GET'][request.url.path] += 1
318
319 path_match = re.match(SCHEMAS_RE, request.url.path)
320 schema_id = path_match.group(1)
321
322 if int(schema_id) == 404:
323 return Response(404, json={'error_code': 40403,
324 'message': "Schema not found"})
325
326 return Response(200, json={'schema': _load_avsc(SCHEMA)})
327
328
329 def get_schema_subjects_callback(request, route):
330 COUNTER['GET'][request.url.path] += 1
331 return Response(200, json=SUBJECTS)
332
333
334 def get_schema_types_callback(request, route):
335 COUNTER['GET'][request.url.path] += 1
336 return Response(200, json=['AVRO', 'JSON', 'PROTOBUF'])
337
338
339 def get_schema_versions_callback(request, route):
340 COUNTER['GET'][request.url.path] += 1
341 return Response(200, json=[
342 {'subject': 'subject1', 'version': 1},
343 {'subject': 'subject2', 'version': 2}
344 ])
345
346
347 def get_subject_version_callback(request, route):
348 COUNTER['GET'][request.url.path] += 1
349
350 path_match = re.match(SUBJECTS_VERSIONS_RE, request.url.path)
351 subject = path_match.group(1)
352 version = path_match.group(2)
353 version_num = -1 if version == 'latest' else int(version)
354
355 if version_num == 404:
356 return Response(404, json={'error_code': 40402,
357 'message': "Version not found"})
358 if version_num == 422:
359 return Response(422, json={'error_code': 42202,
360 'message': "Invalid version"})
361 if subject == 'notfound':
362 return Response(404, json={'error_code': 40401,
363 'message': "Subject not found"})
364 return Response(200, json={'subject': subject,
365 'id': SCHEMA_ID,
366 'version': version_num,
367 'schema': _load_avsc(SCHEMA)})
368
369
370 def delete_subject_version_callback(request, route):
371 COUNTER['DELETE'][request.url.path] += 1
372
373 path_match = re.match(SUBJECTS_VERSIONS_RE, request.url.path)
374 subject = path_match.group(1)
375 version = path_match.group(2)
376 version_num = -1 if version == 'latest' else int(version)
377
378 if version_num == 404:
379 return Response(404, json={'error_code': 40402,
380 'message': "Version not found"})
381
382 if version_num == 422:
383 return Response(422, json={'error_code': 42202,
384 'message': "Invalid version"})
385
386 if subject == "notfound":
387 return Response(404, json={'error_code': 40401,
388 'message': "Subject not found"})
389
390 return Response(200, json=version_num)
391
392
393 def post_subject_version_callback(request, route):
394 COUNTER['POST'][request.url.path] += 1
395
396 path_match = re.match(SUBJECTS_VERSIONS_RE, request.url.path)
397 subject = path_match.group(1)
398 if subject == "conflict":
399 # oddly the Schema Registry does not send a proper error for this.
400 return Response(409, json={'error_code': -1,
401 'message': "Incompatible Schema"})
402
403 if subject == "invalid":
404 return Response(422, json={'error_code': 42201,
405 'message': "Invalid Schema"})
406 else:
407 return Response(200, json={'id': SCHEMA_ID})
408
409
410 def get_subject_version_referenced_by_callback(request, route):
411 COUNTER['GET'][request.url.path] += 1
412 return Response(200, json=[1, 2])
413
414
415 def post_compatibility_subjects_versions_callback(request, route):
416 COUNTER['POST'][request.url.path] += 1
417
418 path_match = re.match(COMPATIBILITY_SUBJECTS_VERSIONS_RE, request.url.path)
419 subject = path_match.group(1)
420 version = path_match.group(2)
421
422 if version == '422':
423 return Response(422, json={'error_code': 42202,
424 'message': 'Invalid version'})
425
426 if version == '404':
427 return Response(404, json={'error_code': 40402,
428 'message': 'Version not found'})
429
430 if subject == 'conflict':
431 return Response(200, json={'is_compatible': False})
432
433 if subject == 'notfound':
434 return Response(404, json={'error_code': 40401,
435 'message': 'Subject not found'})
436
437 if subject == 'invalid':
438 return Response(422, json={'error_code': 42201,
439 'message': 'Invalid Schema'})
440
441 return Response(200, json={'is_compatible': True})
442
443
444 def post_compatibility_subjects_all_versions_callback(request, route):
445 COUNTER['POST'][request.url.path] += 1
446 return Response(200, json={'is_compatible': True})
447
448
449 def get_global_mode_callback(request, route):
450 COUNTER['GET'][request.url.path] += 1
451 return Response(200, json={'mode': 'READWRITE'})
452
453
454 def put_global_mode_callback(request, route):
455 COUNTER['PUT'][request.url.path] += 1
456 body = json.loads(request.content.decode('utf-8'))
457 return Response(200, json=body)
458
459
460 def get_mode_callback(request, route):
461 COUNTER['GET'][request.url.path] += 1
462 return Response(200, json={'mode': 'READWRITE'})
463
464
465 def put_mode_callback(request, route):
466 COUNTER['PUT'][request.url.path] += 1
467
468 path_match = re.match(MODE_RE, request.url.path)
469 subject = path_match.group(1)
470 body = json.loads(request.content.decode('utf-8'))
471 mode = body.get('mode')
472
473 if subject == 'invalid_mode':
474 return Response(422, json={'error_code': 42204,
475 'message': "Invalid mode"})
476 if subject == 'operation_not_permitted':
477 return Response(422, json={'error_code': 42205,
478 'message': "Operation not permitted"})
479 return Response(200, json={'mode': mode})
480
481
482 def delete_mode_callback(request, route):
483 COUNTER['DELETE'][request.url.path] += 1
484 return Response(200, json={'mode': 'READWRITE'})
485
486
487 @pytest.fixture(scope="package")
488 def load_avsc():
489 def get_handle(name):
490 with open(os.path.join(work_dir, '..', 'integration', 'schema_registry',
491 'data', name)) as fd:
492 return fd.read()
493
494 return get_handle