test_testing.py
This file
Path
tests/test_testing.py
271 lines · 7.3 KiB · Python
Last changed by
Default environ (#2047)Michael Recachinasbefore adoptionbd5e297
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():20 app = flask.Flask(__name__)21 app.testing = True22 app.config['SERVER_NAME'] = 'example.com:1234'23 app.config['APPLICATION_ROOT'] = '/foo'24 @app.route('/')25 def index():26 return flask.request.url2728 ctx = app.test_request_context()29 assert ctx.request.url == 'http://example.com:1234/foo/'30 with app.test_client() as c:31 rv = c.get('/')32 assert rv.data == b'http://example.com:1234/foo/'3334def test_environ_defaults():35 app = flask.Flask(__name__)36 app.testing = True37 @app.route('/')38 def index():39 return flask.request.url4041 ctx = app.test_request_context()42 assert ctx.request.url == 'http://localhost/'43 with app.test_client() as c:44 rv = c.get('/')45 assert rv.data == b'http://localhost/'4647def test_environ_base_default():48 app = flask.Flask(__name__)49 app.testing = True50 @app.route('/')51 def index():52 flask.g.user_agent = flask.request.headers["User-Agent"]53 return flask.request.remote_addr5455 with app.test_client() as c:56 rv = c.get('/')57 assert rv.data == b'127.0.0.1'58 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__5960def test_environ_base_modified():61 app = flask.Flask(__name__)62 app.testing = True63 @app.route('/')64 def index():65 flask.g.user_agent = flask.request.headers["User-Agent"]66 return flask.request.remote_addr6768 with app.test_client() as c:69 c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70 c.environ_base['HTTP_USER_AGENT'] = 'Foo'71 rv = c.get('/')72 assert rv.data == b'0.0.0.0'73 assert flask.g.user_agent == 'Foo'7475 c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76 c.environ_base['HTTP_USER_AGENT'] = 'Bar'77 rv = c.get('/')78 assert rv.data == b'0.0.0.1'79 assert flask.g.user_agent == 'Bar'8081def test_redirect_keep_session():82 app = flask.Flask(__name__)83 app.secret_key = 'testing'8485 @app.route('/', methods=['GET', 'POST'])86 def index():87 if flask.request.method == 'POST':88 return flask.redirect('/getsession')89 flask.session['data'] = 'foo'90 return 'index'9192 @app.route('/getsession')93 def get_session():94 return flask.session.get('data', '<missing>')9596 with app.test_client() as c:97 rv = c.get('/getsession')98 assert rv.data == b'<missing>'99100 rv = c.get('/')101 assert rv.data == b'index'102 assert flask.session.get('data') == 'foo'103 rv = c.post('/', data={}, follow_redirects=True)104 assert rv.data == b'foo'105106 # This support requires a new Werkzeug version107 if not hasattr(c, 'redirect_client'):108 assert flask.session.get('data') == 'foo'109110 rv = c.get('/getsession')111 assert rv.data == b'foo'112113def test_session_transactions():114 app = flask.Flask(__name__)115 app.testing = True116 app.secret_key = 'testing'117118 @app.route('/')119 def index():120 return text_type(flask.session['foo'])121122 with app.test_client() as c:123 with c.session_transaction() as sess:124 assert len(sess) == 0125 sess['foo'] = [42]126 assert len(sess) == 1127 rv = c.get('/')128 assert rv.data == b'[42]'129 with c.session_transaction() as sess:130 assert len(sess) == 1131 assert sess['foo'] == [42]132133def test_session_transactions_no_null_sessions():134 app = flask.Flask(__name__)135 app.testing = True136137 with app.test_client() as c:138 with pytest.raises(RuntimeError) as e:139 with c.session_transaction() as sess:140 pass141 assert 'Session backend did not open a session' in str(e.value)142143def test_session_transactions_keep_context():144 app = flask.Flask(__name__)145 app.testing = True146 app.secret_key = 'testing'147148 with app.test_client() as c:149 rv = c.get('/')150 req = flask.request._get_current_object()151 assert req is not None152 with c.session_transaction():153 assert req is flask.request._get_current_object()154155def test_session_transaction_needs_cookies():156 app = flask.Flask(__name__)157 app.testing = True158 c = app.test_client(use_cookies=False)159 with pytest.raises(RuntimeError) as e:160 with c.session_transaction() as s:161 pass162 assert 'cookies' in str(e.value)163164def test_test_client_context_binding():165 app = flask.Flask(__name__)166 app.config['LOGGER_HANDLER_POLICY'] = 'never'167 @app.route('/')168 def index():169 flask.g.value = 42170 return 'Hello World!'171172 @app.route('/other')173 def other():174 1 // 0175176 with app.test_client() as c:177 resp = c.get('/')178 assert flask.g.value == 42179 assert resp.data == b'Hello World!'180 assert resp.status_code == 200181182 resp = c.get('/other')183 assert not hasattr(flask.g, 'value')184 assert b'Internal Server Error' in resp.data185 assert resp.status_code == 500186 flask.g.value = 23187188 try:189 flask.g.value190 except (AttributeError, RuntimeError):191 pass192 else:193 raise AssertionError('some kind of exception expected')194195def test_reuse_client():196 app = flask.Flask(__name__)197 c = app.test_client()198199 with c:200 assert c.get('/').status_code == 404201202 with c:203 assert c.get('/').status_code == 404204205def test_test_client_calls_teardown_handlers():206 app = flask.Flask(__name__)207 called = []208 @app.teardown_request209 def remember(error):210 called.append(error)211212 with app.test_client() as c:213 assert called == []214 c.get('/')215 assert called == []216 assert called == [None]217218 del called[:]219 with app.test_client() as c:220 assert called == []221 c.get('/')222 assert called == []223 c.get('/')224 assert called == [None]225 assert called == [None, None]226227def test_full_url_request():228 app = flask.Flask(__name__)229 app.testing = True230231 @app.route('/action', methods=['POST'])232 def action():233 return 'x'234235 with app.test_client() as c:236 rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})237 assert rv.status_code == 200238 assert 'gin' in flask.request.form239 assert 'vodka' in flask.request.args240241def test_subdomain():242 app = flask.Flask(__name__)243 app.config['SERVER_NAME'] = 'example.com'244 @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.data256257def test_nosubdomain():258 app = flask.Flask(__name__)259 app.config['SERVER_NAME'] = 'example.com'260 @app.route('/<company_id>')261 def view(company_id):262 return company_id263264 with app.test_request_context():265 url = flask.url_for('view', company_id='xxx')266267 with app.test_client() as c:268 response = c.get(url)269270 assert 200 == response.status_code271 assert b'xxx' == response.data