forked from smarkets/flask_injector
/
flask_injector_tests.py
283 lines (200 loc) · 6.58 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
import gc
import json
import warnings
import flask_restful
from eventlet import greenthread
from injector import CallableProvider, inject
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')
@inject(content=str)
def view1(content):
inc()
return render_template_string(content)
@inject(content=list)
class View2(View):
def dispatch_request(self):
inc()
return render_template_string('%s' % self.content)
@app.before_request
@inject(c=list)
def br(c):
inc()
eq_(c, l)
@app.after_request
@inject(c=list)
def ar(response_class, c):
inc()
eq_(c, l)
return response_class
@app.context_processor
@inject(c=list)
def cp(c):
inc()
eq_(c, l)
return {}
@app.teardown_request
@inject(c=list)
def tr(sender, exc=None, c=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], 10)
def test_resets():
app = Flask(__name__)
counter = [0]
class Scope(object):
def __init__(self, injector):
pass
def prepare(self):
pass
def cleanup(self):
counter[0] += 1
@app.route('/')
def index():
eq_(counter[0], 1)
return 'asd'
FlaskInjector(app, request_scope_class=Scope)
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
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('/')
@inject(s=str)
def index(s):
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')
@inject(s=str)
def do_something_helper(s):
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)
@inject(s=str)
def handle_404(error, s):
return s, 404
@app.errorhandler(CustomException)
@inject(s=str)
def handle_custom_exception(error, s):
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():
@inject(_int=int)
class HelloWorld(flask_restful.Resource):
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})