test_testing.py
This file
Path
tests/test_testing.py
273 lines · 6.9 KiB · Python
Last changed by
DRYing up the test suite using pytest fixtures (#2306)Christian Stade-Schuldtbefore adoption5b0b971
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.testing4 ~~~~~~~~~~~~~56 Test client and more.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import pytest1213import flask14import werkzeug1516from flask._compat import text_type171819def test_environ_defaults_from_config(app, client):20 app.config['SERVER_NAME'] = 'example.com:1234'21 app.config['APPLICATION_ROOT'] = '/foo'2223 @app.route('/')24 def index():25 return flask.request.url2627 ctx = app.test_request_context()28 assert ctx.request.url == 'http://example.com:1234/foo/'2930 rv = client.get('/')31 assert rv.data == b'http://example.com:1234/foo/'323334def test_environ_defaults(app, client, app_ctx, req_ctx):35 @app.route('/')36 def index():37 return flask.request.url3839 ctx = app.test_request_context()40 assert ctx.request.url == 'http://localhost/'41 with app.test_client() as c:42 rv = c.get('/')43 assert rv.data == b'http://localhost/'444546def test_environ_base_default(app, client, app_ctx):47 app.testing = True4849 @app.route('/')50 def index():51 flask.g.user_agent = flask.request.headers["User-Agent"]52 return flask.request.remote_addr5354 rv = client.get('/')55 assert rv.data == b'127.0.0.1'56 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__575859def test_environ_base_modified(app, client, app_ctx):60 @app.route('/')61 def index():62 flask.g.user_agent = flask.request.headers["User-Agent"]63 return flask.request.remote_addr6465 client.environ_base['REMOTE_ADDR'] = '0.0.0.0'66 client.environ_base['HTTP_USER_AGENT'] = 'Foo'67 rv = client.get('/')68 assert rv.data == b'0.0.0.0'69 assert flask.g.user_agent == 'Foo'7071 client.environ_base['REMOTE_ADDR'] = '0.0.0.1'72 client.environ_base['HTTP_USER_AGENT'] = 'Bar'73 rv = client.get('/')74 assert rv.data == b'0.0.0.1'75 assert flask.g.user_agent == 'Bar'767778def test_redirect_keep_session(app, client, app_ctx):79 app.secret_key = 'testing'8081 @app.route('/', methods=['GET', 'POST'])82 def index():83 if flask.request.method == 'POST':84 return flask.redirect('/getsession')85 flask.session['data'] = 'foo'86 return 'index'8788 @app.route('/getsession')89 def get_session():90 return flask.session.get('data', '<missing>')9192 with client as c:93 rv = c.get('/getsession')94 assert rv.data == b'<missing>'9596 rv = c.get('/')97 assert rv.data == b'index'98 assert flask.session.get('data') == 'foo'99 rv = c.post('/', data={}, follow_redirects=True)100 assert rv.data == b'foo'101102 # This support requires a new Werkzeug version103 if not hasattr(c, 'redirect_client'):104 assert flask.session.get('data') == 'foo'105106 rv = c.get('/getsession')107 assert rv.data == b'foo'108109110def test_session_transactions(app):111 app.secret_key = 'testing'112113 @app.route('/')114 def index():115 return text_type(flask.session['foo'])116117 with app.test_client() as c:118 with c.session_transaction() as sess:119 assert len(sess) == 0120 sess['foo'] = [42]121 assert len(sess) == 1122 rv = c.get('/')123 assert rv.data == b'[42]'124 with c.session_transaction() as sess:125 assert len(sess) == 1126 assert sess['foo'] == [42]127128129def test_session_transactions_no_null_sessions():130 app = flask.Flask(__name__)131 app.testing = True132133 with app.test_client() as c:134 with pytest.raises(RuntimeError) as e:135 with c.session_transaction() as sess:136 pass137 assert 'Session backend did not open a session' in str(e.value)138139140def test_session_transactions_keep_context(app, client, req_ctx):141 app.secret_key = 'testing'142143 rv = client.get('/')144 req = flask.request._get_current_object()145 assert req is not None146 with client.session_transaction():147 assert req is flask.request._get_current_object()148149def test_session_transaction_needs_cookies(app):150 c = app.test_client(use_cookies=False)151 with pytest.raises(RuntimeError) as e:152 with c.session_transaction() as s:153 pass154 assert 'cookies' in str(e.value)155156157def test_test_client_context_binding():158 app = flask.Flask(__name__)159 app.config['LOGGER_HANDLER_POLICY'] = 'never'160161 @app.route('/')162 def index():163 flask.g.value = 42164 return 'Hello World!'165166 @app.route('/other')167 def other():168 1 // 0169170 with app.test_client() as c:171 resp = c.get('/')172 assert flask.g.value == 42173 assert resp.data == b'Hello World!'174 assert resp.status_code == 200175176 resp = c.get('/other')177 assert not hasattr(flask.g, 'value')178 assert b'Internal Server Error' in resp.data179 assert resp.status_code == 500180 flask.g.value = 23181182 try:183 flask.g.value184 except (AttributeError, RuntimeError):185 pass186 else:187 raise AssertionError('some kind of exception expected')188189190def test_reuse_client():191 app = flask.Flask(__name__)192 c = app.test_client()193194 with c:195 assert c.get('/').status_code == 404196197 with c:198 assert c.get('/').status_code == 404199200201def test_test_client_calls_teardown_handlers():202 app = flask.Flask(__name__)203 called = []204205 @app.teardown_request206 def remember(error):207 called.append(error)208209 with app.test_client() as c:210 assert called == []211 c.get('/')212 assert called == []213 assert called == [None]214215 del called[:]216 with app.test_client() as c:217 assert called == []218 c.get('/')219 assert called == []220 c.get('/')221 assert called == [None]222 assert called == [None, None]223224225def test_full_url_request():226 app = flask.Flask(__name__)227 app.testing = True228229 @app.route('/action', methods=['POST'])230 def action():231 return 'x'232233 with app.test_client() as c:234 rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})235 assert rv.status_code == 200236 assert 'gin' in flask.request.form237 assert 'vodka' in flask.request.args238239240def test_subdomain():241 app = flask.Flask(__name__)242 app.config['SERVER_NAME'] = 'example.com'243244 @app.route('/', subdomain='<company_id>')245 def view(company_id):246 return company_id247248 with app.test_request_context():249 url = flask.url_for('view', company_id='xxx')250251 with app.test_client() as c:252 response = c.get(url)253254 assert 200 == response.status_code255 assert b'xxx' == response.data256257258def test_nosubdomain():259 app = flask.Flask(__name__)260 app.config['SERVER_NAME'] = 'example.com'261262 @app.route('/<company_id>')263 def view(company_id):264 return company_id265266 with app.test_request_context():267 url = flask.url_for('view', company_id='xxx')268269 with app.test_client() as c:270 response = c.get(url)271272 assert 200 == response.status_code273 assert b'xxx' == response.data