test_testing.py
This file
Path
tests/test_testing.py
413 lines · 10.6 KiB · Python
Last changed by
Merge pull request #3206 from pallets/test-client-jsonDavid Lordbefore adoption3dc84ec
History of this fileTake it
The walk stopped after 200 commits: lines older than 8207b15 point at it.
fix formattingDavid Lordbefore adoption8207b15
lines 1–7why, one step back1# -*- coding: utf-8 -*-2"""3 tests.testing4 ~~~~~~~~~~~~~56 Test client and more.7Merge pull request #2624 from pallets/metadataDavid Lordbefore adoption4309c7c
line 8why, one step back8 :copyright: © 2010 by the Pallets team.fix formattingDavid Lordbefore adoption8207b15
lines 9–10why, one step back9 :license: BSD, see LICENSE for more details.10"""Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
line 11why, one step back11import clickfix formattingDavid Lordbefore adoption8207b15
lines 12–16why, one step back12import pytest1314import flask15import werkzeug16Merge pull request #3206 from pallets/test-client-jsonDavid Lordbefore adoption3dc84ec
line 17why, one step back17from flask import appcontext_poppedfix formattingDavid Lordbefore adoption8207b15
line 18why, one step back18from flask._compat import text_typeMerge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
line 19why, one step back19from flask.cli import ScriptInfofix formattingDavid Lordbefore adoption8207b15
line 20why, one step back20from flask.json import jsonifyMerge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
line 21why, one step back21from flask.testing import make_test_environ_builder, FlaskCliRunnerfix formattingDavid Lordbefore adoption8207b15
line 22why, one step back22Merge pull request #3206 from pallets/test-client-jsonDavid Lordbefore adoption3dc84ec
lines 23–26why, one step back23try:24 import blinker25except ImportError:26 blinker = Nonefix formattingDavid Lordbefore adoption8207b15
line 27why, one step back27Merge pull request #3206 from pallets/test-client-jsonDavid Lordbefore adoption3dc84ec
line 28why, one step back28fix formattingDavid Lordbefore adoption8207b15
lines 29–83why, one step back29def test_environ_defaults_from_config(app, client):30 app.config['SERVER_NAME'] = 'example.com:1234'31 app.config['APPLICATION_ROOT'] = '/foo'3233 @app.route('/')34 def index():35 return flask.request.url3637 ctx = app.test_request_context()38 assert ctx.request.url == 'http://example.com:1234/foo/'3940 rv = client.get('/')41 assert rv.data == b'http://example.com:1234/foo/'424344def test_environ_defaults(app, client, app_ctx, req_ctx):45 @app.route('/')46 def index():47 return flask.request.url4849 ctx = app.test_request_context()50 assert ctx.request.url == 'http://localhost/'51 with client:52 rv = client.get('/')53 assert rv.data == b'http://localhost/'545556def test_environ_base_default(app, client, app_ctx):57 @app.route('/')58 def index():59 flask.g.user_agent = flask.request.headers["User-Agent"]60 return flask.request.remote_addr6162 rv = client.get('/')63 assert rv.data == b'127.0.0.1'64 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__656667def test_environ_base_modified(app, client, app_ctx):68 @app.route('/')69 def index():70 flask.g.user_agent = flask.request.headers["User-Agent"]71 return flask.request.remote_addr7273 client.environ_base['REMOTE_ADDR'] = '0.0.0.0'74 client.environ_base['HTTP_USER_AGENT'] = 'Foo'75 rv = client.get('/')76 assert rv.data == b'0.0.0.0'77 assert flask.g.user_agent == 'Foo'7879 client.environ_base['REMOTE_ADDR'] = '0.0.0.1'80 client.environ_base['HTTP_USER_AGENT'] = 'Bar'81 rv = client.get('/')82 assert rv.data == b'0.0.0.1'83 assert flask.g.user_agent == 'Bar'support passing environ to test client (#2412)David Lordbefore adoption59f7966
lines 84–100why, one step back848586def test_client_open_environ(app, client, request):87 @app.route('/index')88 def index():89 return flask.request.remote_addr9091 builder = make_test_environ_builder(app, path='/index', method='GET')92 request.addfinalizer(builder.close)9394 rv = client.open(builder)95 assert rv.data == b'127.0.0.1'9697 environ = builder.get_environ()98 client.environ_base['REMOTE_ADDR'] = '127.0.0.2'99 rv = client.open(environ)100 assert rv.data == b'127.0.0.2'fix formattingDavid Lordbefore adoption8207b15
lines 101–114why, one step back101102103def test_specify_url_scheme(app, client):104 @app.route('/')105 def index():106 return flask.request.url107108 ctx = app.test_request_context(url_scheme='https')109 assert ctx.request.url == 'https://localhost/'110111 rv = client.get('/', url_scheme='https')112 assert rv.data == b'https://localhost/'113114Merge pull request #2430 from erebus1/env_url_scheme_fixDavid Lordbefore adoption85fa8aa
lines 115–122why, one step back115def test_path_is_url(app):116 eb = make_test_environ_builder(app, 'https://example.com/')117 assert eb.url_scheme == 'https'118 assert eb.host == 'example.com'119 assert eb.script_root == ''120 assert eb.path == '/'121122Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20
lines 123–124why, one step back123def test_blueprint_with_subdomain():124 app = flask.Flask(__name__, subdomain_matching=True)fix formattingDavid Lordbefore adoption8207b15
lines 125–126why, one step back125 app.config['SERVER_NAME'] = 'example.com:1234'126 app.config['APPLICATION_ROOT'] = '/foo'Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20
line 127why, one step back127 client = app.test_client()fix formattingDavid Lordbefore adoption8207b15
lines 128–312why, one step back128129 bp = flask.Blueprint('company', __name__, subdomain='xxx')130131 @bp.route('/')132 def index():133 return flask.request.url134135 app.register_blueprint(bp)136137 ctx = app.test_request_context('/', subdomain='xxx')138 assert ctx.request.url == 'http://xxx.example.com:1234/foo/'139 assert ctx.request.blueprint == bp.name140141 rv = client.get('/', subdomain='xxx')142 assert rv.data == b'http://xxx.example.com:1234/foo/'143144145def test_redirect_keep_session(app, client, app_ctx):146 @app.route('/', methods=['GET', 'POST'])147 def index():148 if flask.request.method == 'POST':149 return flask.redirect('/getsession')150 flask.session['data'] = 'foo'151 return 'index'152153 @app.route('/getsession')154 def get_session():155 return flask.session.get('data', '<missing>')156157 with client:158 rv = client.get('/getsession')159 assert rv.data == b'<missing>'160161 rv = client.get('/')162 assert rv.data == b'index'163 assert flask.session.get('data') == 'foo'164 rv = client.post('/', data={}, follow_redirects=True)165 assert rv.data == b'foo'166167 # This support requires a new Werkzeug version168 if not hasattr(client, 'redirect_client'):169 assert flask.session.get('data') == 'foo'170171 rv = client.get('/getsession')172 assert rv.data == b'foo'173174175def test_session_transactions(app, client):176 @app.route('/')177 def index():178 return text_type(flask.session['foo'])179180 with client:181 with client.session_transaction() as sess:182 assert len(sess) == 0183 sess['foo'] = [42]184 assert len(sess) == 1185 rv = client.get('/')186 assert rv.data == b'[42]'187 with client.session_transaction() as sess:188 assert len(sess) == 1189 assert sess['foo'] == [42]190191192def test_session_transactions_no_null_sessions():193 app = flask.Flask(__name__)194 app.testing = True195196 with app.test_client() as c:197 with pytest.raises(RuntimeError) as e:198 with c.session_transaction() as sess:199 pass200 assert 'Session backend did not open a session' in str(e.value)201202203def test_session_transactions_keep_context(app, client, req_ctx):204 rv = client.get('/')205 req = flask.request._get_current_object()206 assert req is not None207 with client.session_transaction():208 assert req is flask.request._get_current_object()209210211def test_session_transaction_needs_cookies(app):212 c = app.test_client(use_cookies=False)213 with pytest.raises(RuntimeError) as e:214 with c.session_transaction() as s:215 pass216 assert 'cookies' in str(e.value)217218219def test_test_client_context_binding(app, client):220 app.testing = False221222 @app.route('/')223 def index():224 flask.g.value = 42225 return 'Hello World!'226227 @app.route('/other')228 def other():229 1 // 0230231 with client:232 resp = client.get('/')233 assert flask.g.value == 42234 assert resp.data == b'Hello World!'235 assert resp.status_code == 200236237 resp = client.get('/other')238 assert not hasattr(flask.g, 'value')239 assert b'Internal Server Error' in resp.data240 assert resp.status_code == 500241 flask.g.value = 23242243 try:244 flask.g.value245 except (AttributeError, RuntimeError):246 pass247 else:248 raise AssertionError('some kind of exception expected')249250251def test_reuse_client(client):252 c = client253254 with c:255 assert client.get('/').status_code == 404256257 with c:258 assert client.get('/').status_code == 404259260261def test_test_client_calls_teardown_handlers(app, client):262 called = []263264 @app.teardown_request265 def remember(error):266 called.append(error)267268 with client:269 assert called == []270 client.get('/')271 assert called == []272 assert called == [None]273274 del called[:]275 with client:276 assert called == []277 client.get('/')278 assert called == []279 client.get('/')280 assert called == [None]281 assert called == [None, None]282283284def test_full_url_request(app, client):285 @app.route('/action', methods=['POST'])286 def action():287 return 'x'288289 with client:290 rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})291 assert rv.status_code == 200292 assert 'gin' in flask.request.form293 assert 'vodka' in flask.request.args294295296def test_json_request_and_response(app, client):297 @app.route('/echo', methods=['POST'])298 def echo():299 return jsonify(flask.request.get_json())300301 with client:302 json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}303 rv = client.post('/echo', json=json_data)304305 # Request should be in JSON306 assert flask.request.is_json307 assert flask.request.get_json() == json_data308309 # Response should be in JSON310 assert rv.status_code == 200311 assert rv.is_json312 assert rv.get_json() == json_dataMerge pull request #3206 from pallets/test-client-jsonDavid Lordbefore adoption3dc84ec
lines 313–333why, one step back313314315@pytest.mark.skipif(blinker is None, reason="blinker is not installed")316def test_client_json_no_app_context(app, client):317 @app.route("/hello", methods=["POST"])318 def hello():319 return "Hello, {}!".format(flask.request.json["name"])320321 class Namespace(object):322 count = 0323324 def add(self, app):325 self.count += 1326327 ns = Namespace()328329 with appcontext_popped.connected_to(ns.add, app):330 rv = client.post("/hello", json={"name": "Flask"})331332 assert rv.get_data(as_text=True) == "Hello, Flask!"333 assert ns.count == 1fix formattingDavid Lordbefore adoption8207b15
lines 334–335why, one step back334335Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20
lines 336–337why, one step back336def test_subdomain():337 app = flask.Flask(__name__, subdomain_matching=True)fix formattingDavid Lordbefore adoption8207b15
line 338why, one step back338 app.config['SERVER_NAME'] = 'example.com'Merge pull request #2635 from pallets/feature/server-name-routingDavid Lordbefore adoptionf808c20
line 339why, one step back339 client = app.test_client()fix formattingDavid Lordbefore adoption8207b15
lines 340–369why, one step back340341 @app.route('/', subdomain='<company_id>')342 def view(company_id):343 return company_id344345 with app.test_request_context():346 url = flask.url_for('view', company_id='xxx')347348 with client:349 response = client.get(url)350351 assert 200 == response.status_code352 assert b'xxx' == response.data353354355def test_nosubdomain(app, client):356 app.config['SERVER_NAME'] = 'example.com'357358 @app.route('/<company_id>')359 def view(company_id):360 return company_id361362 with app.test_request_context():363 url = flask.url_for('view', company_id='xxx')364365 with client:366 response = client.get(url)367368 assert 200 == response.status_code369 assert b'xxx' == response.dataMerge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 370–413why, one step back370371372def test_cli_runner_class(app):373 runner = app.test_cli_runner()374 assert isinstance(runner, FlaskCliRunner)375376 class SubRunner(FlaskCliRunner):377 pass378379 app.test_cli_runner_class = SubRunner380 runner = app.test_cli_runner()381 assert isinstance(runner, SubRunner)382383384def test_cli_invoke(app):385 @app.cli.command('hello')386 def hello_command():387 click.echo('Hello, World!')388389 runner = app.test_cli_runner()390 # invoke with command name391 result = runner.invoke(args=['hello'])392 assert 'Hello' in result.output393 # invoke with command object394 result = runner.invoke(hello_command)395 assert 'Hello' in result.output396397398def test_cli_custom_obj(app):399 class NS(object):400 called = False401402 def create_app():403 NS.called = True404 return app405406 @app.cli.command('hello')407 def hello_command():408 click.echo('Hello, World!')409410 script_info = ScriptInfo(create_app=create_app)411 runner = app.test_cli_runner()412 runner.invoke(hello_command, obj=script_info)413 assert NS.called