Debian Codegraph @

tests/conftest.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import json
2 import random
3
4 import pytest
5 from flasgger import Swagger
6 from flasgger.utils import get_examples
7
8 from flask import Flask
9
10
11 def get_specs_data(mod):
12 """
13 return all specs dictionary for some app
14 """
15 # for each example app in /examples folder
16 from flask.testing import FlaskClient
17 client: FlaskClient = mod.app.test_client()
18 # init swag if not yet inititalized (no-routes example)
19 specs_route = None
20 specs_data = {}
21 if getattr(mod.app, 'swag', None) is None:
22 _swag = Swagger()
23 _swag.config['endpoint'] = str(random.randint(1, 5000))
24 _swag.init_app(mod.app)
25 # get all the specs defined for the example app
26 else:
27 try:
28 flasgger_config = mod.swag.config
29
30 if flasgger_config.get('swagger_ui') is False:
31 return specs_data
32
33 specs_route = flasgger_config.get('specs_route', '/apidocs/')
34 except AttributeError:
35 pass
36
37 if specs_route is None:
38 specs_route = '/apidocs/'
39
40 apidocs = client.get('?'.join((specs_route, 'json=true')))
41 if 200 <= apidocs.status_code < 300:
42 specs = json.loads(apidocs.data.decode("utf-8")).get('specs')
43
44 for spec in specs:
45 # for each spec get the spec url
46 url = spec['url']
47 response = client.get(url)
48 decoded = response.data.decode("utf-8")
49 if 200 <= response.status_code < 300:
50 specs_data[url] = json.loads(decoded)
51 else:
52 raise ValueError(f'specs failure: {mod.__name__} {response.status}')
53 else:
54 raise ValueError(f'specs meta failure: {mod.__name__} {apidocs.status}')
55
56 return specs_data
57
58
59 def get_test_metadata(mod):
60 """Create a dictionary of test metadata defined in an example
61
62 Every top-level constant prefixed with "_TEST_META_" is treated as
63 metadata which may control test behavior. The prefix is stripped and the
64 remaining text is lowercased to form the key in the metadata dictionary.
65
66 Example: '_TEST_META_SKIP_FULL_VALIDATION' -> 'skip_full_validation'
67 """
68
69 test_metadata_prefix = '_TEST_META_'
70 return {key[len(test_metadata_prefix):].lower(): getattr(mod, key)
71 for key in mod.__dict__
72 if key.startswith(test_metadata_prefix)}
73
74
75 def pytest_generate_tests(metafunc):
76 """
77 parametrize tests using examples() function
78 to generate one test for each examples/
79 """
80
81 if 'test_data' in metafunc.fixturenames:
82 test_data = [
83 (mod, mod.app.test_client(),
84 get_specs_data(mod), get_test_metadata(mod))
85 for mod in get_examples()
86 ]
87
88 metafunc.parametrize(
89 'test_data',
90 test_data,
91 ids=lambda x: x[0].__name__
92 )
93
94
95 @pytest.fixture(scope="function")
96 def app():
97 yield Flask(__name__)
98
99
100 @pytest.fixture(scope="function")
101 def cli_runner(app):
102 yield app.test_cli_runner(mix_stderr=False)