/
testing.py
222 lines (170 loc) · 7.75 KB
/
testing.py
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
import contextlib
import click
import click.testing
import flask
from flask_webtest import TestApp
from werkzeug.datastructures import ImmutableMultiDict, MultiDict
from keg import current_app, signals
from keg.utils import app_environ_get
def _config_profile(appcls):
config_profile = 'TestProfile'
if appcls.import_name is not None:
config_profile = app_environ_get(appcls.import_name, 'CONFIG_PROFILE', config_profile)
return config_profile
class ContextManager(object):
"""
Facilitates having a single instance of an application ready for testing.
By default, this is used in ``Keg.testing_prep``.
Constructor arg is the Keg app class to manage for tests.
"""
apps = {}
def __init__(self, appcls):
self.appcls = appcls
self.app = None
self.ctx = None
def ensure_current(self, config):
"""Ensure the manager's app has an instance set as flask's ``current_app``"""
if not self.app:
self.app = self.appcls().init(use_test_profile=True, config=config)
self.ctx = self.app.app_context()
self.ctx.push()
if current_app._get_current_object is not self.app:
self.ctx.push()
return self.app
def cleanup(self):
"""Pop the app context"""
self.ctx.pop()
def is_ready(self):
"""Indicates the manager's app instance exists.
The instance should be created with ``get_for``. Only one ContextManager instance will get
created in a Python process for any given app. But, ``get_for`` may be called multiple
times. The first call to ``ensure_current`` will set up the application and bring the
manager to a ready state."""
return self.app is not None
@classmethod
def get_for(cls, appcls):
"""
Return the ContextManager instance for the given app class. Only one ContextManager
instance will be created in a Python process for any given app.
"""
if appcls not in cls.apps:
cls.apps[appcls] = cls(appcls)
return cls.apps[appcls]
@contextlib.contextmanager
def app_config(**kwargs):
"""
Set config values on any apps instantiated while the context manager is active.
This is intended to be used with cli tests where the ``current_app`` in the test will be
different from the ``current_app`` when the CLI command is invoked, making it very difficult
to dynamically set app config variables using mock.patch.dict like we normally would.
Example::
class TestCLI(CLIBase):
app_cls = MyApp
def test_it(self):
with testing.app_config(FOO_NAME='Bar'):
result = self.invoke('echo-foo-name')
assert 'Bar' in result.output
"""
@signals.config_complete.connect
def set_config(app):
app.config.update(kwargs)
yield
@contextlib.contextmanager
def inrequest(*req_args, args_modifier=None, **req_kwargs):
"""A decorator/context manager to add the flask request context to a test function.
Allows test to assume a request context without running a full view stack. Use for
unit-testing a view instance without setting up a webtest instance for the app and
running requests.
Flask's ``request.args`` is normally immutable, but in test cases, it can be helpful to
patch in args without needing to construct the URL. But, we don't want to leave them
mutable, because potential app bugs could be masked in doing so. To modify args, pass
in a callable as ``args_modifier`` that takes the args dict to be modified in-place. Args
will only be mutable for executing the modifier, then returned to immutable for the
remainder of the scope.
Assumes that ``flask.current_app`` is pointing to the desired app.
Example::
@inrequest('/mypath?foo=bar&baz=boo')
def test_in_request_args(self):
assert flask.request.args['foo'] == 'bar'
def test_request_args_mutated(self):
def args_modifier(args_dict):
args_dict['baz'] = 'custom-value'
with inrequest('/mypath?foo=bar&baz=boo', args_modifier=args_modifier):
assert flask.request.args['foo'] == 'bar'
assert flask.request.args['baz'] == 'custom-value'
"""
with flask.current_app.test_request_context(*req_args, **req_kwargs):
if callable(args_modifier):
# Temporarily turn args into a mutable MultiDict to be patched. Then, we must
# be sure to turn them back immutable, or else tests may end up not catching
# bugs that attempt to modify request args improperly.
new_args = MultiDict(flask.request.args)
args_modifier(new_args)
flask.request.args = ImmutableMultiDict(new_args)
yield
def invoke_command(app_cls, *args, **kwargs):
"""Invoke a command using a CLI runner and return the result.
Optional kwargs:
- exit_code: Default 0. Process exit code to assert.
- runner: Default ``click.testing.CliRunner()``. CLI runner instance to use for invocation.
- use_test_profile: Default True. Drive invoked app to use test profile instead of default.
"""
exit_code = kwargs.pop('exit_code', 0)
runner = kwargs.pop('runner', None) or click.testing.CliRunner()
use_test_profile = kwargs.pop('use_test_profile', True)
env = kwargs.pop('env', {})
if use_test_profile:
app_key = app_cls.environ_key('USE_TEST_PROFILE')
env[app_key] = 'true'
result = runner.invoke(app_cls.cli, args, env=env, catch_exceptions=False, **kwargs)
error_message = 'Command exit code {}, expected {}. Result output follows:\n{}'
assert result.exit_code == exit_code, error_message.format(result.exit_code, exit_code,
result.output)
return result
def cleanup_app_contexts():
while flask.current_app:
cm = ContextManager.get_for(flask.current_app.__class__)
if cm.ctx:
cm.cleanup()
else:
break
# support older flask as well
if flask.current_app and getattr(flask, '_app_ctx_stack'):
while flask._app_ctx_stack.pop():
pass
class CLIBase(object):
"""Test class base for testing Keg click commands.
Creates a CLI runner instance, and allows subclass to call ``self.invoke`` with
command args.
Class attributes:
- app_cls: Optional, will default to ``flask.current_app`` class.
- cmd_name: Optional, provides default in ``self.invoke`` for ``cmd_name`` kwarg.
"""
# child classes will need to set these values in order to use the class
app_cls = None
cmd_name = None
@classmethod
def setup_class(cls):
# If a current app context is set, it may complicate what click is doing to
# set up and run a specific app.
cleanup_app_contexts()
cls.runner = click.testing.CliRunner()
def invoke(self, *args, **kwargs):
"""Run a command, perform some assertions, and return the result for testing."""
cmd_name = kwargs.pop('cmd_name', self.cmd_name)
if cmd_name is None:
cmd_name_args = []
else:
cmd_name_args = cmd_name.split(' ')
invoke_args = cmd_name_args + list(args)
kwargs['runner'] = self.runner
# If the app_cls isn't set, use the class of the current app
app_cls = self.app_cls or flask.current_app._get_current_object().__class__
return invoke_command(app_cls, *invoke_args, **kwargs)
class WebBase(object):
db = None
appcls = None
@classmethod
def setup_class(cls):
cls.app = cls.appcls.testing_prep()
cls.testapp = TestApp(flask.current_app)