Skip to content
Myr

Rewrite assertion methods

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Markus Unterwaditzer · committed by Markus Unterwaditzer · parent dd6b257 · Browse files · 14 files+694 added−719 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+694 added−719 removed

  • tests:+694 added−719 removed

14 files+694 added−719 removed

modified:tests/__init__.py+3 added-31 removed
76 unmodified lines
77def emits_module_deprecation_warning(f):78 def new_f(self, *args, **kwargs):79 with catch_warnings() as log:80 f(self, *args, **kwargs)81 self.assert_true(log, 'expected deprecation warning')81 assert log, 'expected deprecation warning'82 for entry in log:83 self.assert_in('Modules are deprecated', str(entry['message']))83 assert 'Modules are deprecated' in str(entry['message'])84 return update_wrapper(new_f, f)858687class TestFlask(object):
18 unmodified lines
106 # testing flask internally in debug mode in a few cases107 leaks = []108 while flask._request_ctx_stack.top is not None:109 leaks.append(flask._request_ctx_stack.pop())110 self.assert_equal(leaks, [])110 assert leaks == []111112 def setup_method(self, method):113 self.setup()114
4 unmodified lines
119 pass120121 def teardown(self):122 pass123124 def assert_equal(self, x, y):125 assert x == y126127 def assert_raises(self, exc_type, callable=None, *args, **kwargs):128 if callable:129 return pytest.raises(exc_type, callable, *args, **kwargs)130 else:131 return pytest.raises(exc_type)132133 def assert_true(self, x, msg=None):134 assert x135 assert_ = assert_true136137 def assert_false(self, x, msg=None):138 assert not x139140 def assert_in(self, x, y):141 assert x in y142143 def assert_not_in(self, x, y):144 assert x not in y145146 def assert_isinstance(self, obj, cls):147 assert isinstance(obj, cls)148149 def fail(self, msg):150 raise AssertionError(msg)
modified:tests/test_appctx.py+18 added-15 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import unittest16from tests import TestFlask17
10 unmodified lines
28 pass2930 with app.app_context():31 rv = flask.url_for('index')30 self.assert_equal(rv, 'https://localhost/')32 assert rv == 'https://localhost/'3334 def test_url_generation_requires_server_name(self):35 app = flask.Flask(__name__)36 with app.app_context():35 with self.assert_raises(RuntimeError):37 with pytest.raises(RuntimeError):38 flask.url_for('index')3940 def test_url_generation_without_context_fails(self):39 with self.assert_raises(RuntimeError):41 with pytest.raises(RuntimeError):42 flask.url_for('index')4344 def test_request_context_means_app_context(self):45 app = flask.Flask(__name__)46 with app.test_request_context():45 self.assert_equal(flask.current_app._get_current_object(), app)46 self.assert_equal(flask._app_ctx_stack.top, None)47 assert flask.current_app._get_current_object() == app48 assert flask._app_ctx_stack.top == None4950 def test_app_context_provides_current_app(self):51 app = flask.Flask(__name__)52 with app.app_context():51 self.assert_equal(flask.current_app._get_current_object(), app)52 self.assert_equal(flask._app_ctx_stack.top, None)53 assert flask.current_app._get_current_object() == app54 assert flask._app_ctx_stack.top == None5556 def test_app_tearing_down(self):57 cleanup_stuff = []58 app = flask.Flask(__name__)
3 unmodified lines
6263 with app.app_context():64 pass6564 self.assert_equal(cleanup_stuff, [None])66 assert cleanup_stuff == [None]6768 def test_app_tearing_down_with_previous_exception(self):69 cleanup_stuff = []70 app = flask.Flask(__name__)
8 unmodified lines
7980 with app.app_context():81 pass8281 self.assert_equal(cleanup_stuff, [None])83 assert cleanup_stuff == [None]8485 def test_custom_app_ctx_globals_class(self):86 class CustomRequestGlobals(object):87 def __init__(self):88 self.spam = 'eggs'89 app = flask.Flask(__name__)90 app.app_ctx_globals_class = CustomRequestGlobals91 with app.app_context():90 self.assert_equal(91 flask.render_template_string('{{ g.spam }}'), 'eggs')92 assert flask.render_template_string('{{ g.spam }}') == 'eggs'9394 def test_context_refcounts(self):95 called = []96 app = flask.Flask(__name__)
7 unmodified lines
104 def index():105 with flask._app_ctx_stack.top:106 with flask._request_ctx_stack.top:107 pass107 self.assert_true(flask._request_ctx_stack.top.request.environ108 ['werkzeug.request'] is not None)108 env = flask._request_ctx_stack.top.request.environ109 assert env['werkzeug.request'] is not None110 return u''111 c = app.test_client()111 c.get('/')112 self.assert_equal(called, ['request', 'app'])112 res = c.get('/')113 assert res.status_code == 200114 assert res.data == u''115 assert called == ['request', 'app']116117118def suite():119 suite = unittest.TestSuite()
2 unmodified lines
modified:tests/test_basic.py+257 added-248 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import re15import uuid16import time17import flask
15 unmodified lines
33 @app.route('/', methods=['GET', 'POST'])34 def index():35 return 'Hello World'36 rv = app.test_client().open('/', method='OPTIONS')35 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])36 self.assert_equal(rv.data, b'')37 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']38 assert rv.data == b''3940 def test_options_on_multiple_rules(self):41 app = flask.Flask(__name__)42 @app.route('/', methods=['GET', 'POST'])
2 unmodified lines
45 @app.route('/', methods=['PUT'])46 def index_put():47 return 'Aha!'48 rv = app.test_client().open('/', method='OPTIONS')47 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'])49 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']5051 def test_options_handling_disabled(self):52 app = flask.Flask(__name__)53 def index():54 return 'Hello World!'55 index.provide_automatic_options = False56 app.route('/')(index)57 rv = app.test_client().open('/', method='OPTIONS')56 self.assert_equal(rv.status_code, 405)58 assert rv.status_code == 4055960 app = flask.Flask(__name__)61 def index2():62 return 'Hello World!'63 index2.provide_automatic_options = True64 app.route('/', methods=['OPTIONS'])(index2)65 rv = app.test_client().open('/', method='OPTIONS')64 self.assert_equal(sorted(rv.allow), ['OPTIONS'])66 assert sorted(rv.allow) == ['OPTIONS']6768 def test_request_dispatching(self):69 app = flask.Flask(__name__)70 @app.route('/')
3 unmodified lines
74 def more():75 return flask.request.method7677 c = app.test_client()76 self.assert_equal(c.get('/').data, b'GET')78 assert c.get('/').data == b'GET'79 rv = c.post('/')78 self.assert_equal(rv.status_code, 405)79 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])80 assert rv.status_code == 40581 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']82 rv = c.head('/')81 self.assert_equal(rv.status_code, 200)82 self.assert_false(rv.data) # head truncates83 self.assert_equal(c.post('/more').data, b'POST')84 self.assert_equal(c.get('/more').data, b'GET')83 assert rv.status_code == 20084 assert not rv.data # head truncates85 assert c.post('/more').data == b'POST'86 assert c.get('/more').data == b'GET'87 rv = c.delete('/more')86 self.assert_equal(rv.status_code, 405)87 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])88 assert rv.status_code == 40589 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']9091 def test_disallow_string_for_allowed_methods(self):92 app = flask.Flask(__name__)91 with self.assert_raises(TypeError):93 with pytest.raises(TypeError):94 @app.route('/', methods='GET POST')95 def index():96 return "Hey"97
7 unmodified lines
105 app.add_url_rule('/', 'index', index)106 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])107108 c = app.test_client()107 self.assert_equal(c.get('/').data, b'GET')109 assert c.get('/').data == b'GET'110 rv = c.post('/')109 self.assert_equal(rv.status_code, 405)110 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])111 assert rv.status_code == 405112 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']113 rv = c.head('/')112 self.assert_equal(rv.status_code, 200)113 self.assert_false(rv.data) # head truncates114 self.assert_equal(c.post('/more').data, b'POST')115 self.assert_equal(c.get('/more').data, b'GET')114 assert rv.status_code == 200115 assert not rv.data # head truncates116 assert c.post('/more').data == b'POST'117 assert c.get('/more').data == b'GET'118 rv = c.delete('/more')117 self.assert_equal(rv.status_code, 405)118 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])119 assert rv.status_code == 405120 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']121122 def test_werkzeug_routing(self):123 from werkzeug.routing import Submount, Rule124 app = flask.Flask(__name__)
8 unmodified lines
133 app.view_functions['bar'] = bar134 app.view_functions['index'] = index135136 c = app.test_client()135 self.assert_equal(c.get('/foo/').data, b'index')136 self.assert_equal(c.get('/foo/bar').data, b'bar')137 assert c.get('/foo/').data == b'index'138 assert c.get('/foo/bar').data == b'bar'139140 def test_endpoint_decorator(self):141 from werkzeug.routing import Submount, Rule142 app = flask.Flask(__name__)
10 unmodified lines
153 def index():154 return 'index'155156 c = app.test_client()155 self.assert_equal(c.get('/foo/').data, b'index')156 self.assert_equal(c.get('/foo/bar').data, b'bar')157 assert c.get('/foo/').data == b'index'158 assert c.get('/foo/bar').data == b'bar'159160 def test_session(self):161 app = flask.Flask(__name__)162 app.secret_key = 'testkey'
5 unmodified lines
168 def get():169 return flask.session['value']170171 c = app.test_client()170 self.assert_equal(c.post('/set', data={'value': '42'}).data, b'value set')171 self.assert_equal(c.get('/get').data, b'42')172 assert c.post('/set', data={'value': '42'}).data == b'value set'173 assert c.get('/get').data == b'42'174175 def test_session_using_server_name(self):176 app = flask.Flask(__name__)177 app.config.update(
4 unmodified lines
182 def index():183 flask.session['testing'] = 42184 return 'Hello World'185 rv = app.test_client().get('/', 'http://example.com/')184 self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower())185 self.assert_in('httponly', rv.headers['set-cookie'].lower())186 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()187 assert 'httponly' in rv.headers['set-cookie'].lower()188189 def test_session_using_server_name_and_port(self):190 app = flask.Flask(__name__)191 app.config.update(
4 unmodified lines
196 def index():197 flask.session['testing'] = 42198 return 'Hello World'199 rv = app.test_client().get('/', 'http://example.com:8080/')198 self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower())199 self.assert_in('httponly', rv.headers['set-cookie'].lower())200 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()201 assert 'httponly' in rv.headers['set-cookie'].lower()202203 def test_session_using_server_name_port_and_path(self):204 app = flask.Flask(__name__)205 app.config.update(
5 unmodified lines
211 def index():212 flask.session['testing'] = 42213 return 'Hello World'214 rv = app.test_client().get('/', 'http://example.com:8080/foo')213 self.assert_in('domain=example.com', rv.headers['set-cookie'].lower())214 self.assert_in('path=/foo', rv.headers['set-cookie'].lower())215 self.assert_in('httponly', rv.headers['set-cookie'].lower())215 assert 'domain=example.com' in rv.headers['set-cookie'].lower()216 assert 'path=/foo' in rv.headers['set-cookie'].lower()217 assert 'httponly' in rv.headers['set-cookie'].lower()218219 def test_session_using_application_root(self):220 class PrefixPathMiddleware(object):221 def __init__(self, app, prefix):
13 unmodified lines
235 def index():236 flask.session['testing'] = 42237 return 'Hello World'238 rv = app.test_client().get('/', 'http://example.com:8080/')237 self.assert_in('path=/bar', rv.headers['set-cookie'].lower())239 assert 'path=/bar' in rv.headers['set-cookie'].lower()240241 def test_session_using_session_settings(self):242 app = flask.Flask(__name__)243 app.config.update(
10 unmodified lines
254 flask.session['testing'] = 42255 return 'Hello World'256 rv = app.test_client().get('/', 'http://www.example.com:8080/test/')257 cookie = rv.headers['set-cookie'].lower()256 self.assert_in('domain=.example.com', cookie)257 self.assert_in('path=/', cookie)258 self.assert_in('secure', cookie)259 self.assert_not_in('httponly', cookie)258 assert 'domain=.example.com' in cookie259 assert 'path=/' in cookie260 assert 'secure' in cookie261 assert 'httponly' not in cookie262263 def test_missing_session(self):264 app = flask.Flask(__name__)265 def expect_exception(f, *args, **kwargs):266 try:267 f(*args, **kwargs)268 except RuntimeError as e:267 self.assert_true(e.args and 'session is unavailable' in e.args[0])269 assert e.args and 'session is unavailable' in e.args[0]270 else:269 self.assert_true(False, 'expected exception')271 assert False, 'expected exception'272 with app.test_request_context():271 self.assert_true(flask.session.get('missing_key') is None)273 assert flask.session.get('missing_key') is None274 expect_exception(flask.session.__setitem__, 'foo', 42)275 expect_exception(flask.session.pop, 'foo')276277 def test_session_expiration(self):
11 unmodified lines
289 return text_type(flask.session.permanent)290291 client = app.test_client()292 rv = client.get('/')291 self.assert_in('set-cookie', rv.headers)293 assert 'set-cookie' in rv.headers294 match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])295 expires = parse_date(match.group())296 expected = datetime.utcnow() + app.permanent_session_lifetime295 self.assert_equal(expires.year, expected.year)296 self.assert_equal(expires.month, expected.month)297 self.assert_equal(expires.day, expected.day)297 assert expires.year == expected.year298 assert expires.month == expected.month299 assert expires.day == expected.day300301 rv = client.get('/test')300 self.assert_equal(rv.data, b'True')302 assert rv.data == b'True'303304 permanent = False305 rv = app.test_client().get('/')304 self.assert_in('set-cookie', rv.headers)306 assert 'set-cookie' in rv.headers307 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])306 self.assert_true(match is None)308 assert match is None309310 def test_session_stored_last(self):311 app = flask.Flask(__name__)312 app.secret_key = 'development-key'
7 unmodified lines
320 def dump_session_contents():321 return repr(flask.session.get('foo'))322323 c = app.test_client()322 self.assert_equal(c.get('/').data, b'None')323 self.assert_equal(c.get('/').data, b'42')324 assert c.get('/').data == b'None'325 assert c.get('/').data == b'42'326327 def test_session_special_types(self):328 app = flask.Flask(__name__)329 app.secret_key = 'development-key'
16 unmodified lines
346347 c = app.test_client()348 c.get('/')349 rv = pickle.loads(c.get('/').data)348 self.assert_equal(rv['m'], flask.Markup('Hello!'))349 self.assert_equal(type(rv['m']), flask.Markup)350 self.assert_equal(rv['dt'], now)351 self.assert_equal(rv['u'], the_uuid)352 self.assert_equal(rv['b'], b'\xff')353 self.assert_equal(type(rv['b']), bytes)354 self.assert_equal(rv['t'], (1, 2, 3))350 assert rv['m'] == flask.Markup('Hello!')351 assert type(rv['m']) == flask.Markup352 assert rv['dt'] == now353 assert rv['u'] == the_uuid354 assert rv['b'] == b'\xff'355 assert type(rv['b']) == bytes356 assert rv['t'] == (1, 2, 3)357358 def test_session_cookie_setting(self):359 app = flask.Flask(__name__)360 app.testing = True
11 unmodified lines
372 return str(flask.session.get('foo', 0))373374 def run_test(expect_header):375 with app.test_client() as c:374 self.assert_equal(c.get('/bump').data, b'1')375 self.assert_equal(c.get('/bump').data, b'2')376 self.assert_equal(c.get('/bump').data, b'3')376 assert c.get('/bump').data == b'1'377 assert c.get('/bump').data == b'2'378 assert c.get('/bump').data == b'3'379380 rv = c.get('/read')381 set_cookie = rv.headers.get('set-cookie')380 self.assert_equal(set_cookie is not None, expect_header)381 self.assert_equal(rv.data, b'3')382 assert (set_cookie is not None) == expect_header383 assert rv.data == b'3'384385 is_permanent = True386 app.config['SESSION_REFRESH_EACH_REQUEST'] = True387 run_test(expect_header=True)
14 unmodified lines
402 app = flask.Flask(__name__)403 app.secret_key = 'testkey'404405 with app.test_request_context():404 self.assert_false(flask.session.modified)406 assert not flask.session.modified407 flask.flash('Zap')408 flask.session.modified = False409 flask.flash('Zip')408 self.assert_true(flask.session.modified)409 self.assert_equal(list(flask.get_flashed_messages()), ['Zap', 'Zip'])410 assert flask.session.modified411 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']412413 def test_extended_flashing(self):414 # Be sure app.testing=True below, else tests can fail silently.415 #
14 unmodified lines
430431 @app.route('/test/')432 def test():433 messages = flask.get_flashed_messages()432 self.assert_equal(len(messages), 3)433 self.assert_equal(messages[0], u'Hello World')434 self.assert_equal(messages[1], u'Hello World')435 self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>'))434 assert list(messages) == [435 u'Hello World',436 u'Hello World',437 flask.Markup(u'<em>Testing</em>')438 ]439 return ''440441 @app.route('/test_with_categories/')442 def test_with_categories():443 messages = flask.get_flashed_messages(with_categories=True)441 self.assert_equal(len(messages), 3)442 self.assert_equal(messages[0], ('message', u'Hello World'))443 self.assert_equal(messages[1], ('error', u'Hello World'))444 self.assert_equal(messages[2], ('warning', flask.Markup(u'<em>Testing</em>')))444 assert len(messages) == 3445 assert list(messages) == [446 ('message', u'Hello World'),447 ('error', u'Hello World'),448 ('warning', flask.Markup(u'<em>Testing</em>'))449 ]450 return ''451452 @app.route('/test_filter/')453 def test_filter():454 messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True)450 self.assert_equal(len(messages), 1)451 self.assert_equal(messages[0], ('message', u'Hello World'))455 assert list(messages) == [('message', u'Hello World')]456 return ''457458 @app.route('/test_filters/')459 def test_filters():460 messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True)457 self.assert_equal(len(messages), 2)458 self.assert_equal(messages[0], ('message', u'Hello World'))459 self.assert_equal(messages[1], ('warning', flask.Markup(u'<em>Testing</em>')))461 assert list(messages) == [462 ('message', u'Hello World'),463 ('warning', flask.Markup(u'<em>Testing</em>'))464 ]465 return ''466467 @app.route('/test_filters_without_returning_categories/')468 def test_filters2():469 messages = flask.get_flashed_messages(category_filter=['message', 'warning'])465 self.assert_equal(len(messages), 2)466 self.assert_equal(messages[0], u'Hello World')467 self.assert_equal(messages[1], flask.Markup(u'<em>Testing</em>'))470 assert len(messages) == 2471 assert messages[0] == u'Hello World'472 assert messages[1] == flask.Markup(u'<em>Testing</em>')473 return ''474475 # Create new test client on each test to clean flashed messages.476
29 unmodified lines
506 evts.append('after')507 return response508 @app.route('/')509 def index():505 self.assert_in('before', evts)506 self.assert_not_in('after', evts)510 assert 'before' in evts511 assert 'after' not in evts512 return 'request'508 self.assert_not_in('after', evts)513 assert 'after' not in evts514 rv = app.test_client().get('/').data510 self.assert_in('after', evts)511 self.assert_equal(rv, b'request|after')515 assert 'after' in evts516 assert rv == b'request|after'517518 def test_after_request_processing(self):519 app = flask.Flask(__name__)520 app.testing = True
5 unmodified lines
526 return response527 return 'Test'528 c = app.test_client()529 resp = c.get('/')525 self.assert_equal(resp.status_code, 200)526 self.assert_equal(resp.headers['X-Foo'], 'a header')530 assert resp.status_code == 200531 assert resp.headers['X-Foo'] == 'a header'532533 def test_teardown_request_handler(self):534 called = []535 app = flask.Flask(__name__)
4 unmodified lines
540 @app.route('/')541 def root():542 return "Response"543 rv = app.test_client().get('/')539 self.assert_equal(rv.status_code, 200)540 self.assert_in(b'Response', rv.data)541 self.assert_equal(len(called), 1)544 assert rv.status_code == 200545 assert b'Response' in rv.data546 assert len(called) == 1547548 def test_teardown_request_handler_debug_mode(self):549 called = []550 app = flask.Flask(__name__)
5 unmodified lines
556 @app.route('/')557 def root():558 return "Response"559 rv = app.test_client().get('/')555 self.assert_equal(rv.status_code, 200)556 self.assert_in(b'Response', rv.data)557 self.assert_equal(len(called), 1)560 assert rv.status_code == 200561 assert b'Response' in rv.data562 assert len(called) == 1563564 def test_teardown_request_handler_error(self):565 called = []566 app = flask.Flask(__name__)567 app.config['LOGGER_HANDLER_POLICY'] = 'never'568 @app.teardown_request569 def teardown_request1(exc):565 self.assert_equal(type(exc), ZeroDivisionError)570 assert type(exc) == ZeroDivisionError571 called.append(True)572 # This raises a new error and blows away sys.exc_info(), so we can573 # test that all teardown_requests get passed the same original574 # exception.
2 unmodified lines
577 except:578 pass579 @app.teardown_request580 def teardown_request2(exc):576 self.assert_equal(type(exc), ZeroDivisionError)581 assert type(exc) == ZeroDivisionError582 called.append(True)583 # This raises a new error and blows away sys.exc_info(), so we can584 # test that all teardown_requests get passed the same original585 # exception.
4 unmodified lines
590 @app.route('/')591 def fails():592 1 // 0593 rv = app.test_client().get('/')589 self.assert_equal(rv.status_code, 500)590 self.assert_in(b'Internal Server Error', rv.data)591 self.assert_equal(len(called), 2)594 assert rv.status_code == 500595 assert b'Internal Server Error' in rv.data596 assert len(called) == 2597598 def test_before_after_request_order(self):599 called = []600 app = flask.Flask(__name__)
20 unmodified lines
621 @app.route('/')622 def index():623 return '42'624 rv = app.test_client().get('/')620 self.assert_equal(rv.data, b'42')621 self.assert_equal(called, [1, 2, 3, 4, 5, 6])625 assert rv.data == b'42'626 assert called == [1, 2, 3, 4, 5, 6]627628 def test_error_handling(self):629 app = flask.Flask(__name__)630 app.config['LOGGER_HANDLER_POLICY'] = 'never'
16 unmodified lines
647 def error2():648 flask.abort(403)649 c = app.test_client()650 rv = c.get('/')646 self.assert_equal(rv.status_code, 404)647 self.assert_equal(rv.data, b'not found')651 assert rv.status_code == 404652 assert rv.data == b'not found'653 rv = c.get('/error')649 self.assert_equal(rv.status_code, 500)650 self.assert_equal(b'internal server error', rv.data)654 assert rv.status_code == 500655 assert b'internal server error' == rv.data656 rv = c.get('/forbidden')652 self.assert_equal(rv.status_code, 403)653 self.assert_equal(b'forbidden', rv.data)657 assert rv.status_code == 403658 assert b'forbidden' == rv.data659660 def test_before_request_and_routing_errors(self):661 app = flask.Flask(__name__)662 @app.before_request
2 unmodified lines
665 @app.errorhandler(404)666 def return_something(error):667 return flask.g.something, 404668 rv = app.test_client().get('/')664 self.assert_equal(rv.status_code, 404)665 self.assert_equal(rv.data, b'value')669 assert rv.status_code == 404670 assert rv.data == b'value'671672 def test_user_error_handling(self):673 class MyException(Exception):674 pass675676 app = flask.Flask(__name__)677 @app.errorhandler(MyException)678 def handle_my_exception(e):674 self.assert_true(isinstance(e, MyException))679 assert isinstance(e, MyException)680 return '42'681 @app.route('/')682 def index():683 raise MyException()684685 c = app.test_client()681 self.assert_equal(c.get('/').data, b'42')686 assert c.get('/').data == b'42'687688 def test_http_error_subclass_handling(self):689 class ForbiddenSubclass(Forbidden):690 pass691692 app = flask.Flask(__name__)693 @app.errorhandler(ForbiddenSubclass)694 def handle_forbidden_subclass(e):690 self.assert_true(isinstance(e, ForbiddenSubclass))695 assert isinstance(e, ForbiddenSubclass)696 return 'banana'697 @app.errorhandler(403)698 def handle_forbidden_subclass(e):694 self.assert_false(isinstance(e, ForbiddenSubclass))695 self.assert_true(isinstance(e, Forbidden))699 assert not isinstance(e, ForbiddenSubclass)700 assert isinstance(e, Forbidden)701 return 'apple'702703 @app.route('/1')704 def index1():
5 unmodified lines
710 def index3():711 raise Forbidden()712713 c = app.test_client()709 self.assert_equal(c.get('/1').data, b'banana')710 self.assert_equal(c.get('/2').data, b'apple')711 self.assert_equal(c.get('/3').data, b'apple')714 assert c.get('/1').data == b'banana'715 assert c.get('/2').data == b'apple'716 assert c.get('/3').data == b'apple'717718 def test_trapping_of_bad_request_key_errors(self):719 app = flask.Flask(__name__)720 app.testing = True721 @app.route('/fail')722 def fail():723 flask.request.form['missing_key']724 c = app.test_client()720 self.assert_equal(c.get('/fail').status_code, 400)725 assert c.get('/fail').status_code == 400726727 app.config['TRAP_BAD_REQUEST_ERRORS'] = True728 c = app.test_client()729 try:730 c.get('/fail')731 except KeyError as e:727 self.assert_true(isinstance(e, BadRequest))732 assert isinstance(e, BadRequest)733 else:729 self.fail('Expected exception')734 assert False, 'Expected exception'735736 def test_trapping_of_all_http_exceptions(self):737 app = flask.Flask(__name__)738 app.testing = True
7 unmodified lines
746 c.get('/fail')747 except NotFound as e:748 pass749 else:745 self.fail('Expected exception')750 assert False, 'Expected exception'751752 def test_enctype_debug_helper(self):753 from flask.debughelpers import DebugFilesKeyError754 app = flask.Flask(__name__)
8 unmodified lines
763 with app.test_client() as c:764 try:765 c.post('/fail', data={'foo': 'index.txt'})766 except DebugFilesKeyError as e:762 self.assert_in('no file contents were transmitted', str(e))763 self.assert_in('This was submitted: "index.txt"', str(e))767 assert 'no file contents were transmitted' in str(e)768 assert 'This was submitted: "index.txt"' in str(e)769 else:765 self.fail('Expected exception')770 assert False, 'Expected exception'771772 def test_response_creation(self):773 app = flask.Flask(__name__)774 @app.route('/unicode')
24 unmodified lines
799 "X-Bar": "Foo"800 }801802 c = app.test_client()798 self.assert_equal(c.get('/unicode').data, u'Hällo Wörld'.encode('utf-8'))799 self.assert_equal(c.get('/string').data, u'Hällo Wörld'.encode('utf-8'))803 assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')804 assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')805 rv = c.get('/args')801 self.assert_equal(rv.data, b'Meh')802 self.assert_equal(rv.headers['X-Foo'], 'Testing')803 self.assert_equal(rv.status_code, 400)804 self.assert_equal(rv.mimetype, 'text/plain')806 assert rv.data == b'Meh'807 assert rv.headers['X-Foo'] == 'Testing'808 assert rv.status_code == 400809 assert rv.mimetype == 'text/plain'810 rv2 = c.get('/two_args')806 self.assert_equal(rv2.data, b'Hello')807 self.assert_equal(rv2.headers['X-Foo'], 'Test')808 self.assert_equal(rv2.status_code, 200)809 self.assert_equal(rv2.mimetype, 'text/plain')811 assert rv2.data == b'Hello'812 assert rv2.headers['X-Foo'] == 'Test'813 assert rv2.status_code == 200814 assert rv2.mimetype == 'text/plain'815 rv3 = c.get('/args_status')811 self.assert_equal(rv3.data, b'Hi, status!')812 self.assert_equal(rv3.status_code, 400)813 self.assert_equal(rv3.mimetype, 'text/html')816 assert rv3.data == b'Hi, status!'817 assert rv3.status_code == 400818 assert rv3.mimetype == 'text/html'819 rv4 = c.get('/args_header')815 self.assert_equal(rv4.data, b'Hello world')816 self.assert_equal(rv4.headers['X-Foo'], 'Bar')817 self.assert_equal(rv4.headers['X-Bar'], 'Foo')818 self.assert_equal(rv4.status_code, 404)820 assert rv4.data == b'Hello world'821 assert rv4.headers['X-Foo'] == 'Bar'822 assert rv4.headers['X-Bar'] == 'Foo'823 assert rv4.status_code == 404824825 def test_make_response(self):826 app = flask.Flask(__name__)827 with app.test_request_context():828 rv = flask.make_response()824 self.assert_equal(rv.status_code, 200)825 self.assert_equal(rv.data, b'')826 self.assert_equal(rv.mimetype, 'text/html')829 assert rv.status_code == 200830 assert rv.data == b''831 assert rv.mimetype == 'text/html'832833 rv = flask.make_response('Awesome')829 self.assert_equal(rv.status_code, 200)830 self.assert_equal(rv.data, b'Awesome')831 self.assert_equal(rv.mimetype, 'text/html')834 assert rv.status_code == 200835 assert rv.data == b'Awesome'836 assert rv.mimetype == 'text/html'837838 rv = flask.make_response('W00t', 404)834 self.assert_equal(rv.status_code, 404)835 self.assert_equal(rv.data, b'W00t')836 self.assert_equal(rv.mimetype, 'text/html')839 assert rv.status_code == 404840 assert rv.data == b'W00t'841 assert rv.mimetype == 'text/html'842843 def test_make_response_with_response_instance(self):844 app = flask.Flask(__name__)845 with app.test_request_context():846 rv = flask.make_response(847 flask.jsonify({'msg': 'W00t'}), 400)843 self.assert_equal(rv.status_code, 400)844 self.assert_equal(rv.data, b'{\n "msg": "W00t"\n}')845 self.assert_equal(rv.mimetype, 'application/json')848 assert rv.status_code == 400849 assert rv.data == b'{\n "msg": "W00t"\n}'850 assert rv.mimetype == 'application/json'851852 rv = flask.make_response(853 flask.Response(''), 400)849 self.assert_equal(rv.status_code, 400)850 self.assert_equal(rv.data, b'')851 self.assert_equal(rv.mimetype, 'text/html')854 assert rv.status_code == 400855 assert rv.data == b''856 assert rv.mimetype == 'text/html'857858 rv = flask.make_response(859 flask.Response('', headers={'Content-Type': 'text/html'}),860 400, [('X-Foo', 'bar')])856 self.assert_equal(rv.status_code, 400)857 self.assert_equal(rv.headers['Content-Type'], 'text/html')858 self.assert_equal(rv.headers['X-Foo'], 'bar')861 assert rv.status_code == 400862 assert rv.headers['Content-Type'] == 'text/html'863 assert rv.headers['X-Foo'] == 'bar'864865 def test_url_generation(self):866 app = flask.Flask(__name__)867 @app.route('/hello/<name>', methods=['POST'])868 def hello():869 pass870 with app.test_request_context():866 self.assert_equal(flask.url_for('hello', name='test x'), '/hello/test%20x')867 self.assert_equal(flask.url_for('hello', name='test x', _external=True),868 'http://localhost/hello/test%20x')871 assert flask.url_for('hello', name='test x') == '/hello/test%20x'872 assert flask.url_for('hello', name='test x', _external=True) == \873 'http://localhost/hello/test%20x'874875 def test_build_error_handler(self):876 app = flask.Flask(__name__)877878 # Test base case, a URL which results in a BuildError.879 with app.test_request_context():875 self.assert_raises(BuildError, flask.url_for, 'spam')880 pytest.raises(BuildError, flask.url_for, 'spam')881882 # Verify the error is re-raised if not the current exception.883 try:884 with app.test_request_context():
2 unmodified lines
887 error = err888 try:889 raise RuntimeError('Test case where BuildError is not current.')890 except RuntimeError:886 self.assert_raises(BuildError, app.handle_url_build_error, error, 'spam', {})891 pytest.raises(BuildError, app.handle_url_build_error, error, 'spam', {})892893 # Test a custom handler.894 def handler(error, endpoint, values):895 # Just a test.896 return '/test_handler/'897 app.url_build_error_handlers.append(handler)898 with app.test_request_context():894 self.assert_equal(flask.url_for('spam'), '/test_handler/')899 assert flask.url_for('spam') == '/test_handler/'900901 def test_custom_converters(self):902 from werkzeug.routing import BaseConverter903 class ListConverter(BaseConverter):
7 unmodified lines
911 @app.route('/<list:args>')912 def index(args):913 return '|'.join(args)914 c = app.test_client()910 self.assert_equal(c.get('/1,2,3').data, b'1|2|3')915 assert c.get('/1,2,3').data == b'1|2|3'916917 def test_static_files(self):918 app = flask.Flask(__name__)919 app.testing = True920 rv = app.test_client().get('/static/index.html')916 self.assert_equal(rv.status_code, 200)917 self.assert_equal(rv.data.strip(), b'<h1>Hello World!</h1>')921 assert rv.status_code == 200922 assert rv.data.strip() == b'<h1>Hello World!</h1>'923 with app.test_request_context():919 self.assert_equal(flask.url_for('static', filename='index.html'),920 '/static/index.html')924 assert flask.url_for('static', filename='index.html') == \925 '/static/index.html'926 rv.close()927928 def test_none_response(self):929 app = flask.Flask(__name__)
3 unmodified lines
933 return None934 try:935 app.test_client().get('/')936 except ValueError as e:932 self.assert_equal(str(e), 'View function did not return a response')937 assert str(e) == 'View function did not return a response'938 pass939 else:935 self.assert_true("Expected ValueError")940 assert "Expected ValueError"941942 def test_request_locals(self):938 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')939 self.assert_false(flask.g)943 assert repr(flask.g) == '<LocalProxy unbound>'944 assert not flask.g945946 def test_test_app_proper_environ(self):947 app = flask.Flask(__name__)948 app.config.update(
7 unmodified lines
956 def subdomain():957 return 'Foo SubDomain'958959 rv = app.test_client().get('/')955 self.assert_equal(rv.data, b'Foo')960 assert rv.data == b'Foo'961962 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')958 self.assert_equal(rv.data, b'Foo')963 assert rv.data == b'Foo'964965 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')961 self.assert_equal(rv.data, b'Foo')966 assert rv.data == b'Foo'967968 app.config.update(SERVER_NAME='localhost.localdomain')969 rv = app.test_client().get('/', 'https://localhost.localdomain')965 self.assert_equal(rv.data, b'Foo')970 assert rv.data == b'Foo'971972 try:973 app.config.update(SERVER_NAME='localhost.localdomain:443')974 rv = app.test_client().get('/', 'https://localhost.localdomain')975 # Werkzeug 0.8971 self.assert_equal(rv.status_code, 404)976 assert rv.status_code == 404977 except ValueError as e:978 # Werkzeug 0.7979 assert str(e) == (974 self.assert_equal(str(e), "the server name provided " +975 "('localhost.localdomain:443') does not match the " + \976 "server name from the WSGI environment ('localhost.localdomain')")980 "the server name provided "981 "('localhost.localdomain:443') does not match the "982 "server name from the WSGI environment ('localhost.localdomain')"983 )984985 try:986 app.config.update(SERVER_NAME='localhost.localdomain')987 rv = app.test_client().get('/', 'http://foo.localhost')988 # Werkzeug 0.8982 self.assert_equal(rv.status_code, 404)989 assert rv.status_code == 404990 except ValueError as e:991 # Werkzeug 0.7992 assert str(e) == (985 self.assert_equal(str(e), "the server name provided " + \986 "('localhost.localdomain') does not match the " + \987 "server name from the WSGI environment ('foo.localhost')")993 "the server name provided "994 "('localhost.localdomain') does not match the "995 "server name from the WSGI environment ('foo.localhost')"996 )997998 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')990 self.assert_equal(rv.data, b'Foo SubDomain')999 assert rv.data == b'Foo SubDomain'10001001 def test_exception_propagation(self):1002 def apprunner(configkey):1003 app = flask.Flask(__name__)
8 unmodified lines
1012 c.get('/')1013 except Exception:1014 pass1015 else:1007 self.fail('expected exception')1016 assert False, 'expected exception'1017 else:1009 self.assert_equal(c.get('/').status_code, 500)1018 assert c.get('/').status_code == 50010191020 # we have to run this test in an isolated thread because if the1021 # debug flag is set to true and an exception happens the context is1022 # not torn down. This causes other tests that run after this fail
8 unmodified lines
1031 app.config['MAX_CONTENT_LENGTH'] = 641032 @app.before_request1033 def always_first():1034 flask.request.form['myfile']1026 self.assert_true(False)1035 assert False1036 @app.route('/accept', methods=['POST'])1037 def accept_file():1038 flask.request.form['myfile']1030 self.assert_true(False)1039 assert False1040 @app.errorhandler(413)1041 def catcher(error):1042 return '42'10431044 c = app.test_client()1045 rv = c.post('/accept', data={'myfile': 'foo' * 100})1037 self.assert_equal(rv.data, b'42')1046 assert rv.data == b'42'10471048 def test_url_processors(self):1049 app = flask.Flask(__name__)1050
20 unmodified lines
1071 return flask.url_for('about', lang_code='en')10721073 c = app.test_client()10741066 self.assert_equal(c.get('/de/').data, b'/de/about')1067 self.assert_equal(c.get('/de/about').data, b'/foo')1068 self.assert_equal(c.get('/foo').data, b'/en/about')1075 assert c.get('/de/').data == b'/de/about'1076 assert c.get('/de/about').data == b'/foo'1077 assert c.get('/foo').data == b'/en/about'10781079 def test_inject_blueprint_url_defaults(self):1080 app = flask.Flask(__name__)1081 bp = flask.Blueprint('foo.bar.baz', __name__,
9 unmodified lines
10911092 values = dict()1093 app.inject_url_defaults('foo.bar.baz.view', values)1094 expected = dict(page='login')1086 self.assert_equal(values, expected)1095 assert values == expected10961097 with app.test_request_context('/somepage'):1098 url = flask.url_for('foo.bar.baz.view')1099 expected = '/login'1091 self.assert_equal(url, expected)1100 assert url == expected11011102 def test_nonascii_pathinfo(self):1103 app = flask.Flask(__name__)1104 app.testing = True
3 unmodified lines
1108 return 'Hello World!'11091110 c = app.test_client()1111 rv = c.get(u'/киртест')1103 self.assert_equal(rv.data, b'Hello World!')1112 assert rv.data == b'Hello World!'11131114 def test_debug_mode_complains_after_first_request(self):1115 app = flask.Flask(__name__)1116 app.debug = True1117 @app.route('/')1118 def index():1119 return 'Awesome'1111 self.assert_false(app.got_first_request)1112 self.assert_equal(app.test_client().get('/').data, b'Awesome')1120 assert not app.got_first_request1121 assert app.test_client().get('/').data == b'Awesome'1122 try:1123 @app.route('/foo')1124 def broken():1125 return 'Meh'1126 except AssertionError as e:1118 self.assert_in('A setup function was called', str(e))1127 assert 'A setup function was called' in str(e)1128 else:1120 self.fail('Expected exception')1129 assert False, 'Expected exception'11301131 app.debug = False1132 @app.route('/foo')1133 def working():1134 return 'Meh'1126 self.assert_equal(app.test_client().get('/foo').data, b'Meh')1127 self.assert_true(app.got_first_request)1135 assert app.test_client().get('/foo').data == b'Meh'1136 assert app.got_first_request11371138 def test_before_first_request_functions(self):1139 got = []1140 app = flask.Flask(__name__)
1 unmodified line
1142 def foo():1143 got.append(42)1144 c = app.test_client()1145 c.get('/')1137 self.assert_equal(got, [42])1146 assert got == [42]1147 c.get('/')1139 self.assert_equal(got, [42])1140 self.assert_true(app.got_first_request)1148 assert got == [42]1149 assert app.got_first_request11501151 def test_before_first_request_functions_concurrent(self):1152 got = []1153 app = flask.Flask(__name__)
5 unmodified lines
11591160 c = app.test_client()1161 def get_and_assert():1162 c.get("/")1154 self.assert_equal(got, [42])1163 assert got == [42]11641165 t = Thread(target=get_and_assert)1166 t.start()1167 get_and_assert()1168 t.join()1160 self.assert_true(app.got_first_request)1169 assert app.got_first_request11701171 def test_routing_redirect_debugging(self):1172 app = flask.Flask(__name__)1173 app.debug = True
3 unmodified lines
1177 with app.test_client() as c:1178 try:1179 c.post('/foo', data={})1180 except AssertionError as e:1172 self.assert_in('http://localhost/foo/', str(e))1173 self.assert_in('Make sure to directly send your POST-request '1174 'to this URL', str(e))1181 assert 'http://localhost/foo/' in str(e)1182 assert ('Make sure to directly send '1183 'your POST-request to this URL') in str(e)1184 else:1176 self.fail('Expected exception')1185 assert False, 'Expected exception'11861187 rv = c.get('/foo', data={}, follow_redirects=True)1179 self.assert_equal(rv.data, b'success')1188 assert rv.data == b'success'11891190 app.debug = False1191 with app.test_client() as c:1192 rv = c.post('/foo', data={}, follow_redirects=True)1184 self.assert_equal(rv.data, b'success')1193 assert rv.data == b'success'11941195 def test_route_decorator_custom_endpoint(self):1196 app = flask.Flask(__name__)1197 app.debug = True
15 unmodified lines
1213 assert flask.url_for('bar') == '/bar/'1214 assert flask.url_for('123') == '/bar/123'12151216 c = app.test_client()1208 self.assert_equal(c.get('/foo/').data, b'foo')1209 self.assert_equal(c.get('/bar/').data, b'bar')1210 self.assert_equal(c.get('/bar/123').data, b'123')1217 assert c.get('/foo/').data == b'foo'1218 assert c.get('/bar/').data == b'bar'1219 assert c.get('/bar/123').data == b'123'12201221 def test_preserve_only_once(self):1222 app = flask.Flask(__name__)1223 app.debug = True
3 unmodified lines
1227 1 // 012281229 c = app.test_client()1230 for x in range(3):1222 with self.assert_raises(ZeroDivisionError):1231 with pytest.raises(ZeroDivisionError):1232 c.get('/fail')12331225 self.assert_true(flask._request_ctx_stack.top is not None)1226 self.assert_true(flask._app_ctx_stack.top is not None)1234 assert flask._request_ctx_stack.top is not None1235 assert flask._app_ctx_stack.top is not None1236 # implicit appctx disappears too1237 flask._request_ctx_stack.top.pop()1229 self.assert_true(flask._request_ctx_stack.top is None)1230 self.assert_true(flask._app_ctx_stack.top is None)1238 assert flask._request_ctx_stack.top is None1239 assert flask._app_ctx_stack.top is None12401241 def test_preserve_remembers_exception(self):1242 app = flask.Flask(__name__)1243 app.debug = True
13 unmodified lines
12571258 c = app.test_client()12591260 # After this failure we did not yet call the teardown handler1252 with self.assert_raises(ZeroDivisionError):1261 with pytest.raises(ZeroDivisionError):1262 c.get('/fail')1254 self.assert_equal(errors, [])1263 assert errors == []12641265 # But this request triggers it, and it's an error1266 c.get('/success')1258 self.assert_equal(len(errors), 2)1259 self.assert_true(isinstance(errors[0], ZeroDivisionError))1267 assert len(errors) == 21268 assert isinstance(errors[0], ZeroDivisionError)12691270 # At this point another request does nothing.1271 c.get('/success')1263 self.assert_equal(len(errors), 3)1264 self.assert_equal(errors[1], None)1272 assert len(errors) == 31273 assert errors[1] == None12741275 def test_get_method_on_g(self):1276 app = flask.Flask(__name__)1277 app.testing = True12781279 with app.app_context():1271 self.assert_equal(flask.g.get('x'), None)1272 self.assert_equal(flask.g.get('x', 11), 11)1280 assert flask.g.get('x') == None1281 assert flask.g.get('x', 11) == 111282 flask.g.x = 421274 self.assert_equal(flask.g.get('x'), 42)1275 self.assert_equal(flask.g.x, 42)1283 assert flask.g.get('x') == 421284 assert flask.g.x == 4212851286 def test_g_iteration_protocol(self):1287 app = flask.Flask(__name__)1288 app.testing = True12891290 with app.app_context():1291 flask.g.foo = 231292 flask.g.bar = 421284 self.assert_equal('foo' in flask.g, True)1285 self.assert_equal('foos' in flask.g, False)1286 self.assert_equal(sorted(flask.g), ['bar', 'foo'])1293 assert 'foo' in flask.g1294 assert 'foos' not in flask.g1295 assert sorted(flask.g) == ['bar', 'foo']129612971298class TestSubdomain(TestFlask):1299
8 unmodified lines
1308 return 'test index'13091310 c = app.test_client()1311 rv = c.get('/', 'http://localhost/')1303 self.assert_equal(rv.data, b'normal index')1312 assert rv.data == b'normal index'13131314 rv = c.get('/', 'http://test.localhost/')1306 self.assert_equal(rv.data, b'test index')1315 assert rv.data == b'test index'13161317 def test_subdomain_matching(self):1318 app = flask.Flask(__name__)1319 app.config['SERVER_NAME'] = 'localhost'
2 unmodified lines
1322 return 'index for %s' % user13231324 c = app.test_client()1325 rv = c.get('/', 'http://mitsuhiko.localhost/')1317 self.assert_equal(rv.data, b'index for mitsuhiko')1326 assert rv.data == b'index for mitsuhiko'13271328 def test_subdomain_matching_with_ports(self):1329 app = flask.Flask(__name__)1330 app.config['SERVER_NAME'] = 'localhost:3000'
2 unmodified lines
1333 return 'index for %s' % user13341335 c = app.test_client()1336 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1328 self.assert_equal(rv.data, b'index for mitsuhiko')1337 assert rv.data == b'index for mitsuhiko'13381339 def test_multi_route_rules(self):1340 app = flask.Flask(__name__)1341
2 unmodified lines
1344 def index(test='a'):1345 return test13461347 rv = app.test_client().open('/')1339 self.assert_equal(rv.data, b'a')1348 assert rv.data == b'a'1349 rv = app.test_client().open('/b/')1341 self.assert_equal(rv.data, b'b')1350 assert rv.data == b'b'13511352 def test_multi_route_class_views(self):1353 class View(object):1354 def __init__(self, app):
5 unmodified lines
13601361 app = flask.Flask(__name__)1362 _ = View(app)1363 rv = app.test_client().open('/')1355 self.assert_equal(rv.data, b'a')1364 assert rv.data == b'a'1365 rv = app.test_client().open('/b/')1357 self.assert_equal(rv.data, b'b')1366 assert rv.data == b'b'
modified:tests/test_blueprints.py+75 added-75 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import unittest16from tests import TestFlask17from flask._compat import text_type
38 unmodified lines
56 return 'application itself says no', 4035758 c = app.test_client()5958 self.assert_equal(c.get('/frontend-no').data, b'frontend says no')59 self.assert_equal(c.get('/backend-no').data, b'backend says no')60 self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no')60 assert c.get('/frontend-no').data == b'frontend says no'61 assert c.get('/backend-no').data == b'backend says no'62 assert c.get('/what-is-a-sideend').data == b'application itself says no'6364 def test_blueprint_specific_user_error_handling(self):65 class MyDecoratorException(Exception):66 pass
3 unmodified lines
70 blue = flask.Blueprint('blue', __name__)7172 @blue.errorhandler(MyDecoratorException)73 def my_decorator_exception_handler(e):72 self.assert_true(isinstance(e, MyDecoratorException))74 assert isinstance(e, MyDecoratorException)75 return 'boom'7677 def my_function_exception_handler(e):76 self.assert_true(isinstance(e, MyFunctionException))78 assert isinstance(e, MyFunctionException)79 return 'bam'80 blue.register_error_handler(MyFunctionException, my_function_exception_handler)8182 @blue.route('/decorator')
7 unmodified lines
90 app.register_blueprint(blue)9192 c = app.test_client()9392 self.assert_equal(c.get('/decorator').data, b'boom')93 self.assert_equal(c.get('/function').data, b'bam')94 assert c.get('/decorator').data == b'boom'95 assert c.get('/function').data == b'bam'9697 def test_blueprint_url_definitions(self):98 bp = flask.Blueprint('test', __name__)99
9 unmodified lines
109 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})110 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})111112 c = app.test_client()111 self.assert_equal(c.get('/1/foo').data, b'23/42')112 self.assert_equal(c.get('/2/foo').data, b'19/42')113 self.assert_equal(c.get('/1/bar').data, b'23')114 self.assert_equal(c.get('/2/bar').data, b'19')113 assert c.get('/1/foo').data == b'23/42'114 assert c.get('/2/foo').data == b'19/42'115 assert c.get('/1/bar').data == b'23'116 assert c.get('/2/bar').data == b'19'117118 def test_blueprint_url_processors(self):119 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')120
17 unmodified lines
138 app.register_blueprint(bp)139140 c = app.test_client()141140 self.assert_equal(c.get('/de/').data, b'/de/about')141 self.assert_equal(c.get('/de/about').data, b'/de/')142 assert c.get('/de/').data == b'/de/about'143 assert c.get('/de/about').data == b'/de/'144145 def test_templates_and_static(self):146 from blueprintapp import app147 c = app.test_client()148149 rv = c.get('/')148 self.assert_equal(rv.data, b'Hello from the Frontend')150 assert rv.data == b'Hello from the Frontend'151 rv = c.get('/admin/')150 self.assert_equal(rv.data, b'Hello from the Admin')152 assert rv.data == b'Hello from the Admin'153 rv = c.get('/admin/index2')152 self.assert_equal(rv.data, b'Hello from the Admin')154 assert rv.data == b'Hello from the Admin'155 rv = c.get('/admin/static/test.txt')154 self.assert_equal(rv.data.strip(), b'Admin File')156 assert rv.data.strip() == b'Admin File'157 rv.close()158 rv = c.get('/admin/static/css/test.css')157 self.assert_equal(rv.data.strip(), b'/* nested file */')159 assert rv.data.strip() == b'/* nested file */'160 rv.close()161162 # try/finally, in case other tests use this app for Blueprint tests.163 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
3 unmodified lines
167 expected_max_age = 7200168 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age169 rv = c.get('/admin/static/css/test.css')170 cc = parse_cache_control_header(rv.headers['Cache-Control'])169 self.assert_equal(cc.max_age, expected_max_age)171 assert cc.max_age == expected_max_age172 rv.close()173 finally:174 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default175176 with app.test_request_context():175 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),176 '/admin/static/test.txt')177 assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'178179 with app.test_request_context():180 try:181 flask.render_template('missing.html')182 except TemplateNotFound as e:182 self.assert_equal(e.name, 'missing.html')183 assert e.name == 'missing.html'184 else:184 self.assert_true(0, 'expected exception')185 assert 0, 'expected exception'186187 with flask.Flask(__name__).test_request_context():187 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')188 assert flask.render_template('nested/nested.txt') == 'I\'m nested'189190 def test_default_static_cache_timeout(self):191 app = flask.Flask(__name__)192 class MyBlueprint(flask.Blueprint):
12 unmodified lines
205 unexpected_max_age = 7200206 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age207 rv = blueprint.send_static_file('index.html')208 cc = parse_cache_control_header(rv.headers['Cache-Control'])208 self.assert_equal(cc.max_age, 100)209 assert cc.max_age == 100210 rv.close()211 finally:212 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default213214 def test_templates_list(self):215 from blueprintapp import app216 templates = sorted(app.jinja_env.list_templates())216 self.assert_equal(templates, ['admin/index.html',217 'frontend/index.html'])217 assert templates == ['admin/index.html', 'frontend/index.html']218219 def test_dotted_names(self):220 frontend = flask.Blueprint('myapp.frontend', __name__)221 backend = flask.Blueprint('myapp.backend', __name__)
14 unmodified lines
236 app.register_blueprint(frontend)237 app.register_blueprint(backend)238239 c = app.test_client()240 self.assert_equal(c.get('/fe').data.strip(), b'/be')241 self.assert_equal(c.get('/fe2').data.strip(), b'/fe')242 self.assert_equal(c.get('/be').data.strip(), b'/fe')240 assert c.get('/fe').data.strip() == b'/be'241 assert c.get('/fe2').data.strip() == b'/fe'242 assert c.get('/be').data.strip() == b'/fe'243244 def test_dotted_names_from_app(self):245 app = flask.Flask(__name__)246 app.testing = True
10 unmodified lines
257 app.register_blueprint(test)258259 with app.test_client() as c:260 rv = c.get('/')261 self.assert_equal(rv.data, b'/test/')261 assert rv.data == b'/test/'262263 def test_empty_url_defaults(self):264 bp = flask.Blueprint('bp', __name__)265
5 unmodified lines
271 app = flask.Flask(__name__)272 app.register_blueprint(bp)273274 c = app.test_client()275 self.assert_equal(c.get('/').data, b'1')276 self.assert_equal(c.get('/page/2').data, b'2')275 assert c.get('/').data == b'1'276 assert c.get('/page/2').data == b'2'277278 def test_route_decorator_custom_endpoint(self):279280 bp = flask.Blueprint('bp', __name__)
21 unmodified lines
302 def index():303 return flask.request.endpoint304305 c = app.test_client()306 self.assert_equal(c.get('/').data, b'index')307 self.assert_equal(c.get('/py/foo').data, b'bp.foo')308 self.assert_equal(c.get('/py/bar').data, b'bp.bar')309 self.assert_equal(c.get('/py/bar/123').data, b'bp.123')310 self.assert_equal(c.get('/py/bar/foo').data, b'bp.bar_foo')306 assert c.get('/').data == b'index'307 assert c.get('/py/foo').data == b'bp.foo'308 assert c.get('/py/bar').data == b'bp.bar'309 assert c.get('/py/bar/123').data == b'bp.123'310 assert c.get('/py/bar/foo').data == b'bp.bar_foo'311312 def test_route_decorator_custom_endpoint_with_dots(self):313 bp = flask.Blueprint('bp', __name__)314
21 unmodified lines
336337 def foo_foo_foo():338 pass339340 self.assert_raises(340 pytest.raises(341 AssertionError,342 lambda: bp.add_url_rule(343 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo344 )345 )346347 self.assert_raises(347 pytest.raises(348 AssertionError,349 bp.route('/bar/123', endpoint='bar.123'),350 lambda: None351 )
1 unmodified line
353 app = flask.Flask(__name__)354 app.register_blueprint(bp, url_prefix='/py')355356 c = app.test_client()357 self.assert_equal(c.get('/py/foo').data, b'bp.foo')357 assert c.get('/py/foo').data == b'bp.foo'358 # The rule's didn't actually made it through359 rv = c.get('/py/bar')360 assert rv.status_code == 404361 rv = c.get('/py/bar/123')
5 unmodified lines
367 def my_reverse(s):368 return s[::-1]369 app = flask.Flask(__name__)370 app.register_blueprint(bp, url_prefix='/py')371 self.assert_in('my_reverse', app.jinja_env.filters.keys())372 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)373 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')371 assert 'my_reverse' in app.jinja_env.filters.keys()372 assert app.jinja_env.filters['my_reverse'] == my_reverse373 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'374375 def test_add_template_filter(self):376 bp = flask.Blueprint('bp', __name__)377 def my_reverse(s):378 return s[::-1]379 bp.add_app_template_filter(my_reverse)380 app = flask.Flask(__name__)381 app.register_blueprint(bp, url_prefix='/py')382 self.assert_in('my_reverse', app.jinja_env.filters.keys())383 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)384 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')382 assert 'my_reverse' in app.jinja_env.filters.keys()383 assert app.jinja_env.filters['my_reverse'] == my_reverse384 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'385386 def test_template_filter_with_name(self):387 bp = flask.Blueprint('bp', __name__)388 @bp.app_template_filter('strrev')389 def my_reverse(s):390 return s[::-1]391 app = flask.Flask(__name__)392 app.register_blueprint(bp, url_prefix='/py')393 self.assert_in('strrev', app.jinja_env.filters.keys())394 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)395 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')393 assert 'strrev' in app.jinja_env.filters.keys()394 assert app.jinja_env.filters['strrev'] == my_reverse395 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'396397 def test_add_template_filter_with_name(self):398 bp = flask.Blueprint('bp', __name__)399 def my_reverse(s):400 return s[::-1]401 bp.add_app_template_filter(my_reverse, 'strrev')402 app = flask.Flask(__name__)403 app.register_blueprint(bp, url_prefix='/py')404 self.assert_in('strrev', app.jinja_env.filters.keys())405 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)406 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')404 assert 'strrev' in app.jinja_env.filters.keys()405 assert app.jinja_env.filters['strrev'] == my_reverse406 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'407408 def test_template_filter_with_template(self):409 bp = flask.Blueprint('bp', __name__)410 @bp.app_template_filter()
4 unmodified lines
415 @app.route('/')416 def index():417 return flask.render_template('template_filter.html', value='abcd')418 rv = app.test_client().get('/')419 self.assert_equal(rv.data, b'dcba')419 assert rv.data == b'dcba'420421 def test_template_filter_after_route_with_template(self):422 app = flask.Flask(__name__)423 @app.route('/')
4 unmodified lines
428 def super_reverse(s):429 return s[::-1]430 app.register_blueprint(bp, url_prefix='/py')431 rv = app.test_client().get('/')432 self.assert_equal(rv.data, b'dcba')432 assert rv.data == b'dcba'433434 def test_add_template_filter_with_template(self):435 bp = flask.Blueprint('bp', __name__)436 def super_reverse(s):
4 unmodified lines
441 @app.route('/')442 def index():443 return flask.render_template('template_filter.html', value='abcd')444 rv = app.test_client().get('/')445 self.assert_equal(rv.data, b'dcba')445 assert rv.data == b'dcba'446447 def test_template_filter_with_name_and_template(self):448 bp = flask.Blueprint('bp', __name__)449 @bp.app_template_filter('super_reverse')
4 unmodified lines
454 @app.route('/')455 def index():456 return flask.render_template('template_filter.html', value='abcd')457 rv = app.test_client().get('/')458 self.assert_equal(rv.data, b'dcba')458 assert rv.data == b'dcba'459460 def test_add_template_filter_with_name_and_template(self):461 bp = flask.Blueprint('bp', __name__)462 def my_reverse(s):
4 unmodified lines
467 @app.route('/')468 def index():469 return flask.render_template('template_filter.html', value='abcd')470 rv = app.test_client().get('/')471 self.assert_equal(rv.data, b'dcba')471 assert rv.data == b'dcba'472473 def test_template_test(self):474 bp = flask.Blueprint('bp', __name__)475 @bp.app_template_test()476 def is_boolean(value):477 return isinstance(value, bool)478 app = flask.Flask(__name__)479 app.register_blueprint(bp, url_prefix='/py')480 self.assert_in('is_boolean', app.jinja_env.tests.keys())481 self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)482 self.assert_true(app.jinja_env.tests['is_boolean'](False))480 assert 'is_boolean' in app.jinja_env.tests.keys()481 assert app.jinja_env.tests['is_boolean'] == is_boolean482 assert app.jinja_env.tests['is_boolean'](False)483484 def test_add_template_test(self):485 bp = flask.Blueprint('bp', __name__)486 def is_boolean(value):487 return isinstance(value, bool)488 bp.add_app_template_test(is_boolean)489 app = flask.Flask(__name__)490 app.register_blueprint(bp, url_prefix='/py')491 self.assert_in('is_boolean', app.jinja_env.tests.keys())492 self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)493 self.assert_true(app.jinja_env.tests['is_boolean'](False))491 assert 'is_boolean' in app.jinja_env.tests.keys()492 assert app.jinja_env.tests['is_boolean'] == is_boolean493 assert app.jinja_env.tests['is_boolean'](False)494495 def test_template_test_with_name(self):496 bp = flask.Blueprint('bp', __name__)497 @bp.app_template_test('boolean')498 def is_boolean(value):499 return isinstance(value, bool)500 app = flask.Flask(__name__)501 app.register_blueprint(bp, url_prefix='/py')502 self.assert_in('boolean', app.jinja_env.tests.keys())503 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)504 self.assert_true(app.jinja_env.tests['boolean'](False))502 assert 'boolean' in app.jinja_env.tests.keys()503 assert app.jinja_env.tests['boolean'] == is_boolean504 assert app.jinja_env.tests['boolean'](False)505506 def test_add_template_test_with_name(self):507 bp = flask.Blueprint('bp', __name__)508 def is_boolean(value):509 return isinstance(value, bool)510 bp.add_app_template_test(is_boolean, 'boolean')511 app = flask.Flask(__name__)512 app.register_blueprint(bp, url_prefix='/py')513 self.assert_in('boolean', app.jinja_env.tests.keys())514 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)515 self.assert_true(app.jinja_env.tests['boolean'](False))513 assert 'boolean' in app.jinja_env.tests.keys()514 assert app.jinja_env.tests['boolean'] == is_boolean515 assert app.jinja_env.tests['boolean'](False)516517 def test_template_test_with_template(self):518 bp = flask.Blueprint('bp', __name__)519 @bp.app_template_test()
4 unmodified lines
524 @app.route('/')525 def index():526 return flask.render_template('template_test.html', value=False)527 rv = app.test_client().get('/')528 self.assert_in(b'Success!', rv.data)528 assert b'Success!' in rv.data529530 def test_template_test_after_route_with_template(self):531 app = flask.Flask(__name__)532 @app.route('/')
4 unmodified lines
537 def boolean(value):538 return isinstance(value, bool)539 app.register_blueprint(bp, url_prefix='/py')540 rv = app.test_client().get('/')541 self.assert_in(b'Success!', rv.data)541 assert b'Success!' in rv.data542543 def test_add_template_test_with_template(self):544 bp = flask.Blueprint('bp', __name__)545 def boolean(value):
4 unmodified lines
550 @app.route('/')551 def index():552 return flask.render_template('template_test.html', value=False)553 rv = app.test_client().get('/')554 self.assert_in(b'Success!', rv.data)554 assert b'Success!' in rv.data555556 def test_template_test_with_name_and_template(self):557 bp = flask.Blueprint('bp', __name__)558 @bp.app_template_test('boolean')
4 unmodified lines
563 @app.route('/')564 def index():565 return flask.render_template('template_test.html', value=False)566 rv = app.test_client().get('/')567 self.assert_in(b'Success!', rv.data)567 assert b'Success!' in rv.data568569 def test_add_template_test_with_name_and_template(self):570 bp = flask.Blueprint('bp', __name__)571 def is_boolean(value):
4 unmodified lines
576 @app.route('/')577 def index():578 return flask.render_template('template_test.html', value=False)579 rv = app.test_client().get('/')580 self.assert_in(b'Success!', rv.data)580 assert b'Success!' in rv.data581582def suite():583 suite = unittest.TestSuite()584 suite.addTest(unittest.makeSuite(TestBlueprint))
1 unmodified line
modified:tests/test_config.py+33 added-33 removed
28 unmodified lines
2930class TestConfig(TestFlask):3132 def common_object_test(self, app):33 self.assert_equal(app.secret_key, 'devkey')34 self.assert_equal(app.config['TEST_KEY'], 'foo')35 self.assert_not_in('TestConfig', app.config)33 assert app.secret_key == 'devkey'34 assert app.config['TEST_KEY'] == 'foo'35 assert 'TestConfig' not in app.config3637 def test_config_from_file(self):38 app = flask.Flask(__name__)39 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
32 unmodified lines
72 )73 self.common_object_test(app)7475 app = flask.Flask(__name__)76 with self.assert_raises(TypeError):76 with pytest.raises(TypeError):77 app.config.from_mapping(78 {}, {}79 )80
13 unmodified lines
94 app = flask.Flask(__name__)95 try:96 app.config.from_envvar('FOO_SETTINGS')97 except RuntimeError as e:98 self.assert_true("'FOO_SETTINGS' is not set" in str(e))98 assert "'FOO_SETTINGS' is not set" in str(e)99 else:100 self.assert_true(0, 'expected exception')101 self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True))100 assert 0, 'expected exception'101 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)102103 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}104 self.assert_true(app.config.from_envvar('FOO_SETTINGS'))104 assert app.config.from_envvar('FOO_SETTINGS')105 self.common_object_test(app)106 finally:107 os.environ = env108
5 unmodified lines
114 app = flask.Flask(__name__)115 app.config.from_envvar('FOO_SETTINGS')116 except IOError as e:117 msg = str(e)118 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '119 'file (No such file or directory):'))120 self.assert_true(msg.endswith("missing.cfg'"))118 assert msg.startswith('[Errno 2] Unable to load configuration '119 'file (No such file or directory):')120 assert msg.endswith("missing.cfg'")121 else:122 self.fail('expected IOError')123 self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True))122 assert False, 'expected IOError'123 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)124 finally:125 os.environ = env126127 def test_config_missing(self):
1 unmodified line
129 try:130 app.config.from_pyfile('missing.cfg')131 except IOError as e:132 msg = str(e)133 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '134 'file (No such file or directory):'))135 self.assert_true(msg.endswith("missing.cfg'"))133 assert msg.startswith('[Errno 2] Unable to load configuration '134 'file (No such file or directory):')135 assert msg.endswith("missing.cfg'")136 else:137 self.assert_true(0, 'expected config')138 self.assert_false(app.config.from_pyfile('missing.cfg', silent=True))137 assert 0, 'expected config'138 assert not app.config.from_pyfile('missing.cfg', silent=True)139140 def test_config_missing_json(self):141 app = flask.Flask(__name__)142 try:143 app.config.from_json('missing.json')144 except IOError as e:145 msg = str(e)146 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '147 'file (No such file or directory):'))148 self.assert_true(msg.endswith("missing.json'"))146 assert msg.startswith('[Errno 2] Unable to load configuration '147 'file (No such file or directory):')148 assert msg.endswith("missing.json'")149 else:150 self.assert_true(0, 'expected config')151 self.assert_false(app.config.from_json('missing.json', silent=True))150 assert 0, 'expected config'151 assert not app.config.from_json('missing.json', silent=True)152153 def test_custom_config_class(self):154 class Config(flask.Config):155 pass156 class Flask(flask.Flask):157 config_class = Config158 app = Flask(__name__)159 self.assert_isinstance(app.config, Config)159 assert isinstance(app.config, Config)160 app.config.from_object(__name__)161 self.common_object_test(app)162163 def test_session_lifetime(self):164 app = flask.Flask(__name__)165 app.config['PERMANENT_SESSION_LIFETIME'] = 42166 self.assert_equal(app.permanent_session_lifetime.seconds, 42)166 assert app.permanent_session_lifetime.seconds == 42167168 def test_get_namespace(self):169 app = flask.Flask(__name__)170 app.config['FOO_OPTION_1'] = 'foo option 1'171 app.config['FOO_OPTION_2'] = 'foo option 2'172 app.config['BAR_STUFF_1'] = 'bar stuff 1'173 app.config['BAR_STUFF_2'] = 'bar stuff 2'174 foo_options = app.config.get_namespace('FOO_')175 self.assert_equal(2, len(foo_options))176 self.assert_equal('foo option 1', foo_options['option_1'])177 self.assert_equal('foo option 2', foo_options['option_2'])175 assert 2 == len(foo_options)176 assert 'foo option 1' == foo_options['option_1']177 assert 'foo option 2' == foo_options['option_2']178 bar_options = app.config.get_namespace('BAR_', lowercase=False)179 self.assert_equal(2, len(bar_options))180 self.assert_equal('bar stuff 1', bar_options['STUFF_1'])181 self.assert_equal('bar stuff 2', bar_options['STUFF_2'])179 assert 2 == len(bar_options)180 assert 'bar stuff 1' == bar_options['STUFF_1']181 assert 'bar stuff 2' == bar_options['STUFF_2']182183184class TestInstance(TestFlask):185 def test_explicit_instance_paths(self, apps_tmpdir):
1 unmodified line
187 flask.Flask(__name__, instance_path='instance')188 assert 'must be absolute' in str(excinfo.value)189190 app = flask.Flask(__name__, instance_path=str(apps_tmpdir))191 self.assert_equal(app.instance_path, str(apps_tmpdir))191 assert app.instance_path == str(apps_tmpdir)192193 def test_main_module_paths(self, apps_tmpdir, purge_module):194 app = apps_tmpdir.join('main_app.py')195 app.write('import flask\n\napp = flask.Flask("__main__")')
88 unmodified lines
284 def find_module(self, name):285 return self286 sys.meta_path.append(Loader())287 try:288 with self.assert_raises(AttributeError):288 with pytest.raises(AttributeError):289 flask.Flask(__name__)290 finally:291 sys.meta_path.pop()
modified:tests/test_ext.py+28 added-25 removed
9 unmodified lines
10"""1112import sys13import unittest14import pytest1516try:17 from imp import reload as reload_module18except ImportError:19 reload_module = reload
22 unmodified lines
42 cls = type(item)43 if cls.__module__ == 'flask.exthook' and \44 cls.__name__ == 'ExtensionImporter':45 import_hooks += 144 self.assert_equal(import_hooks, 1)46 assert import_hooks == 14748 def teardown(self):49 from flask import ext50 for key in ext.__dict__:49 self.assert_not_in('.', key)51 assert '.' not in key5253 def test_flaskext_new_simple_import_normal(self):54 from flask.ext.newext_simple import ext_id53 self.assert_equal(ext_id, 'newext_simple')55 assert ext_id == 'newext_simple'5657 def test_flaskext_new_simple_import_module(self):58 from flask.ext import newext_simple57 self.assert_equal(newext_simple.ext_id, 'newext_simple')58 self.assert_equal(newext_simple.__name__, 'flask_newext_simple')59 assert newext_simple.ext_id == 'newext_simple'60 assert newext_simple.__name__ == 'flask_newext_simple'6162 def test_flaskext_new_package_import_normal(self):63 from flask.ext.newext_package import ext_id62 self.assert_equal(ext_id, 'newext_package')64 assert ext_id == 'newext_package'6566 def test_flaskext_new_package_import_module(self):67 from flask.ext import newext_package66 self.assert_equal(newext_package.ext_id, 'newext_package')67 self.assert_equal(newext_package.__name__, 'flask_newext_package')68 assert newext_package.ext_id == 'newext_package'69 assert newext_package.__name__ == 'flask_newext_package'7071 def test_flaskext_new_package_import_submodule_function(self):72 from flask.ext.newext_package.submodule import test_function71 self.assert_equal(test_function(), 42)73 assert test_function() == 427475 def test_flaskext_new_package_import_submodule(self):76 from flask.ext.newext_package import submodule75 self.assert_equal(submodule.__name__, 'flask_newext_package.submodule')76 self.assert_equal(submodule.test_function(), 42)77 assert submodule.__name__ == 'flask_newext_package.submodule'78 assert submodule.test_function() == 427980 def test_flaskext_old_simple_import_normal(self):81 from flask.ext.oldext_simple import ext_id80 self.assert_equal(ext_id, 'oldext_simple')82 assert ext_id == 'oldext_simple'8384 def test_flaskext_old_simple_import_module(self):85 from flask.ext import oldext_simple84 self.assert_equal(oldext_simple.ext_id, 'oldext_simple')85 self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple')86 assert oldext_simple.ext_id == 'oldext_simple'87 assert oldext_simple.__name__ == 'flaskext.oldext_simple'8889 def test_flaskext_old_package_import_normal(self):90 from flask.ext.oldext_package import ext_id89 self.assert_equal(ext_id, 'oldext_package')91 assert ext_id == 'oldext_package'9293 def test_flaskext_old_package_import_module(self):94 from flask.ext import oldext_package93 self.assert_equal(oldext_package.ext_id, 'oldext_package')94 self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package')95 assert oldext_package.ext_id == 'oldext_package'96 assert oldext_package.__name__ == 'flaskext.oldext_package'9798 def test_flaskext_old_package_import_submodule(self):99 from flask.ext.oldext_package import submodule98 self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule')99 self.assert_equal(submodule.test_function(), 42)100 assert submodule.__name__ == 'flaskext.oldext_package.submodule'101 assert submodule.test_function() == 42102103 def test_flaskext_old_package_import_submodule_function(self):104 from flask.ext.oldext_package.submodule import test_function103 self.assert_equal(test_function(), 42)105 assert test_function() == 42106107 def test_flaskext_broken_package_no_module_caching(self):108 for x in range(2):107 with self.assert_raises(ImportError):109 with pytest.raises(ImportError):110 import flask.ext.broken111112 def test_no_error_swallowing(self):113 try:114 import flask.ext.broken115 except ImportError:116 exc_type, exc_value, tb = sys.exc_info()115 self.assert_true(exc_type is ImportError)117 assert exc_type is ImportError118 if PY2:119 message = 'No module named missing_module'120 else:121 message = 'No module named \'missing_module\''120 self.assert_equal(str(exc_value), message)121 self.assert_true(tb.tb_frame.f_globals is globals())122 assert str(exc_value) == message123 assert tb.tb_frame.f_globals is globals()124125 # reraise() adds a second frame so we need to skip that one too.126 # On PY3 we even have another one :(127 next = tb.tb_next.tb_next128 if not PY2:129 next = next.tb_next130 131 import os.path130 self.assert_in(os.path.join('flask_broken', '__init__.py'), next.tb_frame.f_code.co_filename)132 assert os.path.join('flask_broken', '__init__.py') in \133 next.tb_frame.f_code.co_filename134135136def suite():137 suite = unittest.TestSuite()
2 unmodified lines
modified:tests/test_helpers.py+94 added-100 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import flask16import unittest17from logging import StreamHandler
19 unmodified lines
37 def return_json():38 return flask.jsonify(foo=text_type(flask.request.get_json()))39 c = app.test_client()40 rv = c.post('/json', data='malformed', content_type='application/json')39 self.assert_equal(rv.status_code, 400)41 assert rv.status_code == 4004243 def test_json_custom_mimetypes(self):44 app = flask.Flask(__name__)45 @app.route('/json', methods=['POST'])46 def return_json():47 return flask.request.get_json()48 c = app.test_client()49 rv = c.post('/json', data='"foo"', content_type='application/x+json')48 self.assert_equal(rv.data, b'foo')50 assert rv.data == b'foo'5152 def test_json_body_encoding(self):53 app = flask.Flask(__name__)54 app.testing = True
3 unmodified lines
5859 c = app.test_client()60 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),61 content_type='application/json; charset=iso-8859-15')60 self.assert_equal(resp.data, u'Hällo Wörld'.encode('utf-8'))62 assert resp.data == u'Hällo Wörld'.encode('utf-8')6364 def test_jsonify(self):65 d = dict(a=23, b=42, c=[1, 2, 3])66 app = flask.Flask(__name__)
5 unmodified lines
72 return flask.jsonify(d)73 c = app.test_client()74 for url in '/kw', '/dict':75 rv = c.get(url)74 self.assert_equal(rv.mimetype, 'application/json')75 self.assert_equal(flask.json.loads(rv.data), d)76 assert rv.mimetype == 'application/json'77 assert flask.json.loads(rv.data) == d7879 def test_json_as_unicode(self):80 app = flask.Flask(__name__)8182 app.config['JSON_AS_ASCII'] = True83 with app.app_context():84 rv = flask.json.dumps(u'\N{SNOWMAN}')83 self.assert_equal(rv, '"\\u2603"')85 assert rv == '"\\u2603"'8687 app.config['JSON_AS_ASCII'] = False88 with app.app_context():89 rv = flask.json.dumps(u'\N{SNOWMAN}')88 self.assert_equal(rv, u'"\u2603"')90 assert rv == u'"\u2603"'9192 def test_json_attr(self):93 app = flask.Flask(__name__)94 @app.route('/add', methods=['POST'])
2 unmodified lines
97 return text_type(json['a'] + json['b'])98 c = app.test_client()99 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),100 content_type='application/json')99 self.assert_equal(rv.data, b'3')101 assert rv.data == b'3'102103 def test_template_escaping(self):104 app = flask.Flask(__name__)105 render = flask.render_template_string106 with app.test_request_context():107 rv = flask.json.htmlsafe_dumps('</script>')106 self.assert_equal(rv, u'"\\u003c/script\\u003e"')107 self.assert_equal(type(rv), text_type)108 assert rv == u'"\\u003c/script\\u003e"'109 assert type(rv) == text_type110 rv = render('{{ "</script>"|tojson }}')109 self.assert_equal(rv, '"\\u003c/script\\u003e"')111 assert rv == '"\\u003c/script\\u003e"'112 rv = render('{{ "<\0/script>"|tojson }}')111 self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')113 assert rv == '"\\u003c\\u0000/script\\u003e"'114 rv = render('{{ "<!--<script>"|tojson }}')113 self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')115 assert rv == '"\\u003c!--\\u003cscript\\u003e"'116 rv = render('{{ "&"|tojson }}')115 self.assert_equal(rv, '"\\u0026"')117 assert rv == '"\\u0026"'118 rv = render('{{ "\'"|tojson }}')117 self.assert_equal(rv, '"\\u0027"')119 assert rv == '"\\u0027"'120 rv = render("<a ng-data='{{ data|tojson }}'></a>",121 data={'x': ["foo", "bar", "baz'"]})120 self.assert_equal(rv,121 '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>')122 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'123124 def test_json_customization(self):125 class X(object):126 def __init__(self, val):
21 unmodified lines
148 c = app.test_client()149 rv = c.post('/', data=flask.json.dumps({150 'x': {'_foo': 42}151 }), content_type='application/json')151 self.assert_equal(rv.data, b'"<42>"')152 assert rv.data == b'"<42>"'153154 def test_modified_url_encoding(self):155 class ModifiedRequest(flask.Request):156 url_charset = 'euc-kr'
6 unmodified lines
163 def index():164 return flask.request.args['foo']165166 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))166 self.assert_equal(rv.status_code, 200)167 self.assert_equal(rv.data, u'정상처리'.encode('utf-8'))167 assert rv.status_code == 200168 assert rv.data == u'정상처리'.encode('utf-8')169170 if not has_encoding('euc-kr'):171 test_modified_url_encoding = None172173 def test_json_key_sorting(self):174 app = flask.Flask(__name__)175 app.testing = True175 self.assert_equal(app.config['JSON_SORT_KEYS'], True)176 assert app.config['JSON_SORT_KEYS'] == True177 d = dict.fromkeys(range(20), 'foo')178179 @app.route('/')180 def index():
55 unmodified lines
236 '}'237 ]238239 try:239 self.assert_equal(lines, sorted_by_int)240 assert lines == sorted_by_int241 except AssertionError:241 self.assert_equal(lines, sorted_by_str)242 assert lines == sorted_by_str243244class TestSendfile(TestFlask):245246 def test_send_file_regular(self):247 app = flask.Flask(__name__)248 with app.test_request_context():249 rv = flask.send_file('static/index.html')249 self.assert_true(rv.direct_passthrough)250 self.assert_equal(rv.mimetype, 'text/html')250 assert rv.direct_passthrough251 assert rv.mimetype == 'text/html'252 with app.open_resource('static/index.html') as f:253 rv.direct_passthrough = False253 self.assert_equal(rv.data, f.read())254 assert rv.data == f.read()255 rv.close()256257 def test_send_file_xsendfile(self):258 app = flask.Flask(__name__)259 app.use_x_sendfile = True260 with app.test_request_context():261 rv = flask.send_file('static/index.html')261 self.assert_true(rv.direct_passthrough)262 self.assert_in('x-sendfile', rv.headers)263 self.assert_equal(rv.headers['x-sendfile'],264 os.path.join(app.root_path, 'static/index.html'))265 self.assert_equal(rv.mimetype, 'text/html')262 assert rv.direct_passthrough263 assert 'x-sendfile' in rv.headers264 assert rv.headers['x-sendfile'] == \265 os.path.join(app.root_path, 'static/index.html')266 assert rv.mimetype == 'text/html'267 rv.close()268269 def test_send_file_object(self):270 app = flask.Flask(__name__)
2 unmodified lines
273 f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')274 rv = flask.send_file(f)275 rv.direct_passthrough = False276 with app.open_resource('static/index.html') as f:276 self.assert_equal(rv.data, f.read())277 self.assert_equal(rv.mimetype, 'text/html')277 assert rv.data == f.read()278 assert rv.mimetype == 'text/html'279 rv.close()280 # mimetypes + etag280 self.assert_equal(len(captured), 2)281 assert len(captured) == 2282283 app.use_x_sendfile = True284 with catch_warnings() as captured:285 with app.test_request_context():286 f = open(os.path.join(app.root_path, 'static/index.html'))287 rv = flask.send_file(f)287 self.assert_equal(rv.mimetype, 'text/html')288 self.assert_in('x-sendfile', rv.headers)289 self.assert_equal(rv.headers['x-sendfile'],290 os.path.join(app.root_path, 'static/index.html'))288 assert rv.mimetype == 'text/html'289 assert 'x-sendfile' in rv.headers290 assert rv.headers['x-sendfile'] == \291 os.path.join(app.root_path, 'static/index.html')292 rv.close()293 # mimetypes + etag293 self.assert_equal(len(captured), 2)294 assert len(captured) == 2295296 app.use_x_sendfile = False297 with app.test_request_context():298 with catch_warnings() as captured:299 f = StringIO('Test')300 rv = flask.send_file(f)301 rv.direct_passthrough = False301 self.assert_equal(rv.data, b'Test')302 self.assert_equal(rv.mimetype, 'application/octet-stream')302 assert rv.data == b'Test'303 assert rv.mimetype == 'application/octet-stream'304 rv.close()305 # etags305 self.assert_equal(len(captured), 1)306 assert len(captured) == 1307 with catch_warnings() as captured:308 class PyStringIO(object):309 def __init__(self, *args, **kwargs):310 self._io = StringIO(*args, **kwargs)
2 unmodified lines
313 f = PyStringIO('Test')314 f.name = 'test.txt'315 rv = flask.send_file(f)316 rv.direct_passthrough = False316 self.assert_equal(rv.data, b'Test')317 self.assert_equal(rv.mimetype, 'text/plain')317 assert rv.data == b'Test'318 assert rv.mimetype == 'text/plain'319 rv.close()320 # attachment_filename and etags320 self.assert_equal(len(captured), 3)321 assert len(captured) == 3322 with catch_warnings() as captured:323 f = StringIO('Test')324 rv = flask.send_file(f, mimetype='text/plain')325 rv.direct_passthrough = False325 self.assert_equal(rv.data, b'Test')326 self.assert_equal(rv.mimetype, 'text/plain')326 assert rv.data == b'Test'327 assert rv.mimetype == 'text/plain'328 rv.close()329 # etags329 self.assert_equal(len(captured), 1)330 assert len(captured) == 1331332 app.use_x_sendfile = True333 with catch_warnings() as captured:334 with app.test_request_context():335 f = StringIO('Test')336 rv = flask.send_file(f)336 self.assert_not_in('x-sendfile', rv.headers)337 assert 'x-sendfile' not in rv.headers338 rv.close()339 # etags339 self.assert_equal(len(captured), 1)340 assert len(captured) == 1341342 def test_attachment(self):343 app = flask.Flask(__name__)344 with catch_warnings() as captured:345 with app.test_request_context():346 f = open(os.path.join(app.root_path, 'static/index.html'))347 rv = flask.send_file(f, as_attachment=True)348 value, options = parse_options_header(rv.headers['Content-Disposition'])348 self.assert_equal(value, 'attachment')349 assert value == 'attachment'350 rv.close()351 # mimetypes + etag351 self.assert_equal(len(captured), 2)352 assert len(captured) == 2353354 with app.test_request_context():354 self.assert_equal(options['filename'], 'index.html')355 assert options['filename'] == 'index.html'356 rv = flask.send_file('static/index.html', as_attachment=True)357 value, options = parse_options_header(rv.headers['Content-Disposition'])357 self.assert_equal(value, 'attachment')358 self.assert_equal(options['filename'], 'index.html')358 assert value == 'attachment'359 assert options['filename'] == 'index.html'360 rv.close()361362 with app.test_request_context():363 rv = flask.send_file(StringIO('Test'), as_attachment=True,364 attachment_filename='index.txt',365 add_etags=False)365 self.assert_equal(rv.mimetype, 'text/plain')366 assert rv.mimetype == 'text/plain'367 value, options = parse_options_header(rv.headers['Content-Disposition'])367 self.assert_equal(value, 'attachment')368 self.assert_equal(options['filename'], 'index.txt')368 assert value == 'attachment'369 assert options['filename'] == 'index.txt'370 rv.close()371372 def test_static_file(self):373 app = flask.Flask(__name__)
1 unmodified line
375 with app.test_request_context():376 # Test with static file handler.377 rv = app.send_static_file('index.html')378 cc = parse_cache_control_header(rv.headers['Cache-Control'])378 self.assert_equal(cc.max_age, 12 * 60 * 60)379 assert cc.max_age == 12 * 60 * 60380 rv.close()381 # Test again with direct use of send_file utility.382 rv = flask.send_file('static/index.html')383 cc = parse_cache_control_header(rv.headers['Cache-Control'])383 self.assert_equal(cc.max_age, 12 * 60 * 60)384 assert cc.max_age == 12 * 60 * 60385 rv.close()386 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600387 with app.test_request_context():388 # Test with static file handler.389 rv = app.send_static_file('index.html')390 cc = parse_cache_control_header(rv.headers['Cache-Control'])390 self.assert_equal(cc.max_age, 3600)391 assert cc.max_age == 3600392 rv.close()393 # Test again with direct use of send_file utility.394 rv = flask.send_file('static/index.html')395 cc = parse_cache_control_header(rv.headers['Cache-Control'])395 self.assert_equal(cc.max_age, 3600)396 assert cc.max_age == 3600397 rv.close()398 class StaticFileApp(flask.Flask):399 def get_send_file_max_age(self, filename):400 return 10
1 unmodified line
402 with app.test_request_context():403 # Test with static file handler.404 rv = app.send_static_file('index.html')405 cc = parse_cache_control_header(rv.headers['Cache-Control'])405 self.assert_equal(cc.max_age, 10)406 assert cc.max_age == 10407 rv.close()408 # Test again with direct use of send_file utility.409 rv = flask.send_file('static/index.html')410 cc = parse_cache_control_header(rv.headers['Cache-Control'])410 self.assert_equal(cc.max_age, 10)411 assert cc.max_age == 10412 rv.close()413414 def test_send_from_directory(self):415 app = flask.Flask(__name__)
2 unmodified lines
418 'test_apps', 'subdomaintestmodule')419 with app.test_request_context():420 rv = flask.send_from_directory('static', 'hello.txt')421 rv.direct_passthrough = False421 self.assert_equal(rv.data.strip(), b'Hello Subdomain')422 assert rv.data.strip() == b'Hello Subdomain'423 rv.close()424425426class TestLogging(TestFlask):427428 def test_logger_cache(self):429 app = flask.Flask(__name__)430 logger1 = app.logger430 self.assert_true(app.logger is logger1)431 self.assert_equal(logger1.name, __name__)431 assert app.logger is logger1432 assert logger1.name == __name__433 app.logger_name = __name__ + '/test_logger_cache'433 self.assert_true(app.logger is not logger1)434 assert app.logger is not logger1435436 def test_debug_log(self):437 app = flask.Flask(__name__)438 app.debug = True
11 unmodified lines
450 with app.test_client() as c:451 with catch_stderr() as err:452 c.get('/')453 out = err.getvalue()453 self.assert_in('WARNING in test_helpers [', out)454 self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out)455 self.assert_in('the standard library is dead', out)456 self.assert_in('this is a debug statement', out)454 assert 'WARNING in test_helpers [' in out455 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out456 assert 'the standard library is dead' in out457 assert 'this is a debug statement' in out458459 with catch_stderr() as err:460 try:461 c.get('/exc')462 except ZeroDivisionError:463 pass464 else:464 self.assert_true(False, 'debug log ate the exception')465 assert False, 'debug log ate the exception'466467 def test_debug_log_override(self):468 app = flask.Flask(__name__)469 app.debug = True470 app.logger_name = 'flask_tests/test_debug_log_override'471 app.logger.level = 10471 self.assert_equal(app.logger.level, 10)472 assert app.logger.level == 10473474 def test_exception_logging(self):475 out = StringIO()476 app = flask.Flask(__name__)
5 unmodified lines
482 def index():483 1 // 0484485 rv = app.test_client().get('/')485 self.assert_equal(rv.status_code, 500)486 self.assert_in(b'Internal Server Error', rv.data)486 assert rv.status_code == 500487 assert b'Internal Server Error' in rv.data488489 err = out.getvalue()489 self.assert_in('Exception on / [GET]', err)490 self.assert_in('Traceback (most recent call last):', err)491 self.assert_in('1 // 0', err)492 self.assert_in('ZeroDivisionError:', err)490 assert 'Exception on / [GET]' in err491 assert 'Traceback (most recent call last):' in err492 assert '1 // 0' in err493 assert 'ZeroDivisionError:' in err494495 def test_processor_exceptions(self):496 app = flask.Flask(__name__)497 app.config['LOGGER_HANDLER_POLICY'] = 'never'
13 unmodified lines
511 def internal_server_error(e):512 return 'Hello Server Error', 500513 for trigger in 'before', 'after':514 rv = app.test_client().get('/')514 self.assert_equal(rv.status_code, 500)515 self.assert_equal(rv.data, b'Hello Server Error')515 assert rv.status_code == 500516 assert rv.data == b'Hello Server Error'517518 def test_url_for_with_anchor(self):519 app = flask.Flask(__name__)520 @app.route('/')521 def index():522 return '42'523 with app.test_request_context():523 self.assert_equal(flask.url_for('index', _anchor='x y'),524 '/#x%20y')524 assert flask.url_for('index', _anchor='x y') == '/#x%20y'525526 def test_url_for_with_scheme(self):527 app = flask.Flask(__name__)528 @app.route('/')529 def index():530 return '42'531 with app.test_request_context():532 self.assert_equal(flask.url_for('index',533 _external=True,534 _scheme='https'),535 'https://localhost/')532 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'533534 def test_url_for_with_scheme_not_external(self):535 app = flask.Flask(__name__)536 @app.route('/')537 def index():538 return '42'539 with app.test_request_context():543 self.assert_raises(ValueError,540 pytest.raises(ValueError,541 flask.url_for,542 'index',543 _scheme='https')544
15 unmodified lines
560 app.add_url_rule('/myview/create', methods=['POST'],561 view_func=myview)562563 with app.test_request_context():567 self.assert_equal(flask.url_for('myview', _method='GET'),568 '/myview/')569 self.assert_equal(flask.url_for('myview', id=42, _method='GET'),570 '/myview/42')571 self.assert_equal(flask.url_for('myview', _method='POST'),572 '/myview/create')564 assert flask.url_for('myview', _method='GET') == '/myview/'565 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'566 assert flask.url_for('myview', _method='POST') == '/myview/create'567568569class TestNoImports(TestFlask):570 """Test Flasks are created without import.
9 unmodified lines
580 def test_name_with_import_error(self):581 try:582 flask.Flask('importerror')583 except NotImplementedError:590 self.fail('Flask(import_name) is importing import_name.')584 assert False, 'Flask(import_name) is importing import_name.'585586587class TestStreaming(TestFlask):588
8 unmodified lines
597 yield '!'598 return flask.Response(flask.stream_with_context(generate()))599 c = app.test_client()600 rv = c.get('/?name=World')607 self.assert_equal(rv.data, b'Hello World!')601 assert rv.data == b'Hello World!'602603 def test_streaming_with_context_as_decorator(self):604 app = flask.Flask(__name__)605 app.testing = True
6 unmodified lines
612 yield '!'613 return flask.Response(generate())614 c = app.test_client()615 rv = c.get('/?name=World')622 self.assert_equal(rv.data, b'Hello World!')616 assert rv.data == b'Hello World!'617618 def test_streaming_with_context_and_custom_close(self):619 app = flask.Flask(__name__)620 app.testing = True
17 unmodified lines
638 return flask.Response(flask.stream_with_context(639 Wrapper(generate())))640 c = app.test_client()641 rv = c.get('/?name=World')648 self.assert_equal(rv.data, b'Hello World!')649 self.assert_equal(called, [42])642 assert rv.data == b'Hello World!'643 assert called == [42]644645646def suite():647 suite = unittest.TestSuite()
7 unmodified lines
modified:tests/test_regression.py+5 added-5 removed
67 unmodified lines
6869 def fire():70 with app.test_client() as c:71 rv = c.get('/')72 self.assert_equal(rv.status_code, 200)73 self.assert_equal(rv.data, b'<h1>42</h1>')72 assert rv.status_code == 20073 assert rv.data == b'<h1>42</h1>'7475 # Trigger caches76 fire()77
5 unmodified lines
83 fire()8485 def test_safe_join_toplevel_pardir(self):86 from flask.helpers import safe_join87 with self.assert_raises(NotFound):87 with pytest.raises(NotFound):88 safe_join('/foo', '..')899091class TestException(TestFlask):
17 unmodified lines
109 raise Foo()110111 with app.test_client() as c:112 rv = c.get('/')113 self.assert_equal(rv.headers['Location'], 'http://localhost/test')113 assert rv.headers['Location'] == 'http://localhost/test'114 rv = c.get('/test')115 self.assert_equal(rv.data, b'42')115 assert rv.data == b'42'
modified:tests/test_reqctx.py+45 added-50 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import unittest16try:17 from greenlet import greenlet
12 unmodified lines
30 buffer.append(exception)3132 ctx = app.test_request_context()33 ctx.push()32 self.assert_equal(buffer, [])34 assert buffer == []35 ctx.pop()34 self.assert_equal(buffer, [None])36 assert buffer == [None]3738 def test_teardown_with_previous_exception(self):39 buffer = []40 app = flask.Flask(__name__)
6 unmodified lines
47 except Exception:48 pass4950 with app.test_request_context():49 self.assert_equal(buffer, [])50 self.assert_equal(buffer, [None])51 assert buffer == []52 assert buffer == [None]5354 def test_proper_test_request_context(self):55 app = flask.Flask(__name__)56 app.config.update(
8 unmodified lines
65 def sub():66 return None6768 with app.test_request_context('/'):67 self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')69 assert flask.url_for('index', _external=True) == \70 'http://localhost.localdomain:5000/'7172 with app.test_request_context('/'):70 self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')73 assert flask.url_for('sub', _external=True) == \74 'http://foo.localhost.localdomain:5000/'7576 try:77 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):78 pass75 except Exception as e:76 self.assert_true(isinstance(e, ValueError))77 self.assert_equal(str(e), "the server name provided " +78 "('localhost.localdomain:5000') does not match the " + \79 "server name from the WSGI environment ('localhost')")8081 try:82 app.config.update(SERVER_NAME='localhost')83 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):84 pass79 except ValueError as e:86 raise ValueError(87 "No ValueError exception should have been raised \"%s\"" % e80 assert str(e) == (81 "the server name provided "82 "('localhost.localdomain:5000') does not match the "83 "server name from the WSGI environment ('localhost')"84 )8590 try:91 app.config.update(SERVER_NAME='localhost:80')92 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):93 pass86 app.config.update(SERVER_NAME='localhost')87 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):88 pass94 except ValueError as e:95 raise ValueError(96 "No ValueError exception should have been raised \"%s\"" % e97 )8990 app.config.update(SERVER_NAME='localhost:80')91 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):92 pass9394 def test_context_binding(self):95 app = flask.Flask(__name__)96 @app.route('/')97 def index():
2 unmodified lines
100 def meh():101 return flask.request.url102103 with app.test_request_context('/?name=World'):109 self.assert_equal(index(), 'Hello World!')104 assert index() == 'Hello World!'105 with app.test_request_context('/meh'):111 self.assert_equal(meh(), 'http://localhost/meh')112 self.assert_true(flask._request_ctx_stack.top is None)106 assert meh() == 'http://localhost/meh'107 assert flask._request_ctx_stack.top is None108109 def test_context_test(self):110 app = flask.Flask(__name__)116 self.assert_false(flask.request)117 self.assert_false(flask.has_request_context())111 assert not flask.request112 assert not flask.has_request_context()113 ctx = app.test_request_context()114 ctx.push()115 try:121 self.assert_true(flask.request)122 self.assert_true(flask.has_request_context())116 assert flask.request117 assert flask.has_request_context()118 finally:119 ctx.pop()120121 def test_manual_context_binding(self):
3 unmodified lines
125 return 'Hello %s!' % flask.request.args['name']126127 ctx = app.test_request_context('/?name=World')128 ctx.push()134 self.assert_equal(index(), 'Hello World!')129 assert index() == 'Hello World!'130 ctx.pop()131 try:132 index()133 except RuntimeError:134 pass135 else:141 self.assert_true(0, 'expected runtime error')136 assert 0, 'expected runtime error'137138 def test_greenlet_context_copying(self):139 app = flask.Flask(__name__)140 greenlets = []
1 unmodified line
142 @app.route('/')143 def index():144 reqctx = flask._request_ctx_stack.top.copy()145 def g():151 self.assert_false(flask.request)152 self.assert_false(flask.current_app)146 assert not flask.request147 assert not flask.current_app148 with reqctx:154 self.assert_true(flask.request)155 self.assert_equal(flask.current_app, app)156 self.assert_equal(flask.request.path, '/')157 self.assert_equal(flask.request.args['foo'], 'bar')158 self.assert_false(flask.request)149 assert flask.request150 assert flask.current_app == app151 assert flask.request.path == '/'152 assert flask.request.args['foo'] == 'bar'153 assert not flask.request154 return 42155 greenlets.append(greenlet(g))156 return 'Hello World!'157158 rv = app.test_client().get('/?foo=bar')164 self.assert_equal(rv.data, b'Hello World!')159 assert rv.data == b'Hello World!'160161 result = greenlets[0].run()167 self.assert_equal(result, 42)162 assert result == 42163164 def test_greenlet_context_copying_api(self):165 app = flask.Flask(__name__)166 greenlets = []
2 unmodified lines
169 def index():170 reqctx = flask._request_ctx_stack.top.copy()171 @flask.copy_current_request_context172 def g():178 self.assert_true(flask.request)179 self.assert_equal(flask.current_app, app)180 self.assert_equal(flask.request.path, '/')181 self.assert_equal(flask.request.args['foo'], 'bar')173 assert flask.request174 assert flask.current_app == app175 assert flask.request.path == '/'176 assert flask.request.args['foo'] == 'bar'177 return 42178 greenlets.append(greenlet(g))179 return 'Hello World!'180181 rv = app.test_client().get('/?foo=bar')187 self.assert_equal(rv.data, b'Hello World!')182 assert rv.data == b'Hello World!'183184 result = greenlets[0].run()190 self.assert_equal(result, 42)185 assert result == 42186187 # Disable test if we don't have greenlets available188 if greenlet is None:189 test_greenlet_context_copying = None
7 unmodified lines
modified:tests/test_signals.py+16 added-17 removed
40 unmodified lines
4142 flask.template_rendered.connect(record, app)43 try:44 app.test_client().get('/')45 self.assert_equal(len(recorded), 1)45 assert len(recorded) == 146 template, context = recorded[0]47 self.assert_equal(template.name, 'simple_template.html')48 self.assert_equal(context['whiskey'], 42)47 assert template.name == 'simple_template.html'48 assert context['whiskey'] == 4249 finally:50 flask.template_rendered.disconnect(record, app)5152 def test_request_signals(self):
3 unmodified lines
56 def before_request_signal(sender):57 calls.append('before-signal')5859 def after_request_signal(sender, response):60 self.assert_equal(response.data, b'stuff')60 assert response.data == b'stuff'61 calls.append('after-signal')6263 @app.before_request64 def before_request_handler():
14 unmodified lines
79 flask.request_finished.connect(after_request_signal, app)8081 try:82 rv = app.test_client().get('/')83 self.assert_equal(rv.data, b'stuff')83 assert rv.data == b'stuff'8485 self.assert_equal(calls, ['before-signal', 'before-handler',86 'handler', 'after-handler',87 'after-signal'])85 assert calls == ['before-signal', 'before-handler', 'handler',86 'after-handler', 'after-signal']87 finally:88 flask.request_started.disconnect(before_request_signal, app)89 flask.request_finished.disconnect(after_request_signal, app)90
9 unmodified lines
100 recorded.append(exception)101102 flask.got_request_exception.connect(record, app)103 try:105 self.assert_equal(app.test_client().get('/').status_code, 500)106 self.assert_equal(len(recorded), 1)107 self.assert_true(isinstance(recorded[0], ZeroDivisionError))104 assert app.test_client().get('/').status_code == 500105 assert len(recorded) == 1106 assert isinstance(recorded[0], ZeroDivisionError)107 finally:108 flask.got_request_exception.disconnect(record, app)109110 def test_appcontext_signals(self):
14 unmodified lines
125 flask.appcontext_popped.connect(record_pop, app)126 try:127 with app.test_client() as c:128 rv = c.get('/')130 self.assert_equal(rv.data, b'Hello')131 self.assert_equal(recorded, ['push'])132 self.assert_equal(recorded, ['push', 'pop'])129 assert rv.data == b'Hello'130 assert recorded == ['push']131 assert recorded == ['push', 'pop']132 finally:133 flask.appcontext_pushed.disconnect(record_push, app)134 flask.appcontext_popped.disconnect(record_pop, app)135
15 unmodified lines
151 try:152 client = app.test_client()153 with client.session_transaction():154 client.get('/')156 self.assert_equal(len(recorded), 1)155 assert len(recorded) == 1156 message, category = recorded[0]158 self.assert_equal(message, 'This is a flash message')159 self.assert_equal(category, 'notice')157 assert message == 'This is a flash message'158 assert category == 'notice'159 finally:160 flask.message_flashed.disconnect(record, app)
modified:tests/test_subclassing.py+3 added-3 removed
31 unmodified lines
32 def index():33 1 // 03435 rv = app.test_client().get('/')36 self.assert_equal(rv.status_code, 500)37 self.assert_in(b'Internal Server Error', rv.data)36 assert rv.status_code == 50037 assert b'Internal Server Error' in rv.data3839 err = out.getvalue()40 self.assert_equal(err, '')40 assert err == ''414243def suite():44 suite = unittest.TestSuite()
2 unmodified lines
modified:tests/test_templating.py+63 added-65 removed
26 unmodified lines
27 @app.route('/')28 def index():29 return flask.render_template('context_template.html', value=23)30 rv = app.test_client().get('/')31 self.assert_equal(rv.data, b'<p>23|42')31 assert rv.data == b'<p>23|42'3233 def test_original_win(self):34 app = flask.Flask(__name__)35 @app.route('/')36 def index():37 return flask.render_template_string('{{ config }}', config=42)38 rv = app.test_client().get('/')39 self.assert_equal(rv.data, b'42')39 assert rv.data == b'42'4041 def test_request_less_rendering(self):42 app = flask.Flask(__name__)43 app.config['WORLD_NAME'] = 'Special World'
3 unmodified lines
4748 with app.app_context():49 rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '50 '{{ foo }}')51 self.assert_equal(rv, 'Hello Special World 42')51 assert rv == 'Hello Special World 42'5253 def test_standard_context(self):54 app = flask.Flask(__name__)55 app.secret_key = 'development key'
7 unmodified lines
63 {{ config.DEBUG }}64 {{ session.test }}65 ''')66 rv = app.test_client().get('/?foo=42')67 self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha'])67 assert rv.data.split() == [b'42', b'23', b'False', b'aha']6869 def test_escaping(self):70 text = '<p>Hello World!'71 app = flask.Flask(__name__)
1 unmodified line
73 def index():74 return flask.render_template('escaping_template.html', text=text,75 html=flask.Markup(text))76 lines = app.test_client().get('/').data.splitlines()77 self.assert_equal(lines, [77 assert lines == [78 b'&lt;p&gt;Hello World!',79 b'<p>Hello World!',80 b'<p>Hello World!',81 b'<p>Hello World!',82 b'&lt;p&gt;Hello World!',83 b'<p>Hello World!'84 ])84 ]8586 def test_no_escaping(self):87 app = flask.Flask(__name__)88 with app.test_request_context():89 self.assert_equal(flask.render_template_string('{{ foo }}',90 foo='<test>'), '<test>')91 self.assert_equal(flask.render_template('mail.txt', foo='<test>'),92 '<test> Mail')89 assert flask.render_template_string(90 '{{ foo }}', foo='<test>') == '<test>'91 assert flask.render_template('mail.txt', foo='<test>') == \92 '<test> Mail'9394 def test_macros(self):95 app = flask.Flask(__name__)96 with app.test_request_context():97 macro = flask.get_template_attribute('_macro.html', 'hello')98 self.assert_equal(macro('World'), 'Hello World!')98 assert macro('World') == 'Hello World!'99100 def test_template_filter(self):101 app = flask.Flask(__name__)102 @app.template_filter()103 def my_reverse(s):104 return s[::-1]105 self.assert_in('my_reverse', app.jinja_env.filters.keys())106 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)107 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')105 assert 'my_reverse' in app.jinja_env.filters.keys()106 assert app.jinja_env.filters['my_reverse'] == my_reverse107 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'108109 def test_add_template_filter(self):110 app = flask.Flask(__name__)111 def my_reverse(s):112 return s[::-1]113 app.add_template_filter(my_reverse)114 self.assert_in('my_reverse', app.jinja_env.filters.keys())115 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)116 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')114 assert 'my_reverse' in app.jinja_env.filters.keys()115 assert app.jinja_env.filters['my_reverse'] == my_reverse116 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'117118 def test_template_filter_with_name(self):119 app = flask.Flask(__name__)120 @app.template_filter('strrev')121 def my_reverse(s):122 return s[::-1]123 self.assert_in('strrev', app.jinja_env.filters.keys())124 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)125 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')123 assert 'strrev' in app.jinja_env.filters.keys()124 assert app.jinja_env.filters['strrev'] == my_reverse125 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'126127 def test_add_template_filter_with_name(self):128 app = flask.Flask(__name__)129 def my_reverse(s):130 return s[::-1]131 app.add_template_filter(my_reverse, 'strrev')132 self.assert_in('strrev', app.jinja_env.filters.keys())133 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)134 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')132 assert 'strrev' in app.jinja_env.filters.keys()133 assert app.jinja_env.filters['strrev'] == my_reverse134 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'135136 def test_template_filter_with_template(self):137 app = flask.Flask(__name__)138 @app.template_filter()
2 unmodified lines
141 @app.route('/')142 def index():143 return flask.render_template('template_filter.html', value='abcd')144 rv = app.test_client().get('/')145 self.assert_equal(rv.data, b'dcba')145 assert rv.data == b'dcba'146147 def test_add_template_filter_with_template(self):148 app = flask.Flask(__name__)149 def super_reverse(s):
2 unmodified lines
152 @app.route('/')153 def index():154 return flask.render_template('template_filter.html', value='abcd')155 rv = app.test_client().get('/')156 self.assert_equal(rv.data, b'dcba')156 assert rv.data == b'dcba'157158 def test_template_filter_with_name_and_template(self):159 app = flask.Flask(__name__)160 @app.template_filter('super_reverse')
2 unmodified lines
163 @app.route('/')164 def index():165 return flask.render_template('template_filter.html', value='abcd')166 rv = app.test_client().get('/')167 self.assert_equal(rv.data, b'dcba')167 assert rv.data == b'dcba'168169 def test_add_template_filter_with_name_and_template(self):170 app = flask.Flask(__name__)171 def my_reverse(s):
2 unmodified lines
174 @app.route('/')175 def index():176 return flask.render_template('template_filter.html', value='abcd')177 rv = app.test_client().get('/')178 self.assert_equal(rv.data, b'dcba')178 assert rv.data == b'dcba'179180 def test_template_test(self):181 app = flask.Flask(__name__)182 @app.template_test()183 def boolean(value):184 return isinstance(value, bool)185 self.assert_in('boolean', app.jinja_env.tests.keys())186 self.assert_equal(app.jinja_env.tests['boolean'], boolean)187 self.assert_true(app.jinja_env.tests['boolean'](False))185 assert 'boolean' in app.jinja_env.tests.keys()186 assert app.jinja_env.tests['boolean'] == boolean187 assert app.jinja_env.tests['boolean'](False)188189 def test_add_template_test(self):190 app = flask.Flask(__name__)191 def boolean(value):192 return isinstance(value, bool)193 app.add_template_test(boolean)194 self.assert_in('boolean', app.jinja_env.tests.keys())195 self.assert_equal(app.jinja_env.tests['boolean'], boolean)196 self.assert_true(app.jinja_env.tests['boolean'](False))194 assert 'boolean' in app.jinja_env.tests.keys()195 assert app.jinja_env.tests['boolean'] == boolean196 assert app.jinja_env.tests['boolean'](False)197198 def test_template_test_with_name(self):199 app = flask.Flask(__name__)200 @app.template_test('boolean')201 def is_boolean(value):202 return isinstance(value, bool)203 self.assert_in('boolean', app.jinja_env.tests.keys())204 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)205 self.assert_true(app.jinja_env.tests['boolean'](False))203 assert 'boolean' in app.jinja_env.tests.keys()204 assert app.jinja_env.tests['boolean'] == is_boolean205 assert app.jinja_env.tests['boolean'](False)206207 def test_add_template_test_with_name(self):208 app = flask.Flask(__name__)209 def is_boolean(value):210 return isinstance(value, bool)211 app.add_template_test(is_boolean, 'boolean')212 self.assert_in('boolean', app.jinja_env.tests.keys())213 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)214 self.assert_true(app.jinja_env.tests['boolean'](False))212 assert 'boolean' in app.jinja_env.tests.keys()213 assert app.jinja_env.tests['boolean'] == is_boolean214 assert app.jinja_env.tests['boolean'](False)215216 def test_template_test_with_template(self):217 app = flask.Flask(__name__)218 @app.template_test()
2 unmodified lines
221 @app.route('/')222 def index():223 return flask.render_template('template_test.html', value=False)224 rv = app.test_client().get('/')225 self.assert_in(b'Success!', rv.data)225 assert b'Success!' in rv.data226227 def test_add_template_test_with_template(self):228 app = flask.Flask(__name__)229 def boolean(value):
2 unmodified lines
232 @app.route('/')233 def index():234 return flask.render_template('template_test.html', value=False)235 rv = app.test_client().get('/')236 self.assert_in(b'Success!', rv.data)236 assert b'Success!' in rv.data237238 def test_template_test_with_name_and_template(self):239 app = flask.Flask(__name__)240 @app.template_test('boolean')
2 unmodified lines
243 @app.route('/')244 def index():245 return flask.render_template('template_test.html', value=False)246 rv = app.test_client().get('/')247 self.assert_in(b'Success!', rv.data)247 assert b'Success!' in rv.data248249 def test_add_template_test_with_name_and_template(self):250 app = flask.Flask(__name__)251 def is_boolean(value):
2 unmodified lines
254 @app.route('/')255 def index():256 return flask.render_template('template_test.html', value=False)257 rv = app.test_client().get('/')258 self.assert_in(b'Success!', rv.data)258 assert b'Success!' in rv.data259260 def test_add_template_global(self):261 app = flask.Flask(__name__)262 @app.template_global()263 def get_stuff():264 return 42265 self.assert_in('get_stuff', app.jinja_env.globals.keys())266 self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff)267 self.assert_true(app.jinja_env.globals['get_stuff'](), 42)265 assert 'get_stuff' in app.jinja_env.globals.keys()266 assert app.jinja_env.globals['get_stuff'] == get_stuff267 assert app.jinja_env.globals['get_stuff'](), 42268 with app.app_context():269 rv = flask.render_template_string('{{ get_stuff() }}')270 self.assert_equal(rv, '42')270 assert rv == '42'271272 def test_custom_template_loader(self):273 class MyFlask(flask.Flask):274 def create_global_jinja_loader(self):
4 unmodified lines
279 def index():280 return flask.render_template('index.html')281 c = app.test_client()282 rv = c.get('/')283 self.assert_equal(rv.data, b'Hello Custom World!')283 assert rv.data == b'Hello Custom World!'284285 def test_iterable_loader(self):286 app = flask.Flask(__name__)287 @app.context_processor
7 unmodified lines
295 'context_template.html'],296 value=23)297298 rv = app.test_client().get('/')299 self.assert_equal(rv.data, b'<h1>Jameson</h1>')299 assert rv.data == b'<h1>Jameson</h1>'300301 def test_templates_auto_reload(self):302 app = flask.Flask(__name__)303 self.assert_true(app.config['TEMPLATES_AUTO_RELOAD'])304 self.assert_true(app.jinja_env.auto_reload)303 assert app.config['TEMPLATES_AUTO_RELOAD']304 assert app.jinja_env.auto_reload305 app = flask.Flask(__name__)306 app.config['TEMPLATES_AUTO_RELOAD'] = False307 self.assert_false(app.jinja_env.auto_reload)307 assert not app.jinja_env.auto_reload308309 def test_template_loader_debugging(self):310 from blueprintapp import app311
1 unmodified line
313 class _TestHandler(logging.Handler):314 def handle(x, record):315 called.append(True)316 text = str(record.msg)317 self.assert_('1: trying loader of application '318 '"blueprintapp"' in text)319 self.assert_('2: trying loader of blueprint "admin" '320 '(blueprintapp.apps.admin)' in text)321 self.assert_('trying loader of blueprint "frontend" '322 '(blueprintapp.apps.frontend)' in text)323 self.assert_('Error: the template could not be found' in text)324 self.assert_('looked up from an endpoint that belongs to '325 'the blueprint "frontend"' in text)326 self.assert_(317 assert '1: trying loader of application "blueprintapp"' in text318 assert ('2: trying loader of blueprint "admin" '319 '(blueprintapp.apps.admin)') in text320 assert ('trying loader of blueprint "frontend" '321 '(blueprintapp.apps.frontend)') in text322 assert 'Error: the template could not be found' in text323 assert ('looked up from an endpoint that belongs to '324 'the blueprint "frontend"') in text325 assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text327 'See http://flask.pocoo.org/docs/blueprints/#templates' in text)326327 with app.test_client() as c:328 try:329 old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']
3 unmodified lines
333334 try:335 c.get('/missing')336 except TemplateNotFound as e:339 self.assert_('missing_template.html' in str(e))337 assert 'missing_template.html' in str(e)338 else:339 self.fail('Expected template not found exception.')340 finally:341 app.logger.handlers[:] = old_handlers342 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting343346 self.assert_equal(len(called), 1)344 assert len(called) == 1345346347def suite():348 suite = unittest.TestSuite()
2 unmodified lines
modified:tests/test_testing.py+37 added-37 removed
26 unmodified lines
27 def index():28 return flask.request.url2930 ctx = app.test_request_context()31 self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/')31 assert ctx.request.url == 'http://example.com:1234/foo/'32 with app.test_client() as c:33 rv = c.get('/')34 self.assert_equal(rv.data, b'http://example.com:1234/foo/')34 assert rv.data == b'http://example.com:1234/foo/'3536 def test_environ_defaults(self):37 app = flask.Flask(__name__)38 app.testing = True
1 unmodified line
40 def index():41 return flask.request.url4243 ctx = app.test_request_context()44 self.assert_equal(ctx.request.url, 'http://localhost/')44 assert ctx.request.url == 'http://localhost/'45 with app.test_client() as c:46 rv = c.get('/')47 self.assert_equal(rv.data, b'http://localhost/')47 assert rv.data == b'http://localhost/'4849 def test_redirect_keep_session(self):50 app = flask.Flask(__name__)51 app.secret_key = 'testing'
36 unmodified lines
88 return text_type(flask.session['foo'])8990 with app.test_client() as c:91 with c.session_transaction() as sess:92 self.assert_equal(len(sess), 0)92 assert len(sess) == 093 sess['foo'] = [42]94 self.assert_equal(len(sess), 1)94 assert len(sess) == 195 rv = c.get('/')96 self.assert_equal(rv.data, b'[42]')96 assert rv.data == b'[42]'97 with c.session_transaction() as sess:98 self.assert_equal(len(sess), 1)99 self.assert_equal(sess['foo'], [42])98 assert len(sess) == 199 assert sess['foo'] == [42]100101 def test_session_transactions_no_null_sessions(self):102 app = flask.Flask(__name__)103 app.testing = True
2 unmodified lines
106 try:107 with c.session_transaction() as sess:108 pass109 except RuntimeError as e:110 self.assert_in('Session backend did not open a session', str(e))110 assert 'Session backend did not open a session' in str(e)111 else:112 self.fail('Expected runtime error')112 assert False, 'Expected runtime error'113114 def test_session_transactions_keep_context(self):115 app = flask.Flask(__name__)116 app.testing = True
1 unmodified line
118119 with app.test_client() as c:120 rv = c.get('/')121 req = flask.request._get_current_object()122 self.assert_true(req is not None)122 assert req is not None123 with c.session_transaction():124 self.assert_true(req is flask.request._get_current_object())124 assert req is flask.request._get_current_object()125126 def test_session_transaction_needs_cookies(self):127 app = flask.Flask(__name__)128 app.testing = True
1 unmodified line
130 try:131 with c.session_transaction() as s:132 pass133 except RuntimeError as e:134 self.assert_in('cookies', str(e))134 assert 'cookies' in str(e)135 else:136 self.fail('Expected runtime error')136 assert False, 'Expected runtime error'137138 def test_test_client_context_binding(self):139 app = flask.Flask(__name__)140 app.config['LOGGER_HANDLER_POLICY'] = 'never'
7 unmodified lines
148 1 // 0149150 with app.test_client() as c:151 resp = c.get('/')152 self.assert_equal(flask.g.value, 42)153 self.assert_equal(resp.data, b'Hello World!')154 self.assert_equal(resp.status_code, 200)152 assert flask.g.value == 42153 assert resp.data == b'Hello World!'154 assert resp.status_code == 200155156 resp = c.get('/other')157 self.assert_false(hasattr(flask.g, 'value'))158 self.assert_in(b'Internal Server Error', resp.data)159 self.assert_equal(resp.status_code, 500)157 assert not hasattr(flask.g, 'value')158 assert b'Internal Server Error' in resp.data159 assert resp.status_code == 500160 flask.g.value = 23161162 try:163 flask.g.value
6 unmodified lines
170 app = flask.Flask(__name__)171 c = app.test_client()172173 with c:174 self.assert_equal(c.get('/').status_code, 404)174 assert c.get('/').status_code == 404175176 with c:177 self.assert_equal(c.get('/').status_code, 404)177 assert c.get('/').status_code == 404178179 def test_test_client_calls_teardown_handlers(self):180 app = flask.Flask(__name__)181 called = []
1 unmodified line
183 def remember(error):184 called.append(error)185186 with app.test_client() as c:187 self.assert_equal(called, [])187 assert called == []188 c.get('/')189 self.assert_equal(called, [])190 self.assert_equal(called, [None])189 assert called == []190 assert called == [None]191192 del called[:]193 with app.test_client() as c:194 self.assert_equal(called, [])194 assert called == []195 c.get('/')196 self.assert_equal(called, [])196 assert called == []197 c.get('/')198 self.assert_equal(called, [None])199 self.assert_equal(called, [None, None])198 assert called == [None]199 assert called == [None, None]200201 def test_full_url_request(self):202 app = flask.Flask(__name__)203 app.testing = True
3 unmodified lines
207 return 'x'208209 with app.test_client() as c:210 rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})211 self.assert_equal(rv.status_code, 200)212 self.assert_true('gin' in flask.request.form)213 self.assert_true('vodka' in flask.request.args)211 assert rv.status_code == 200212 assert 'gin' in flask.request.form213 assert 'vodka' in flask.request.args214215216class TestSubdomain(TestFlask):217
22 unmodified lines
240241 url = flask.url_for('view', company_id='xxx')242 response = client.get(url)243244 self.assert_equal(200, response.status_code)245 self.assert_equal(b'xxx', response.data)244 assert 200 == response.status_code245 assert b'xxx' == response.data246247248 def test_nosubdomain(self, app, client):249 @app.route('/<company_id>')
2 unmodified lines
252253 url = flask.url_for('view', company_id='xxx')254 response = client.get(url)255256 self.assert_equal(200, response.status_code)257 self.assert_equal(b'xxx', response.data)256 assert 200 == response.status_code257 assert b'xxx' == response.data
modified:tests/test_views.py+17 added-15 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import flask.views16import unittest17from tests import TestFlask
3 unmodified lines
2122 def common_test(self, app):23 c = app.test_client()2423 self.assert_equal(c.get('/').data, b'GET')24 self.assert_equal(c.post('/').data, b'POST')25 self.assert_equal(c.put('/').status_code, 405)25 assert c.get('/').data == b'GET'26 assert c.post('/').data == b'POST'27 assert c.put('/').status_code == 40528 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])29 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']3031 def test_basic_view(self):32 app = flask.Flask(__name__)33
54 unmodified lines
88 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))89 c = app.test_client()9091 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])90 self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])92 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']9394 def test_view_decorators(self):95 app = flask.Flask(__name__)96
11 unmodified lines
108109 app.add_url_rule('/', view_func=Index.as_view('index'))110 c = app.test_client()111 rv = c.get('/')110 self.assert_equal(rv.headers['X-Parachute'], 'awesome')111 self.assert_equal(rv.data, b'Awesome')112 assert rv.headers['X-Parachute'] == 'awesome'113 assert rv.data == b'Awesome'114115 def test_implicit_head(self):116 app = flask.Flask(__name__)117
5 unmodified lines
123124 app.add_url_rule('/', view_func=Index.as_view('index'))125 c = app.test_client()126 rv = c.get('/')125 self.assert_equal(rv.data, b'Blub')126 self.assert_equal(rv.headers['X-Method'], 'GET')127 assert rv.data == b'Blub'128 assert rv.headers['X-Method'] == 'GET'129 rv = c.head('/')128 self.assert_equal(rv.data, b'')129 self.assert_equal(rv.headers['X-Method'], 'HEAD')130 assert rv.data == b''131 assert rv.headers['X-Method'] == 'HEAD'132133 def test_explicit_head(self):134 app = flask.Flask(__name__)135
5 unmodified lines
141142 app.add_url_rule('/', view_func=Index.as_view('index'))143 c = app.test_client()144 rv = c.get('/')143 self.assert_equal(rv.data, b'GET')145 assert rv.data == b'GET'146 rv = c.head('/')145 self.assert_equal(rv.data, b'')146 self.assert_equal(rv.headers['X-Method'], 'HEAD')147 assert rv.data == b''148 assert rv.headers['X-Method'] == 'HEAD'149150 def test_endpoint_override(self):151 app = flask.Flask(__name__)152 app.debug = True
4 unmodified lines
157 return flask.request.method158159 app.add_url_rule('/', view_func=Index.as_view('index'))160159 with self.assert_raises(AssertionError):161 with pytest.raises(AssertionError):162 app.add_url_rule('/', view_func=Index.as_view('index'))163164 # But these tests should still pass. We just log a warning.165 self.common_test(app)
6 unmodified lines