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
Provenance
- Commit
5da2c00- Tree
95b8316- Author
Markus Unterwaditzer <markus@unterwaditzer.net>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent
dd6b257
14 files changed+694 added−719 removed
modified:tests/__init__.py+3 added-31 removed
76 unmodified lines77 def 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)85 86 87 class TestFlask(object):18 unmodified lines106 # 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 == []111 112 def setup_method(self, method):113 self.setup()114 4 unmodified lines119 pass120 121 def teardown(self):122 pass123-124- def assert_equal(self, x, y):125- assert x == y126-127- 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)132-133- def assert_true(self, x, msg=None):134- assert x135- assert_ = assert_true136-137- def assert_false(self, x, msg=None):138- assert not x139-140- def assert_in(self, x, y):141- assert x in y142-143- def assert_not_in(self, x, y):144- assert x not in y145-146- def assert_isinstance(self, obj, cls):147- assert isinstance(obj, cls)148-149- def fail(self, msg):150- raise AssertionError(msg)modified:tests/test_appctx.py+18 added-15 removed
7 unmodified lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import flask15 import unittest16 from tests import TestFlask17 10 unmodified lines28 pass29 30 with app.app_context():31 rv = flask.url_for('index')30- self.assert_equal(rv, 'https://localhost/')32+ assert rv == 'https://localhost/'33 34 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')39 40 def test_url_generation_without_context_fails(self):39- with self.assert_raises(RuntimeError):41+ with pytest.raises(RuntimeError):42 flask.url_for('index')43 44 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 == None49 50 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 == None55 56 def test_app_tearing_down(self):57 cleanup_stuff = []58 app = flask.Flask(__name__)3 unmodified lines62 63 with app.app_context():64 pass65 64- self.assert_equal(cleanup_stuff, [None])66+ assert cleanup_stuff == [None]67 68 def test_app_tearing_down_with_previous_exception(self):69 cleanup_stuff = []70 app = flask.Flask(__name__)8 unmodified lines79 80 with app.app_context():81 pass82 81- self.assert_equal(cleanup_stuff, [None])83+ assert cleanup_stuff == [None]84 85 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'93 94 def test_context_refcounts(self):95 called = []96 app = flask.Flask(__name__)7 unmodified lines104 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']116 117 118 def suite():119 suite = unittest.TestSuite()2 unmodified linesmodified:tests/test_basic.py+257 added-248 removed
7 unmodified lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import re15 import uuid16 import time17 import flask15 unmodified lines33 @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''39 40 def test_options_on_multiple_rules(self):41 app = flask.Flask(__name__)42 @app.route('/', methods=['GET', 'POST'])2 unmodified lines45 @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']50 51 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 == 40559 60 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']67 68 def test_request_dispatching(self):69 app = flask.Flask(__name__)70 @app.route('/')3 unmodified lines74 def more():75 return flask.request.method76 77 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']90 91 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 lines105 app.add_url_rule('/', 'index', index)106 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])107 108 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']121 122 def test_werkzeug_routing(self):123 from werkzeug.routing import Submount, Rule124 app = flask.Flask(__name__)8 unmodified lines133 app.view_functions['bar'] = bar134 app.view_functions['index'] = index135 136 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'139 140 def test_endpoint_decorator(self):141 from werkzeug.routing import Submount, Rule142 app = flask.Flask(__name__)10 unmodified lines153 def index():154 return 'index'155 156 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'159 160 def test_session(self):161 app = flask.Flask(__name__)162 app.secret_key = 'testkey'5 unmodified lines168 def get():169 return flask.session['value']170 171 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'174 175 def test_session_using_server_name(self):176 app = flask.Flask(__name__)177 app.config.update(4 unmodified lines182 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()188 189 def test_session_using_server_name_and_port(self):190 app = flask.Flask(__name__)191 app.config.update(4 unmodified lines196 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()202 203 def test_session_using_server_name_port_and_path(self):204 app = flask.Flask(__name__)205 app.config.update(5 unmodified lines211 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()218 219 def test_session_using_application_root(self):220 class PrefixPathMiddleware(object):221 def __init__(self, app, prefix):13 unmodified lines235 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()240 241 def test_session_using_session_settings(self):242 app = flask.Flask(__name__)243 app.config.update(10 unmodified lines254 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 cookie262 263 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')276 277 def test_session_expiration(self):11 unmodified lines289 return text_type(flask.session.permanent)290 291 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.day300 301 rv = client.get('/test')300- self.assert_equal(rv.data, b'True')302+ assert rv.data == b'True'303 304 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 None309 310 def test_session_stored_last(self):311 app = flask.Flask(__name__)312 app.secret_key = 'development-key'7 unmodified lines320 def dump_session_contents():321 return repr(flask.session.get('foo'))322 323 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'326 327 def test_session_special_types(self):328 app = flask.Flask(__name__)329 app.secret_key = 'development-key'16 unmodified lines346 347 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)357 358 def test_session_cookie_setting(self):359 app = flask.Flask(__name__)360 app.testing = True11 unmodified lines372 return str(flask.session.get('foo', 0))373 374 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'379 380 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'384 385 is_permanent = True386 app.config['SESSION_REFRESH_EACH_REQUEST'] = True387 run_test(expect_header=True)14 unmodified lines402 app = flask.Flask(__name__)403 app.secret_key = 'testkey'404 405 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']412 413 def test_extended_flashing(self):414 # Be sure app.testing=True below, else tests can fail silently.415 #14 unmodified lines430 431 @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 ''440 441 @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 ''451 452 @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 ''457 458 @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 ''466 467 @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 ''474 475 # Create new test client on each test to clean flashed messages.476 29 unmodified lines506 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'517 518 def test_after_request_processing(self):519 app = flask.Flask(__name__)520 app.testing = True5 unmodified lines526 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'532 533 def test_teardown_request_handler(self):534 called = []535 app = flask.Flask(__name__)4 unmodified lines540 @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) == 1547 548 def test_teardown_request_handler_debug_mode(self):549 called = []550 app = flask.Flask(__name__)5 unmodified lines556 @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) == 1563 564 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 lines577 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 lines590 @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) == 2597 598 def test_before_after_request_order(self):599 called = []600 app = flask.Flask(__name__)20 unmodified lines621 @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]627 628 def test_error_handling(self):629 app = flask.Flask(__name__)630 app.config['LOGGER_HANDLER_POLICY'] = 'never'16 unmodified lines647 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.data659 660 def test_before_request_and_routing_errors(self):661 app = flask.Flask(__name__)662 @app.before_request2 unmodified lines665 @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'671 672 def test_user_error_handling(self):673 class MyException(Exception):674 pass675 676 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()684 685 c = app.test_client()681- self.assert_equal(c.get('/').data, b'42')686+ assert c.get('/').data == b'42'687 688 def test_http_error_subclass_handling(self):689 class ForbiddenSubclass(Forbidden):690 pass691 692 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'702 703 @app.route('/1')704 def index1():5 unmodified lines710 def index3():711 raise Forbidden()712 713 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'717 718 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 == 400726 727 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'735 736 def test_trapping_of_all_http_exceptions(self):737 app = flask.Flask(__name__)738 app.testing = True7 unmodified lines746 c.get('/fail')747 except NotFound as e:748 pass749 else:745- self.fail('Expected exception')750+ assert False, 'Expected exception'751 752 def test_enctype_debug_helper(self):753 from flask.debughelpers import DebugFilesKeyError754 app = flask.Flask(__name__)8 unmodified lines763 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'771 772 def test_response_creation(self):773 app = flask.Flask(__name__)774 @app.route('/unicode')24 unmodified lines799 "X-Bar": "Foo"800 }801 802 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 == 404824 825 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'832 833 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'837 838 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'842 843 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'851 852 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'857 858 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'864 865 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'874 875 def test_build_error_handler(self):876 app = flask.Flask(__name__)877 878 # 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')881 882 # Verify the error is re-raised if not the current exception.883 try:884 with app.test_request_context():2 unmodified lines887 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', {})892 893 # 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/'900 901 def test_custom_converters(self):902 from werkzeug.routing import BaseConverter903 class ListConverter(BaseConverter):7 unmodified lines911 @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'916 917 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()927 928 def test_none_response(self):929 app = flask.Flask(__name__)3 unmodified lines933 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"941 942 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.g945 946 def test_test_app_proper_environ(self):947 app = flask.Flask(__name__)948 app.config.update(7 unmodified lines956 def subdomain():957 return 'Foo SubDomain'958 959 rv = app.test_client().get('/')955- self.assert_equal(rv.data, b'Foo')960+ assert rv.data == b'Foo'961 962 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')958- self.assert_equal(rv.data, b'Foo')963+ assert rv.data == b'Foo'964 965 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')961- self.assert_equal(rv.data, b'Foo')966+ assert rv.data == b'Foo'967 968 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'971 972 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+ )984 985 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+ )997 998 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'1000 1001 def test_exception_propagation(self):1002 def apprunner(configkey):1003 app = flask.Flask(__name__)8 unmodified lines1012 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 == 5001019 1020 # 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 fail8 unmodified lines1031 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'1043 1044 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'1047 1048 def test_url_processors(self):1049 app = flask.Flask(__name__)1050 20 unmodified lines1071 return flask.url_for('about', lang_code='en')1072 1073 c = app.test_client()1074 1066- 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'1078 1079 def test_inject_blueprint_url_defaults(self):1080 app = flask.Flask(__name__)1081 bp = flask.Blueprint('foo.bar.baz', __name__,9 unmodified lines1091 1092 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 == expected1096 1097 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 == expected1101 1102 def test_nonascii_pathinfo(self):1103 app = flask.Flask(__name__)1104 app.testing = True3 unmodified lines1108 return 'Hello World!'1109 1110 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!'1113 1114 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'1130 1131 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_request1137 1138 def test_before_first_request_functions(self):1139 got = []1140 app = flask.Flask(__name__)1 unmodified line1142 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_request1150 1151 def test_before_first_request_functions_concurrent(self):1152 got = []1153 app = flask.Flask(__name__)5 unmodified lines1159 1160 c = app.test_client()1161 def get_and_assert():1162 c.get("/")1154- self.assert_equal(got, [42])1163+ assert got == [42]1164 1165 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_request1170 1171 def test_routing_redirect_debugging(self):1172 app = flask.Flask(__name__)1173 app.debug = True3 unmodified lines1177 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'1186 1187 rv = c.get('/foo', data={}, follow_redirects=True)1179- self.assert_equal(rv.data, b'success')1188+ assert rv.data == b'success'1189 1190 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'1194 1195 def test_route_decorator_custom_endpoint(self):1196 app = flask.Flask(__name__)1197 app.debug = True15 unmodified lines1213 assert flask.url_for('bar') == '/bar/'1214 assert flask.url_for('123') == '/bar/123'1215 1216 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'1220 1221 def test_preserve_only_once(self):1222 app = flask.Flask(__name__)1223 app.debug = True3 unmodified lines1227 1 // 01228 1229 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')1233 1225- 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 None1240 1241 def test_preserve_remembers_exception(self):1242 app = flask.Flask(__name__)1243 app.debug = True13 unmodified lines1257 1258 c = app.test_client()1259 1260 # 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 == []1264 1265 # 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)1269 1270 # 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] == None1274 1275 def test_get_method_on_g(self):1276 app = flask.Flask(__name__)1277 app.testing = True1278 1279 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 == 421285 1286 def test_g_iteration_protocol(self):1287 app = flask.Flask(__name__)1288 app.testing = True1289 1290 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']1296 1297 1298 class TestSubdomain(TestFlask):1299 8 unmodified lines1308 return 'test index'1309 1310 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'1313 1314 rv = c.get('/', 'http://test.localhost/')1306- self.assert_equal(rv.data, b'test index')1315+ assert rv.data == b'test index'1316 1317 def test_subdomain_matching(self):1318 app = flask.Flask(__name__)1319 app.config['SERVER_NAME'] = 'localhost'2 unmodified lines1322 return 'index for %s' % user1323 1324 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'1327 1328 def test_subdomain_matching_with_ports(self):1329 app = flask.Flask(__name__)1330 app.config['SERVER_NAME'] = 'localhost:3000'2 unmodified lines1333 return 'index for %s' % user1334 1335 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'1338 1339 def test_multi_route_rules(self):1340 app = flask.Flask(__name__)1341 2 unmodified lines1344 def index(test='a'):1345 return test1346 1347 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'1351 1352 def test_multi_route_class_views(self):1353 class View(object):1354 def __init__(self, app):5 unmodified lines1360 1361 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 lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import flask15 import unittest16 from tests import TestFlask17 from flask._compat import text_type38 unmodified lines56 return 'application itself says no', 40357 58 c = app.test_client()59 58- 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'63 64 def test_blueprint_specific_user_error_handling(self):65 class MyDecoratorException(Exception):66 pass3 unmodified lines70 blue = flask.Blueprint('blue', __name__)71 72 @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'76 77 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)81 82 @blue.route('/decorator')7 unmodified lines90 app.register_blueprint(blue)91 92 c = app.test_client()93 92- 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'96 97 def test_blueprint_url_definitions(self):98 bp = flask.Blueprint('test', __name__)99 9 unmodified lines109 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})110 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})111 112 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'117 118 def test_blueprint_url_processors(self):119 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')120 17 unmodified lines138 app.register_blueprint(bp)139 140 c = app.test_client()141 140- 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/'144 145 def test_templates_and_static(self):146 from blueprintapp import app147 c = app.test_client()148 149 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()161 162 # 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 lines167 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_default175 176 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'178 179 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'186 187 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'189 190 def test_default_static_cache_timeout(self):191 app = flask.Flask(__name__)192 class MyBlueprint(flask.Blueprint):12 unmodified lines205 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_default213 214 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']218 219 def test_dotted_names(self):220 frontend = flask.Blueprint('myapp.frontend', __name__)221 backend = flask.Blueprint('myapp.backend', __name__)14 unmodified lines236 app.register_blueprint(frontend)237 app.register_blueprint(backend)238 239 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'243 244 def test_dotted_names_from_app(self):245 app = flask.Flask(__name__)246 app.testing = True10 unmodified lines257 app.register_blueprint(test)258 259 with app.test_client() as c:260 rv = c.get('/')261- self.assert_equal(rv.data, b'/test/')261+ assert rv.data == b'/test/'262 263 def test_empty_url_defaults(self):264 bp = flask.Blueprint('bp', __name__)265 5 unmodified lines271 app = flask.Flask(__name__)272 app.register_blueprint(bp)273 274 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'277 278 def test_route_decorator_custom_endpoint(self):279 280 bp = flask.Blueprint('bp', __name__)21 unmodified lines302 def index():303 return flask.request.endpoint304 305 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'311 312 def test_route_decorator_custom_endpoint_with_dots(self):313 bp = flask.Blueprint('bp', __name__)314 21 unmodified lines336 337 def foo_foo_foo():338 pass339 340- 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 )346 347- self.assert_raises(347+ pytest.raises(348 AssertionError,349 bp.route('/bar/123', endpoint='bar.123'),350 lambda: None351 )1 unmodified line353 app = flask.Flask(__name__)354 app.register_blueprint(bp, url_prefix='/py')355 356 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 lines367 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'374 375 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'385 386 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'396 397 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'407 408 def test_template_filter_with_template(self):409 bp = flask.Blueprint('bp', __name__)410 @bp.app_template_filter()4 unmodified lines415 @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'420 421 def test_template_filter_after_route_with_template(self):422 app = flask.Flask(__name__)423 @app.route('/')4 unmodified lines428 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'433 434 def test_add_template_filter_with_template(self):435 bp = flask.Blueprint('bp', __name__)436 def super_reverse(s):4 unmodified lines441 @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'446 447 def test_template_filter_with_name_and_template(self):448 bp = flask.Blueprint('bp', __name__)449 @bp.app_template_filter('super_reverse')4 unmodified lines454 @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'459 460 def test_add_template_filter_with_name_and_template(self):461 bp = flask.Blueprint('bp', __name__)462 def my_reverse(s):4 unmodified lines467 @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'472 473 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)483 484 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)494 495 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)505 506 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)516 517 def test_template_test_with_template(self):518 bp = flask.Blueprint('bp', __name__)519 @bp.app_template_test()4 unmodified lines524 @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.data529 530 def test_template_test_after_route_with_template(self):531 app = flask.Flask(__name__)532 @app.route('/')4 unmodified lines537 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.data542 543 def test_add_template_test_with_template(self):544 bp = flask.Blueprint('bp', __name__)545 def boolean(value):4 unmodified lines550 @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.data555 556 def test_template_test_with_name_and_template(self):557 bp = flask.Blueprint('bp', __name__)558 @bp.app_template_test('boolean')4 unmodified lines563 @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.data568 569 def test_add_template_test_with_name_and_template(self):570 bp = flask.Blueprint('bp', __name__)571 def is_boolean(value):4 unmodified lines576 @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.data581 582 def suite():583 suite = unittest.TestSuite()584 suite.addTest(unittest.makeSuite(TestBlueprint))1 unmodified linemodified:tests/test_config.py+33 added-33 removed
28 unmodified lines29 30 class TestConfig(TestFlask):31 32 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.config36 37 def test_config_from_file(self):38 app = flask.Flask(__name__)39 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')32 unmodified lines72 )73 self.common_object_test(app)74 75 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 lines94 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)102 103 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 lines114 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 = env126 127 def test_config_missing(self):1 unmodified line129 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)139 140 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)152 153 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)162 163 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 == 42167 168 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']182 183 184 class TestInstance(TestFlask):185 def test_explicit_instance_paths(self, apps_tmpdir):1 unmodified line187 flask.Flask(__name__, instance_path='instance')188 assert 'must be absolute' in str(excinfo.value)189 190 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)192 193 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 lines284 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 lines10 """11 12 import sys13 import unittest14+import pytest15+16 try:17 from imp import reload as reload_module18 except ImportError:19 reload_module = reload22 unmodified lines42 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 == 147 48 def teardown(self):49 from flask import ext50 for key in ext.__dict__:49- self.assert_not_in('.', key)51+ assert '.' not in key52 53 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'56 57 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'61 62 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'65 66 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'70 71 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() == 4274 75 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() == 4279 80 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'83 84 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'88 89 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'92 93 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'97 98 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() == 42102 103 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() == 42106 107 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.broken111 112 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()124 125 # 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_filename134 135 136 def suite():137 suite = unittest.TestSuite()2 unmodified linesmodified:tests/test_helpers.py+94 added-100 removed
7 unmodified lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import os15 import flask16 import unittest17 from logging import StreamHandler19 unmodified lines37 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 == 40042 43 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'51 52 def test_json_body_encoding(self):53 app = flask.Flask(__name__)54 app.testing = True3 unmodified lines58 59 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')63 64 def test_jsonify(self):65 d = dict(a=23, b=42, c=[1, 2, 3])66 app = flask.Flask(__name__)5 unmodified lines72 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) == d78 79 def test_json_as_unicode(self):80 app = flask.Flask(__name__)81 82 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"'86 87 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"'91 92 def test_json_attr(self):93 app = flask.Flask(__name__)94 @app.route('/add', methods=['POST'])2 unmodified lines97 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'102 103 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>'123 124 def test_json_customization(self):125 class X(object):126 def __init__(self, val):21 unmodified lines148 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>"'153 154 def test_modified_url_encoding(self):155 class ModifiedRequest(flask.Request):156 url_charset = 'euc-kr'6 unmodified lines163 def index():164 return flask.request.args['foo']165 166 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')169 170 if not has_encoding('euc-kr'):171 test_modified_url_encoding = None172 173 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')178 179 @app.route('/')180 def index():55 unmodified lines236 '}'237 ]238 239 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_str243 244 class TestSendfile(TestFlask):245 246 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()256 257 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()268 269 def test_send_file_object(self):270 app = flask.Flask(__name__)2 unmodified lines273 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) == 2282 283 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) == 2295 296 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 lines313 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) == 1331 332 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) == 1341 342 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) == 2353 354 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()361 362 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()371 372 def test_static_file(self):373 app = flask.Flask(__name__)1 unmodified line375 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 101 unmodified line402 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()413 414 def test_send_from_directory(self):415 app = flask.Flask(__name__)2 unmodified lines418 '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()424 425 426 class TestLogging(TestFlask):427 428 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 logger1435 436 def test_debug_log(self):437 app = flask.Flask(__name__)438 app.debug = True11 unmodified lines450 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 out458 459 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'466 467 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 == 10473 474 def test_exception_logging(self):475 out = StringIO()476 app = flask.Flask(__name__)5 unmodified lines482 def index():483 1 // 0484 485 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.data488 489 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 err494 495 def test_processor_exceptions(self):496 app = flask.Flask(__name__)497 app.config['LOGGER_HANDLER_POLICY'] = 'never'13 unmodified lines511 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'517 518 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'525 526 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/'533 534 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 lines560 app.add_url_rule('/myview/create', methods=['POST'],561 view_func=myview)562 563 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'567 568 569 class TestNoImports(TestFlask):570 """Test Flasks are created without import.9 unmodified lines580 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.'585 586 587 class TestStreaming(TestFlask):588 8 unmodified lines597 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!'602 603 def test_streaming_with_context_as_decorator(self):604 app = flask.Flask(__name__)605 app.testing = True6 unmodified lines612 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!'617 618 def test_streaming_with_context_and_custom_close(self):619 app = flask.Flask(__name__)620 app.testing = True17 unmodified lines638 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]644 645 646 def suite():647 suite = unittest.TestSuite()7 unmodified linesmodified:tests/test_regression.py+5 added-5 removed
67 unmodified lines68 69 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>'74 75 # Trigger caches76 fire()77 5 unmodified lines83 fire()84 85 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', '..')89 90 91 class TestException(TestFlask):17 unmodified lines109 raise Foo()110 111 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 lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import flask15 import unittest16 try:17 from greenlet import greenlet12 unmodified lines30 buffer.append(exception)31 32 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]37 38 def test_teardown_with_previous_exception(self):39 buffer = []40 app = flask.Flask(__name__)6 unmodified lines47 except Exception:48 pass49 50 with app.test_request_context():49- self.assert_equal(buffer, [])50- self.assert_equal(buffer, [None])51+ assert buffer == []52+ assert buffer == [None]53 54 def test_proper_test_request_context(self):55 app = flask.Flask(__name__)56 app.config.update(8 unmodified lines65 def sub():66 return None67 68 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/'71 72 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/'75 76 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')")80-81- 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 )85 90- 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- )89 90+ app.config.update(SERVER_NAME='localhost:80')91+ with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):92+ pass93+94 def test_context_binding(self):95 app = flask.Flask(__name__)96 @app.route('/')97 def index():2 unmodified lines100 def meh():101 return flask.request.url102 103 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 None108 109 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()120 121 def test_manual_context_binding(self):3 unmodified lines125 return 'Hello %s!' % flask.request.args['name']126 127 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'137 138 def test_greenlet_context_copying(self):139 app = flask.Flask(__name__)140 greenlets = []1 unmodified line142 @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!'157 158 rv = app.test_client().get('/?foo=bar')164- self.assert_equal(rv.data, b'Hello World!')159+ assert rv.data == b'Hello World!'160 161 result = greenlets[0].run()167- self.assert_equal(result, 42)162+ assert result == 42163 164 def test_greenlet_context_copying_api(self):165 app = flask.Flask(__name__)166 greenlets = []2 unmodified lines169 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!'180 181 rv = app.test_client().get('/?foo=bar')187- self.assert_equal(rv.data, b'Hello World!')182+ assert rv.data == b'Hello World!'183 184 result = greenlets[0].run()190- self.assert_equal(result, 42)185+ assert result == 42186 187 # Disable test if we don't have greenlets available188 if greenlet is None:189 test_greenlet_context_copying = None7 unmodified linesmodified:tests/test_signals.py+16 added-17 removed
40 unmodified lines41 42 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)51 52 def test_request_signals(self):3 unmodified lines56 def before_request_signal(sender):57 calls.append('before-signal')58 59 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')62 63 @app.before_request64 def before_request_handler():14 unmodified lines79 flask.request_finished.connect(after_request_signal, app)80 81 try:82 rv = app.test_client().get('/')83- self.assert_equal(rv.data, b'stuff')83+ assert rv.data == b'stuff'84 85- 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 lines100 recorded.append(exception)101 102 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)109 110 def test_appcontext_signals(self):14 unmodified lines125 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 lines151 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 lines32 def index():33 1 // 034 35 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.data38 39 err = out.getvalue()40- self.assert_equal(err, '')40+ assert err == ''41 42 43 def suite():44 suite = unittest.TestSuite()2 unmodified linesmodified:tests/test_templating.py+63 added-65 removed
26 unmodified lines27 @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'32 33 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'40 41 def test_request_less_rendering(self):42 app = flask.Flask(__name__)43 app.config['WORLD_NAME'] = 'Special World'3 unmodified lines47 48 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'52 53 def test_standard_context(self):54 app = flask.Flask(__name__)55 app.secret_key = 'development key'7 unmodified lines63 {{ 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']68 69 def test_escaping(self):70 text = '<p>Hello World!'71 app = flask.Flask(__name__)1 unmodified line73 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'<p>Hello World!',79 b'<p>Hello World!',80 b'<p>Hello World!',81 b'<p>Hello World!',82 b'<p>Hello World!',83 b'<p>Hello World!'84- ])84+ ]85 86 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'93 94 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!'99 100 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'108 109 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'117 118 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'126 127 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'135 136 def test_template_filter_with_template(self):137 app = flask.Flask(__name__)138 @app.template_filter()2 unmodified lines141 @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'146 147 def test_add_template_filter_with_template(self):148 app = flask.Flask(__name__)149 def super_reverse(s):2 unmodified lines152 @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'157 158 def test_template_filter_with_name_and_template(self):159 app = flask.Flask(__name__)160 @app.template_filter('super_reverse')2 unmodified lines163 @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'168 169 def test_add_template_filter_with_name_and_template(self):170 app = flask.Flask(__name__)171 def my_reverse(s):2 unmodified lines174 @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'179 180 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)188 189 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)197 198 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)206 207 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)215 216 def test_template_test_with_template(self):217 app = flask.Flask(__name__)218 @app.template_test()2 unmodified lines221 @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.data226 227 def test_add_template_test_with_template(self):228 app = flask.Flask(__name__)229 def boolean(value):2 unmodified lines232 @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.data237 238 def test_template_test_with_name_and_template(self):239 app = flask.Flask(__name__)240 @app.template_test('boolean')2 unmodified lines243 @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.data248 249 def test_add_template_test_with_name_and_template(self):250 app = flask.Flask(__name__)251 def is_boolean(value):2 unmodified lines254 @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.data259 260 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'271 272 def test_custom_template_loader(self):273 class MyFlask(flask.Flask):274 def create_global_jinja_loader(self):4 unmodified lines279 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!'284 285 def test_iterable_loader(self):286 app = flask.Flask(__name__)287 @app.context_processor7 unmodified lines295 'context_template.html'],296 value=23)297 298 rv = app.test_client().get('/')299- self.assert_equal(rv.data, b'<h1>Jameson</h1>')299+ assert rv.data == b'<h1>Jameson</h1>'300 301 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_reload308 309 def test_template_loader_debugging(self):310 from blueprintapp import app311 1 unmodified line313 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)326 327 with app.test_client() as c:328 try:329 old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']3 unmodified lines333 334 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_setting343 346- self.assert_equal(len(called), 1)344+ assert len(called) == 1345 346 347 def suite():348 suite = unittest.TestSuite()2 unmodified linesmodified:tests/test_testing.py+37 added-37 removed
26 unmodified lines27 def index():28 return flask.request.url29 30 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/'35 36 def test_environ_defaults(self):37 app = flask.Flask(__name__)38 app.testing = True1 unmodified line40 def index():41 return flask.request.url42 43 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/'48 49 def test_redirect_keep_session(self):50 app = flask.Flask(__name__)51 app.secret_key = 'testing'36 unmodified lines88 return text_type(flask.session['foo'])89 90 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]100 101 def test_session_transactions_no_null_sessions(self):102 app = flask.Flask(__name__)103 app.testing = True2 unmodified lines106 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'113 114 def test_session_transactions_keep_context(self):115 app = flask.Flask(__name__)116 app.testing = True1 unmodified line118 119 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()125 126 def test_session_transaction_needs_cookies(self):127 app = flask.Flask(__name__)128 app.testing = True1 unmodified line130 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'137 138 def test_test_client_context_binding(self):139 app = flask.Flask(__name__)140 app.config['LOGGER_HANDLER_POLICY'] = 'never'7 unmodified lines148 1 // 0149 150 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 == 200155 156 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 = 23161 162 try:163 flask.g.value6 unmodified lines170 app = flask.Flask(__name__)171 c = app.test_client()172 173 with c:174- self.assert_equal(c.get('/').status_code, 404)174+ assert c.get('/').status_code == 404175 176 with c:177- self.assert_equal(c.get('/').status_code, 404)177+ assert c.get('/').status_code == 404178 179 def test_test_client_calls_teardown_handlers(self):180 app = flask.Flask(__name__)181 called = []1 unmodified line183 def remember(error):184 called.append(error)185 186 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]191 192 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]200 201 def test_full_url_request(self):202 app = flask.Flask(__name__)203 app.testing = True3 unmodified lines207 return 'x'208 209 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.args214 215 216 class TestSubdomain(TestFlask):217 22 unmodified lines240 241 url = flask.url_for('view', company_id='xxx')242 response = client.get(url)243 244- 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.data246 247 248 def test_nosubdomain(self, app, client):249 @app.route('/<company_id>')2 unmodified lines252 253 url = flask.url_for('view', company_id='xxx')254 response = client.get(url)255 256- 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.datamodified:tests/test_views.py+17 added-15 removed
7 unmodified lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import flask15 import flask.views16 import unittest17 from tests import TestFlask3 unmodified lines21 22 def common_test(self, app):23 c = app.test_client()24 23- 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']30 31 def test_basic_view(self):32 app = flask.Flask(__name__)33 54 unmodified lines88 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))89 c = app.test_client()90 91 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']93 94 def test_view_decorators(self):95 app = flask.Flask(__name__)96 11 unmodified lines108 109 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'114 115 def test_implicit_head(self):116 app = flask.Flask(__name__)117 5 unmodified lines123 124 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'132 133 def test_explicit_head(self):134 app = flask.Flask(__name__)135 5 unmodified lines141 142 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'149 150 def test_endpoint_override(self):151 app = flask.Flask(__name__)152 app.debug = True4 unmodified lines157 return flask.request.method158 159 app.add_url_rule('/', view_func=Index.as_view('index'))160 159- with self.assert_raises(AssertionError):161+ with pytest.raises(AssertionError):162 app.add_url_rule('/', view_func=Index.as_view('index'))163 164 # But these tests should still pass. We just log a warning.165 self.common_test(app)6 unmodified lines