test_testing.py
This file
Path
tests/test_testing.py
382 lines · 9.8 KiB · Python
Last changed by
add test_cli_runner for testing app.cli commandsDavid Lordbefore adoptioncf5525f
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.testing4 ~~~~~~~~~~~~~56 Test client and more.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""11import click12import pytest1314import flask15import werkzeug1617from flask._compat import text_type18from flask.cli import ScriptInfo19from flask.json import jsonify20from flask.testing import make_test_environ_builder, FlaskCliRunner212223def test_environ_defaults_from_config(app, client):24 app.config['SERVER_NAME'] = 'example.com:1234'25 app.config['APPLICATION_ROOT'] = '/foo'2627 @app.route('/')28 def index():29 return flask.request.url3031 ctx = app.test_request_context()32 assert ctx.request.url == 'http://example.com:1234/foo/'3334 rv = client.get('/')35 assert rv.data == b'http://example.com:1234/foo/'363738def test_environ_defaults(app, client, app_ctx, req_ctx):39 @app.route('/')40 def index():41 return flask.request.url4243 ctx = app.test_request_context()44 assert ctx.request.url == 'http://localhost/'45 with client:46 rv = client.get('/')47 assert rv.data == b'http://localhost/'484950def test_environ_base_default(app, client, app_ctx):51 @app.route('/')52 def index():53 flask.g.user_agent = flask.request.headers["User-Agent"]54 return flask.request.remote_addr5556 rv = client.get('/')57 assert rv.data == b'127.0.0.1'58 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__596061def test_environ_base_modified(app, client, app_ctx):62 @app.route('/')63 def index():64 flask.g.user_agent = flask.request.headers["User-Agent"]65 return flask.request.remote_addr6667 client.environ_base['REMOTE_ADDR'] = '0.0.0.0'68 client.environ_base['HTTP_USER_AGENT'] = 'Foo'69 rv = client.get('/')70 assert rv.data == b'0.0.0.0'71 assert flask.g.user_agent == 'Foo'7273 client.environ_base['REMOTE_ADDR'] = '0.0.0.1'74 client.environ_base['HTTP_USER_AGENT'] = 'Bar'75 rv = client.get('/')76 assert rv.data == b'0.0.0.1'77 assert flask.g.user_agent == 'Bar'787980def test_client_open_environ(app, client, request):81 @app.route('/index')82 def index():83 return flask.request.remote_addr8485 builder = make_test_environ_builder(app, path='/index', method='GET')86 request.addfinalizer(builder.close)8788 rv = client.open(builder)89 assert rv.data == b'127.0.0.1'9091 environ = builder.get_environ()92 client.environ_base['REMOTE_ADDR'] = '127.0.0.2'93 rv = client.open(environ)94 assert rv.data == b'127.0.0.2'959697def test_specify_url_scheme(app, client):98 @app.route('/')99 def index():100 return flask.request.url101102 ctx = app.test_request_context(url_scheme='https')103 assert ctx.request.url == 'https://localhost/'104105 rv = client.get('/', url_scheme='https')106 assert rv.data == b'https://localhost/'107108109def test_path_is_url(app):110 eb = make_test_environ_builder(app, 'https://example.com/')111 assert eb.url_scheme == 'https'112 assert eb.host == 'example.com'113 assert eb.script_root == ''114 assert eb.path == '/'115116117def test_blueprint_with_subdomain(app, client):118 app.config['SERVER_NAME'] = 'example.com:1234'119 app.config['APPLICATION_ROOT'] = '/foo'120121 bp = flask.Blueprint('company', __name__, subdomain='xxx')122123 @bp.route('/')124 def index():125 return flask.request.url126127 app.register_blueprint(bp)128129 ctx = app.test_request_context('/', subdomain='xxx')130 assert ctx.request.url == 'http://xxx.example.com:1234/foo/'131 assert ctx.request.blueprint == bp.name132133 rv = client.get('/', subdomain='xxx')134 assert rv.data == b'http://xxx.example.com:1234/foo/'135136137def test_redirect_keep_session(app, client, app_ctx):138 @app.route('/', methods=['GET', 'POST'])139 def index():140 if flask.request.method == 'POST':141 return flask.redirect('/getsession')142 flask.session['data'] = 'foo'143 return 'index'144145 @app.route('/getsession')146 def get_session():147 return flask.session.get('data', '<missing>')148149 with client:150 rv = client.get('/getsession')151 assert rv.data == b'<missing>'152153 rv = client.get('/')154 assert rv.data == b'index'155 assert flask.session.get('data') == 'foo'156 rv = client.post('/', data={}, follow_redirects=True)157 assert rv.data == b'foo'158159 # This support requires a new Werkzeug version160 if not hasattr(client, 'redirect_client'):161 assert flask.session.get('data') == 'foo'162163 rv = client.get('/getsession')164 assert rv.data == b'foo'165166167def test_session_transactions(app, client):168 @app.route('/')169 def index():170 return text_type(flask.session['foo'])171172 with client:173 with client.session_transaction() as sess:174 assert len(sess) == 0175 sess['foo'] = [42]176 assert len(sess) == 1177 rv = client.get('/')178 assert rv.data == b'[42]'179 with client.session_transaction() as sess:180 assert len(sess) == 1181 assert sess['foo'] == [42]182183184def test_session_transactions_no_null_sessions():185 app = flask.Flask(__name__)186 app.testing = True187188 with app.test_client() as c:189 with pytest.raises(RuntimeError) as e:190 with c.session_transaction() as sess:191 pass192 assert 'Session backend did not open a session' in str(e.value)193194195def test_session_transactions_keep_context(app, client, req_ctx):196 rv = client.get('/')197 req = flask.request._get_current_object()198 assert req is not None199 with client.session_transaction():200 assert req is flask.request._get_current_object()201202203def test_session_transaction_needs_cookies(app):204 c = app.test_client(use_cookies=False)205 with pytest.raises(RuntimeError) as e:206 with c.session_transaction() as s:207 pass208 assert 'cookies' in str(e.value)209210211def test_test_client_context_binding(app, client):212 app.testing = False213214 @app.route('/')215 def index():216 flask.g.value = 42217 return 'Hello World!'218219 @app.route('/other')220 def other():221 1 // 0222223 with client:224 resp = client.get('/')225 assert flask.g.value == 42226 assert resp.data == b'Hello World!'227 assert resp.status_code == 200228229 resp = client.get('/other')230 assert not hasattr(flask.g, 'value')231 assert b'Internal Server Error' in resp.data232 assert resp.status_code == 500233 flask.g.value = 23234235 try:236 flask.g.value237 except (AttributeError, RuntimeError):238 pass239 else:240 raise AssertionError('some kind of exception expected')241242243def test_reuse_client(client):244 c = client245246 with c:247 assert client.get('/').status_code == 404248249 with c:250 assert client.get('/').status_code == 404251252253def test_test_client_calls_teardown_handlers(app, client):254 called = []255256 @app.teardown_request257 def remember(error):258 called.append(error)259260 with client:261 assert called == []262 client.get('/')263 assert called == []264 assert called == [None]265266 del called[:]267 with client:268 assert called == []269 client.get('/')270 assert called == []271 client.get('/')272 assert called == [None]273 assert called == [None, None]274275276def test_full_url_request(app, client):277 @app.route('/action', methods=['POST'])278 def action():279 return 'x'280281 with client:282 rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})283 assert rv.status_code == 200284 assert 'gin' in flask.request.form285 assert 'vodka' in flask.request.args286287288def test_json_request_and_response(app, client):289 @app.route('/echo', methods=['POST'])290 def echo():291 return jsonify(flask.request.get_json())292293 with client:294 json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}295 rv = client.post('/echo', json=json_data)296297 # Request should be in JSON298 assert flask.request.is_json299 assert flask.request.get_json() == json_data300301 # Response should be in JSON302 assert rv.status_code == 200303 assert rv.is_json304 assert rv.get_json() == json_data305306307def test_subdomain(app, client):308 app.config['SERVER_NAME'] = 'example.com'309310 @app.route('/', subdomain='<company_id>')311 def view(company_id):312 return company_id313314 with app.test_request_context():315 url = flask.url_for('view', company_id='xxx')316317 with client:318 response = client.get(url)319320 assert 200 == response.status_code321 assert b'xxx' == response.data322323324def test_nosubdomain(app, client):325 app.config['SERVER_NAME'] = 'example.com'326327 @app.route('/<company_id>')328 def view(company_id):329 return company_id330331 with app.test_request_context():332 url = flask.url_for('view', company_id='xxx')333334 with client:335 response = client.get(url)336337 assert 200 == response.status_code338 assert b'xxx' == response.data339340341def test_cli_runner_class(app):342 runner = app.test_cli_runner()343 assert isinstance(runner, FlaskCliRunner)344345 class SubRunner(FlaskCliRunner):346 pass347348 app.test_cli_runner_class = SubRunner349 runner = app.test_cli_runner()350 assert isinstance(runner, SubRunner)351352353def test_cli_invoke(app):354 @app.cli.command('hello')355 def hello_command():356 click.echo('Hello, World!')357358 runner = app.test_cli_runner()359 # invoke with command name360 result = runner.invoke(args=['hello'])361 assert 'Hello' in result.output362 # invoke with command object363 result = runner.invoke(hello_command)364 assert 'Hello' in result.output365366367def test_cli_custom_obj(app):368 class NS(object):369 called = False370371 def create_app():372 NS.called = True373 return app374375 @app.cli.command('hello')376 def hello_command():377 click.echo('Hello, World!')378379 script_info = ScriptInfo(create_app=create_app)380 runner = app.test_cli_runner()381 runner.invoke(hello_command, obj=script_info)382 assert NS.called