/
test_app_extension.py
382 lines (309 loc) · 13.7 KB
/
test_app_extension.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
# -*- coding: utf-8 -*-
"""
test
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2016 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
import re
from ..base_test import FlaskCorsTestCase
from flask import Flask, jsonify
from flask_cors import *
from flask_cors.core import *
letters = 'abcdefghijklmnopqrstuvwxyz' # string.letters is not PY3 compatible
class AppExtensionRegexp(FlaskCorsTestCase):
def setUp(self):
self.app = Flask(__name__)
CORS(self.app, resources={
r'/test_list': {'origins': ["http://foo.com", "http://bar.com"]},
r'/test_string': {'origins': 'http://foo.com'},
r'/test_set': {
'origins': {"http://foo.com", "http://bar.com"}
},
r'/test_subdomain_regex': {
'origins': r"http?://\w*\.?example\.com:?\d*/?.*"
},
r'/test_regex_list': {
'origins': [r".*.example.com", r".*.otherexample.com"]
},
r'/test_regex_mixed_list': {
'origins': ["http://example.com", r".*.otherexample.com"]
},
r'/test_send_wildcard_with_origin' : {
'send_wildcard':True
},
re.compile('/test_compiled_subdomain_\w*'): {
'origins': re.compile("http://example\d+.com")
},
r'/test_defaults':{}
})
@self.app.route('/test_defaults')
def wildcard():
return 'Welcome!'
@self.app.route('/test_send_wildcard_with_origin')
def send_wildcard_with_origin():
return 'Welcome!'
@self.app.route('/test_list')
def test_list():
return 'Welcome!'
@self.app.route('/test_string')
def test_string():
return 'Welcome!'
@self.app.route('/test_set')
def test_set():
return 'Welcome!'
def test_defaults_no_origin(self):
''' If there is no Origin header in the request,
by default the '*' should be sent
'''
for resp in self.iter_responses('/test_defaults'):
self.assertEqual(resp.headers.get(ACL_ORIGIN), '*')
def test_defaults_with_origin(self):
''' If there is an Origin header in the request, the
Access-Control-Allow-Origin header should be included.
'''
for resp in self.iter_responses('/test_defaults', origin='http://example.com'):
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://example.com')
def test_send_wildcard_with_origin(self):
''' If there is an Origin header in the request, the
Access-Control-Allow-Origin header should be included.
'''
for resp in self.iter_responses('/test_send_wildcard_with_origin', origin='http://example.com'):
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.headers.get(ACL_ORIGIN), '*')
def test_list_serialized(self):
''' If there is an Origin header in the request, the
Access-Control-Allow-Origin header should be echoed.
'''
resp = self.get('/test_list', origin='http://bar.com')
self.assertEqual(resp.headers.get(ACL_ORIGIN),'http://bar.com')
def test_string_serialized(self):
''' If there is an Origin header in the request,
the Access-Control-Allow-Origin header should be echoed back.
'''
resp = self.get('/test_string', origin='http://foo.com')
self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://foo.com')
def test_set_serialized(self):
''' If there is an Origin header in the request,
the Access-Control-Allow-Origin header should be echoed back.
'''
resp = self.get('/test_set', origin='http://bar.com')
allowed = resp.headers.get(ACL_ORIGIN)
# Order is not guaranteed
self.assertEqual(allowed, 'http://bar.com')
def test_not_matching_origins(self):
for resp in self.iter_responses('/test_list',origin="http://bazz.com"):
self.assertFalse(ACL_ORIGIN in resp.headers)
def test_subdomain_regex(self):
for sub in letters:
domain = "http://%s.example.com" % sub
for resp in self.iter_responses('/test_subdomain_regex',
headers={'origin': domain}):
self.assertEqual(domain, resp.headers.get(ACL_ORIGIN))
def test_compiled_subdomain_regex(self):
for sub in [1, 100, 200]:
domain = "http://example%s.com" % sub
for resp in self.iter_responses('/test_compiled_subdomain_regex',
headers={'origin': domain}):
self.assertEqual(domain, resp.headers.get(ACL_ORIGIN))
for resp in self.iter_responses('/test_compiled_subdomain_regex',
headers={'origin': "http://examplea.com"}):
self.assertEqual(None, resp.headers.get(ACL_ORIGIN))
def test_regex_list(self):
for parent in 'example.com', 'otherexample.com':
for sub in letters:
domain = "http://{}.{}.com".format(sub, parent)
for resp in self.iter_responses('/test_regex_list',
headers={'origin': domain}):
self.assertEqual(domain, resp.headers.get(ACL_ORIGIN))
def test_regex_mixed_list(self):
'''
Tests the corner case occurs when the send_always setting is True
and no Origin header in the request, it is not possible to match
the regular expression(s) to determine the correct
Access-Control-Allow-Origin header to be returned. Instead, the
list of origins is serialized, and any strings which seem like
regular expressions (e.g. are not a '*' and contain either '*'
or '?') will be skipped.
Thus, the list of returned Access-Control-Allow-Origin header
is guaranteed to be 'null', the origin or "*", as per the w3
http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
'''
for sub in letters:
domain = "http://%s.otherexample.com" % sub
for resp in self.iter_responses('/test_regex_mixed_list',
origin=domain):
self.assertEqual(domain, resp.headers.get(ACL_ORIGIN))
self.assertEquals("http://example.com",
self.get('/test_regex_mixed_list', origin='http://example.com').headers.get(ACL_ORIGIN))
class AppExtensionList(FlaskCorsTestCase):
def setUp(self):
self.app = Flask(__name__)
CORS(self.app, resources=[r'/test_exposed', r'/test_other_exposed'],
origins=['http://foo.com', 'http://bar.com'])
@self.app.route('/test_unexposed')
def unexposed():
return 'Not exposed over CORS!'
@self.app.route('/test_exposed')
def exposed1():
return 'Welcome!'
@self.app.route('/test_other_exposed')
def exposed2():
return 'Welcome!'
def test_exposed(self):
for resp in self.iter_responses('/test_exposed', origin='http://foo.com'):
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.headers.get(ACL_ORIGIN),'http://foo.com')
def test_other_exposed(self):
for resp in self.iter_responses('/test_other_exposed', origin='http://bar.com'):
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://bar.com')
def test_unexposed(self):
for resp in self.iter_responses('/test_unexposed', origin='http://foo.com'):
self.assertEqual(resp.status_code, 200)
self.assertFalse(ACL_ORIGIN in resp.headers)
class AppExtensionString(FlaskCorsTestCase):
def setUp(self):
self.app = Flask(__name__)
CORS(self.app, resources=r'/api/*',
allow_headers='Content-Type',
expose_headers='X-Total-Count',
origins='http://bar.com')
@self.app.route('/api/v1/foo')
def exposed1():
return jsonify(success=True)
@self.app.route('/api/v1/bar')
def exposed2():
return jsonify(success=True)
@self.app.route('/api/v1/special')
@cross_origin(origins='http://foo.com')
def overridden():
return jsonify(special=True)
@self.app.route('/')
def index():
return 'Welcome'
@self.app.route('/foo.txt')
def foo_txt():
return 'Welcome'
def test_exposed(self):
for path in '/api/v1/foo', '/api/v1/bar':
for resp in self.iter_responses(path, origin='http://bar.com'):
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://bar.com')
self.assertEqual(resp.headers.get(ACL_EXPOSE_HEADERS),
'X-Total-Count')
for resp in self.iter_responses(path, origin='http://foo.com'):
self.assertEqual(resp.status_code, 200)
self.assertFalse(ACL_ORIGIN in resp.headers)
self.assertFalse(ACL_EXPOSE_HEADERS in resp.headers)
def test_unexposed(self):
for resp in self.iter_responses('/', origin='http://bar.com'):
self.assertEqual(resp.status_code, 200)
self.assertFalse(ACL_ORIGIN in resp.headers)
self.assertFalse(ACL_EXPOSE_HEADERS in resp.headers)
def test_override(self):
for resp in self.iter_responses('/api/v1/special', origin='http://foo.com'):
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://foo.com')
self.assertFalse(ACL_EXPOSE_HEADERS in resp.headers)
for resp in self.iter_responses('/api/v1/special', origin='http://bar.com'):
self.assertEqual(resp.status_code, 200)
self.assertFalse(ACL_ORIGIN in resp.headers)
self.assertFalse(ACL_EXPOSE_HEADERS in resp.headers)
class AppExtensionError(FlaskCorsTestCase):
def test_value_error(self):
try:
app = Flask(__name__)
CORS(app, resources=5)
self.assertTrue(False, "Should've raised a value error")
except ValueError:
pass
class AppExtensionDefault(FlaskCorsTestCase):
def test_default(self):
'''
By default match all.
'''
self.app = Flask(__name__)
CORS(self.app)
@self.app.route('/')
def index():
return 'Welcome'
for resp in self.iter_responses('/', origin='http://foo.com'):
self.assertEqual(resp.status_code, 200)
self.assertTrue(ACL_ORIGIN in resp.headers)
class AppExtensionExampleApp(FlaskCorsTestCase):
def setUp(self):
self.app = Flask(__name__)
CORS(self.app, resources={
r'/api/*': {'origins': ['http://blah.com', 'http://foo.bar']}
})
@self.app.route('/')
def index():
return ''
@self.app.route('/api/foo')
def test_wildcard():
return ''
@self.app.route('/api/')
def test_exact_match():
return ''
def test_index(self):
'''
If regex does not match, do not set CORS
'''
for resp in self.iter_responses('/', origin='http://foo.bar'):
self.assertFalse(ACL_ORIGIN in resp.headers)
def test_wildcard(self):
'''
Match anything matching the path /api/* with an origin
of 'http://blah.com' or 'http://foo.bar'
'''
for origin in ['http://foo.bar', 'http://blah.com']:
for resp in self.iter_responses('/api/foo', origin=origin):
self.assertTrue(ACL_ORIGIN in resp.headers)
self.assertEqual(origin, resp.headers.get(ACL_ORIGIN))
def test_exact_match(self):
'''
Match anything matching the path /api/* with an origin
of 'http://blah.com' or 'http://foo.bar'
'''
for origin in ['http://foo.bar', 'http://blah.com']:
for resp in self.iter_responses('/api/', origin=origin):
self.assertTrue(ACL_ORIGIN in resp.headers)
self.assertEqual(origin, resp.headers.get(ACL_ORIGIN))
class AppExtensionCompiledRegexp(FlaskCorsTestCase):
def test_compiled_regex(self):
'''
Ensure we do not error if the user sepcifies an bad regular
expression.
'''
import re
self.app = Flask(__name__)
CORS(self.app, resources=re.compile('/api/.*'))
@self.app.route('/')
def index():
return 'Welcome'
@self.app.route('/api/v1')
def example():
return 'Welcome'
for resp in self.iter_responses('/'):
self.assertFalse(ACL_ORIGIN in resp.headers)
for resp in self.iter_responses('/api/v1', origin='http://foo.com'):
self.assertTrue(ACL_ORIGIN in resp.headers)
class AppExtensionBadRegexp(FlaskCorsTestCase):
def test_value_error(self):
'''
Ensure we do not error if the user sepcifies an bad regular
expression.
'''
self.app = Flask(__name__)
CORS(self.app, resources="}")
@self.app.route('/')
def index():
return 'Welcome'
for resp in self.iter_responses('/'):
self.assertEqual(resp.status_code, 200)
if __name__ == "__main__":
unittest.main()