test_testing.py
This file
Path
tests/test_testing.py
447 lines · 11.7 KiB · Python
Last changed by
Merge branch '1.0.x'David Lordbefore adoption1351d0a
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.testing4 ~~~~~~~~~~~~~56 Test client and more.78 :copyright: 2010 Pallets9 :license: BSD-3-Clause10"""11import click12import pytest13import werkzeug1415import flask16from flask import appcontext_popped17from flask._compat import text_type18from flask.cli import ScriptInfo19from flask.json import jsonify20from flask.testing import EnvironBuilder21from flask.testing import FlaskCliRunner22from flask.testing import make_test_environ_builder2324try:25 import blinker26except ImportError:27 blinker = None282930def test_environ_defaults_from_config(app, client):31 app.config["SERVER_NAME"] = "example.com:1234"32 app.config["APPLICATION_ROOT"] = "/foo"3334 @app.route("/")35 def index():36 return flask.request.url3738 ctx = app.test_request_context()39 assert ctx.request.url == "http://example.com:1234/foo/"4041 rv = client.get("/")42 assert rv.data == b"http://example.com:1234/foo/"434445def test_environ_defaults(app, client, app_ctx, req_ctx):46 @app.route("/")47 def index():48 return flask.request.url4950 ctx = app.test_request_context()51 assert ctx.request.url == "http://localhost/"52 with client:53 rv = client.get("/")54 assert rv.data == b"http://localhost/"555657def test_environ_base_default(app, client, app_ctx):58 @app.route("/")59 def index():60 flask.g.user_agent = flask.request.headers["User-Agent"]61 return flask.request.remote_addr6263 rv = client.get("/")64 assert rv.data == b"127.0.0.1"65 assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__666768def test_environ_base_modified(app, client, app_ctx):69 @app.route("/")70 def index():71 flask.g.user_agent = flask.request.headers["User-Agent"]72 return flask.request.remote_addr7374 client.environ_base["REMOTE_ADDR"] = "0.0.0.0"75 client.environ_base["HTTP_USER_AGENT"] = "Foo"76 rv = client.get("/")77 assert rv.data == b"0.0.0.0"78 assert flask.g.user_agent == "Foo"7980 client.environ_base["REMOTE_ADDR"] = "0.0.0.1"81 client.environ_base["HTTP_USER_AGENT"] = "Bar"82 rv = client.get("/")83 assert rv.data == b"0.0.0.1"84 assert flask.g.user_agent == "Bar"858687def test_client_open_environ(app, client, request):88 @app.route("/index")89 def index():90 return flask.request.remote_addr9192 builder = EnvironBuilder(app, path="/index", method="GET")93 request.addfinalizer(builder.close)9495 rv = client.open(builder)96 assert rv.data == b"127.0.0.1"9798 environ = builder.get_environ()99 client.environ_base["REMOTE_ADDR"] = "127.0.0.2"100 rv = client.open(environ)101 assert rv.data == b"127.0.0.2"102103104def test_specify_url_scheme(app, client):105 @app.route("/")106 def index():107 return flask.request.url108109 ctx = app.test_request_context(url_scheme="https")110 assert ctx.request.url == "https://localhost/"111112 rv = client.get("/", url_scheme="https")113 assert rv.data == b"https://localhost/"114115116def test_path_is_url(app):117 eb = EnvironBuilder(app, "https://example.com/")118 assert eb.url_scheme == "https"119 assert eb.host == "example.com"120 assert eb.script_root == ""121 assert eb.path == "/"122123124def test_make_test_environ_builder(app):125 with pytest.deprecated_call():126 eb = make_test_environ_builder(app, "https://example.com/")127 assert eb.url_scheme == "https"128 assert eb.host == "example.com"129 assert eb.script_root == ""130 assert eb.path == "/"131132133def test_environbuilder_json_dumps(app):134 """EnvironBuilder.json_dumps() takes settings from the app."""135 app.config["JSON_AS_ASCII"] = False136 eb = EnvironBuilder(app, json=u"\u20ac")137 assert eb.input_stream.read().decode("utf8") == u'"\u20ac"'138139140def test_blueprint_with_subdomain():141 app = flask.Flask(__name__, subdomain_matching=True)142 app.config["SERVER_NAME"] = "example.com:1234"143 app.config["APPLICATION_ROOT"] = "/foo"144 client = app.test_client()145146 bp = flask.Blueprint("company", __name__, subdomain="xxx")147148 @bp.route("/")149 def index():150 return flask.request.url151152 app.register_blueprint(bp)153154 ctx = app.test_request_context("/", subdomain="xxx")155 assert ctx.request.url == "http://xxx.example.com:1234/foo/"156157 with ctx:158 assert ctx.request.blueprint == bp.name159160 rv = client.get("/", subdomain="xxx")161 assert rv.data == b"http://xxx.example.com:1234/foo/"162163164def test_redirect_keep_session(app, client, app_ctx):165 @app.route("/", methods=["GET", "POST"])166 def index():167 if flask.request.method == "POST":168 return flask.redirect("/getsession")169 flask.session["data"] = "foo"170 return "index"171172 @app.route("/getsession")173 def get_session():174 return flask.session.get("data", "<missing>")175176 with client:177 rv = client.get("/getsession")178 assert rv.data == b"<missing>"179180 rv = client.get("/")181 assert rv.data == b"index"182 assert flask.session.get("data") == "foo"183 rv = client.post("/", data={}, follow_redirects=True)184 assert rv.data == b"foo"185186 # This support requires a new Werkzeug version187 if not hasattr(client, "redirect_client"):188 assert flask.session.get("data") == "foo"189190 rv = client.get("/getsession")191 assert rv.data == b"foo"192193194def test_session_transactions(app, client):195 @app.route("/")196 def index():197 return text_type(flask.session["foo"])198199 with client:200 with client.session_transaction() as sess:201 assert len(sess) == 0202 sess["foo"] = [42]203 assert len(sess) == 1204 rv = client.get("/")205 assert rv.data == b"[42]"206 with client.session_transaction() as sess:207 assert len(sess) == 1208 assert sess["foo"] == [42]209210211def test_session_transactions_no_null_sessions():212 app = flask.Flask(__name__)213 app.testing = True214215 with app.test_client() as c:216 with pytest.raises(RuntimeError) as e:217 with c.session_transaction():218 pass219 assert "Session backend did not open a session" in str(e.value)220221222def test_session_transactions_keep_context(app, client, req_ctx):223 client.get("/")224 req = flask.request._get_current_object()225 assert req is not None226 with client.session_transaction():227 assert req is flask.request._get_current_object()228229230def test_session_transaction_needs_cookies(app):231 c = app.test_client(use_cookies=False)232 with pytest.raises(RuntimeError) as e:233 with c.session_transaction():234 pass235 assert "cookies" in str(e.value)236237238def test_test_client_context_binding(app, client):239 app.testing = False240241 @app.route("/")242 def index():243 flask.g.value = 42244 return "Hello World!"245246 @app.route("/other")247 def other():248 1 // 0249250 with client:251 resp = client.get("/")252 assert flask.g.value == 42253 assert resp.data == b"Hello World!"254 assert resp.status_code == 200255256 resp = client.get("/other")257 assert not hasattr(flask.g, "value")258 assert b"Internal Server Error" in resp.data259 assert resp.status_code == 500260 flask.g.value = 23261262 try:263 flask.g.value264 except (AttributeError, RuntimeError):265 pass266 else:267 raise AssertionError("some kind of exception expected")268269270def test_reuse_client(client):271 c = client272273 with c:274 assert client.get("/").status_code == 404275276 with c:277 assert client.get("/").status_code == 404278279280def test_test_client_calls_teardown_handlers(app, client):281 called = []282283 @app.teardown_request284 def remember(error):285 called.append(error)286287 with client:288 assert called == []289 client.get("/")290 assert called == []291 assert called == [None]292293 del called[:]294 with client:295 assert called == []296 client.get("/")297 assert called == []298 client.get("/")299 assert called == [None]300 assert called == [None, None]301302303def test_full_url_request(app, client):304 @app.route("/action", methods=["POST"])305 def action():306 return "x"307308 with client:309 rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})310 assert rv.status_code == 200311 assert "gin" in flask.request.form312 assert "vodka" in flask.request.args313314315def test_json_request_and_response(app, client):316 @app.route("/echo", methods=["POST"])317 def echo():318 return jsonify(flask.request.get_json())319320 with client:321 json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}322 rv = client.post("/echo", json=json_data)323324 # Request should be in JSON325 assert flask.request.is_json326 assert flask.request.get_json() == json_data327328 # Response should be in JSON329 assert rv.status_code == 200330 assert rv.is_json331 assert rv.get_json() == json_data332333334@pytest.mark.skipif(blinker is None, reason="blinker is not installed")335def test_client_json_no_app_context(app, client):336 @app.route("/hello", methods=["POST"])337 def hello():338 return "Hello, {}!".format(flask.request.json["name"])339340 class Namespace(object):341 count = 0342343 def add(self, app):344 self.count += 1345346 ns = Namespace()347348 with appcontext_popped.connected_to(ns.add, app):349 rv = client.post("/hello", json={"name": "Flask"})350351 assert rv.get_data(as_text=True) == "Hello, Flask!"352 assert ns.count == 1353354355def test_subdomain():356 app = flask.Flask(__name__, subdomain_matching=True)357 app.config["SERVER_NAME"] = "example.com"358 client = app.test_client()359360 @app.route("/", subdomain="<company_id>")361 def view(company_id):362 return company_id363364 with app.test_request_context():365 url = flask.url_for("view", company_id="xxx")366367 with client:368 response = client.get(url)369370 assert 200 == response.status_code371 assert b"xxx" == response.data372373374def test_nosubdomain(app, client):375 app.config["SERVER_NAME"] = "example.com"376377 @app.route("/<company_id>")378 def view(company_id):379 return company_id380381 with app.test_request_context():382 url = flask.url_for("view", company_id="xxx")383384 with client:385 response = client.get(url)386387 assert 200 == response.status_code388 assert b"xxx" == response.data389390391def test_cli_runner_class(app):392 runner = app.test_cli_runner()393 assert isinstance(runner, FlaskCliRunner)394395 class SubRunner(FlaskCliRunner):396 pass397398 app.test_cli_runner_class = SubRunner399 runner = app.test_cli_runner()400 assert isinstance(runner, SubRunner)401402403def test_cli_invoke(app):404 @app.cli.command("hello")405 def hello_command():406 click.echo("Hello, World!")407408 runner = app.test_cli_runner()409 # invoke with command name410 result = runner.invoke(args=["hello"])411 assert "Hello" in result.output412 # invoke with command object413 result = runner.invoke(hello_command)414 assert "Hello" in result.output415416417def test_cli_custom_obj(app):418 class NS(object):419 called = False420421 def create_app():422 NS.called = True423 return app424425 @app.cli.command("hello")426 def hello_command():427 click.echo("Hello, World!")428429 script_info = ScriptInfo(create_app=create_app)430 runner = app.test_cli_runner()431 runner.invoke(hello_command, obj=script_info)432 assert NS.called433434435def test_client_pop_all_preserved(app, req_ctx, client):436 @app.route("/")437 def index():438 # stream_with_context pushes a third context, preserved by client439 return flask.Response(flask.stream_with_context("hello"))440441 # req_ctx fixture pushed an initial context, not marked preserved442 with client:443 # request pushes a second request context, preserved by client444 client.get("/")445446 # only req_ctx fixture should still be pushed447 assert flask._request_ctx_stack.top is req_ctx