-
Notifications
You must be signed in to change notification settings - Fork 43
/
flask_injector_tests.py
412 lines (295 loc) · 10.7 KB
/
flask_injector_tests.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
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
import gc
import json
import warnings
from functools import partial
import flask_restful
import flask_restplus
from eventlet import greenthread
from injector import __version__ as injector_version, CallableProvider, inject, Scope
from flask import Blueprint, Flask
from flask.templating import render_template_string
from flask.views import View
from nose.tools import eq_
from flask_injector import request, FlaskInjector
def test_injections():
l = [1, 2, 3]
counter = [0]
def inc():
counter[0] += 1
def conf(binder):
binder.bind(str, to="something")
binder.bind(list, to=l)
app = Flask(__name__)
@app.route('/view1')
def view1(content: str):
inc()
return render_template_string(content)
class View2(View):
@inject
def __init__(self, *args, content: list, **kwargs):
self.content = content
super().__init__(*args, **kwargs)
def dispatch_request(self):
inc()
return render_template_string('%s' % self.content)
@app.before_request
def br(c: list):
inc()
eq_(c, l)
@app.before_first_request
def bfr(c: list):
inc()
eq_(c, l)
@app.after_request
def ar(response_class, c: list):
inc()
eq_(c, l)
return response_class
@app.context_processor
def cp(c: list):
inc()
eq_(c, l)
return {}
@app.teardown_request
def tr(sender, exc=None, c: list = None):
inc()
eq_(c, l)
app.add_url_rule('/view2', view_func=View2.as_view('view2'))
FlaskInjector(app=app, modules=[conf])
with app.test_client() as c:
response = c.get('/view1')
eq_(response.get_data(as_text=True), "something")
with app.test_client() as c:
response = c.get('/view2')
eq_(response.get_data(as_text=True), '%s' % (l,))
eq_(counter[0], 11)
def test_resets():
app = Flask(__name__)
counter = [0]
class OurScope(Scope):
def __init__(self, injector):
pass
def prepare(self):
pass
def cleanup(self):
counter[0] += 1
@app.route('/')
def index():
return 'asd'
FlaskInjector(app, request_scope_class=OurScope)
eq_(counter[0], 0)
with app.test_client() as c:
c.get('/')
eq_(counter[0], 1)
def test_memory_leak():
# The RequestScope holds references to GreenThread objects which would
# cause memory leak
# More explanation below
#
# In Werkzeug locals are indexed using values returned by ``get_ident`` function:
#
# try:
# from greenlet import getcurrent as get_ident
# except ImportError:
# try:
# from thread import get_ident
# except ImportError:
# from _thread import get_ident
#
# This is what LocalManager.cleanup runs indirectly (__ident_func__
# points to get_ident unless it's overridden):
#
# self.__storage__.pop(self.__ident_func__(), None)
# If something's assigned in local storage *after* the cleanup is done an entry
# in internal storage under "the return value of get_ident()" key is recreated
# and a reference to the key will be kept forever.
#
# This is not strictly related to Eventlet/GreenThreads but that's how
# the issue manifested itself so the test reflects that.
app = Flask(__name__)
FlaskInjector(app)
@app.route('/')
def index():
return 'test'
def get_request():
with app.test_client() as c:
c.get('/')
green_thread = greenthread.spawn(get_request)
green_thread.wait()
# Delete green_thread so the GreenThread object is dereferenced
del green_thread
# Force run garbage collect to make sure GreenThread object is collected if
# there is no memory leak
gc.collect()
greenthread_count = len([obj for obj in gc.get_objects() if type(obj) is greenthread.GreenThread])
eq_(greenthread_count, 0)
def test_doesnt_raise_deprecation_warning():
app = Flask(__name__)
def provide_str():
return 'this is string'
def configure(binder):
binder.bind(str, to=CallableProvider(provide_str), scope=request)
@app.route('/')
def index(s: str):
return s
FlaskInjector(app=app, modules=[configure])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
with app.test_client() as c:
c.get('/')
eq_(len(w), 0, map(str, w))
def test_jinja_env_globals_support_injection():
app = Flask(__name__)
def configure(binder):
binder.bind(str, to='xyz')
def do_something_helper(s: str):
return s
app.jinja_env.globals['do_something'] = do_something_helper
@app.route('/')
def index():
return render_template_string('{{ do_something() }}')
FlaskInjector(app=app, modules=[configure])
with app.test_client() as c:
eq_(c.get('/').get_data(as_text=True), 'xyz')
def test_error_handlers_support_injection():
app = Flask(__name__)
class CustomException(Exception):
pass
@app.route('/custom-exception')
def custom_exception():
raise CustomException()
@app.errorhandler(404)
def handle_404(error, s: str):
return s, 404
@app.errorhandler(CustomException)
def handle_custom_exception(error, s: str):
return s, 500
def configure(binder):
binder.bind(str, to='injected content')
FlaskInjector(app=app, modules=[configure])
with app.test_client() as c:
response = c.get('/this-page-does-not-exist')
eq_((response.status_code, response.get_data(as_text=True)), (404, 'injected content'))
response = c.get('/custom-exception')
eq_((response.status_code, response.get_data(as_text=True)), (500, 'injected content'))
def test_view_functions_arent_modified_globally():
# Connected to GH #6 "Doing multiple requests on a flask test client on an injected route
# fails for all but the first request"
# The code would modify view functions generated by View.as_view(), it wasn't an issue with
# views added directly to an application but if function was added to a blueprint and
# that blueprint was used in multiple applications it'd raise an error
class MyView(View):
pass
blueprint = Blueprint('test', __name__)
blueprint.add_url_rule('/', view_func=MyView.as_view('view'))
app = Flask(__name__)
app.register_blueprint(blueprint)
FlaskInjector(app=app)
app2 = Flask(__name__)
app2.register_blueprint(blueprint)
# it'd fail here
FlaskInjector(app=app2)
def test_view_args_and_class_args_are_passed_to_class_based_views():
class MyView(View):
def __init__(self, class_arg):
self.class_arg = class_arg
def dispatch_request(self, dispatch_arg):
return '%s %s' % (self.class_arg, dispatch_arg)
app = Flask(__name__)
app.add_url_rule('/<dispatch_arg>', view_func=MyView.as_view('view', class_arg='aaa'))
FlaskInjector(app=app)
client = app.test_client()
response = client.get('/bbb')
print(response.data)
eq_(response.data, b'aaa bbb')
def test_flask_restful_integration_works():
class HelloWorld(flask_restful.Resource):
@inject
def __init__(self, *args, int: int, **kwargs):
self._int = int
super().__init__(*args, **kwargs)
def get(self):
return {'int': self._int}
app = Flask(__name__)
api = flask_restful.Api(app)
api.add_resource(HelloWorld, '/')
FlaskInjector(app=app)
client = app.test_client()
response = client.get('/')
data = json.loads(response.data.decode('utf-8'))
eq_(data, {'int': 0})
def test_flask_restplus_integration_works():
class HelloWorld(flask_restplus.Resource):
@inject
def __init__(self, *args, int: int, **kwargs):
self._int = int
super().__init__(*args, **kwargs)
def get(self):
return {'int': self._int}
app = Flask(__name__)
api = flask_restplus.Api(app)
api.add_resource(HelloWorld, '/hello')
FlaskInjector(app=app)
client = app.test_client()
response = client.get('/hello')
data = json.loads(response.data.decode('utf-8'))
eq_(data, {'int': 0})
def test_request_scope_not_started_before_any_request_made_regression():
# Version 0.6.1 (patch cacaef6 specifially) broke backwards compatibility in
# a relatively subtle way. The code used to support RequestScope even in
# the thread that originally created the Injector object. After cacaef6 an
# "AttributeError: scope" exception would be raised.
#
# For compatibility reason I'll restore the old behaviour, we can
# deprecate it later if needed
def configure(binder):
binder.bind(str, to='this is string', scope=request)
app = Flask(__name__)
flask_injector = FlaskInjector(app=app, modules=[configure])
eq_(flask_injector.injector.get(str), 'this is string')
def test_noninstrospectable_hooks_dont_crash_everything():
app = Flask(__name__)
def do_nothing():
pass
app.before_request(partial(do_nothing))
# It'd crash here
FlaskInjector(app=app)
def test_instance_methods():
class HelloWorldService:
def get_value(self):
return "test message 1"
class HelloWorld:
def from_injected_service(self, service: HelloWorldService):
return service.get_value()
def static_value(self):
return "test message 2"
app = Flask(__name__)
hello_world = HelloWorld()
app.add_url_rule('/from_injected_service', 'from_injected_service', hello_world.from_injected_service)
app.add_url_rule('/static_value', 'static_value', hello_world.static_value)
FlaskInjector(app=app)
client = app.test_client()
response = client.get('/from_injected_service')
eq_(response.data.decode('utf-8'), "test message 1")
response = client.get('/static_value')
eq_(response.data.decode('utf-8'), "test message 2")
if injector_version >= '0.12':
def test_forward_references_work():
app = Flask(__name__)
@app.route('/')
def index(x: 'X'):
return x.message
FlaskInjector(app=app)
# The class needs to be module-global in order for the string -> object
# resolution mechanism to work. I could make it work with locals but it
# doesn't seem worth it.
global X
class X:
def __init__(self) -> None:
self.message = 'Hello World'
try:
client = app.test_client()
response = client.get('/')
eq_(response.data.decode(), 'Hello World')
finally:
del X