test_testing.py
This file
Path
tests/test_testing.py
403 lines · 10.6 KiB · Python
Last changed by
Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
History of this fileTake it
1import click2import pytest3import werkzeug45import flask6from flask import appcontext_popped7from flask.cli import ScriptInfo8from flask.globals import _cv_request9from flask.json import jsonify10from flask.testing import EnvironBuilder11from flask.testing import FlaskCliRunner1213try:14 import blinker15except ImportError:16 blinker = None171819def 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 client:42 rv = client.get("/")43 assert rv.data == b"http://localhost/"444546def test_environ_base_default(app, client, app_ctx):47 @app.route("/")48 def index():49 flask.g.user_agent = flask.request.headers["User-Agent"]50 return flask.request.remote_addr5152 rv = client.get("/")53 assert rv.data == b"127.0.0.1"54 assert flask.g.user_agent == f"werkzeug/{werkzeug.__version__}"555657def test_environ_base_modified(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 client.environ_base["REMOTE_ADDR"] = "0.0.0.0"64 client.environ_base["HTTP_USER_AGENT"] = "Foo"65 rv = client.get("/")66 assert rv.data == b"0.0.0.0"67 assert flask.g.user_agent == "Foo"6869 client.environ_base["REMOTE_ADDR"] = "0.0.0.1"70 client.environ_base["HTTP_USER_AGENT"] = "Bar"71 rv = client.get("/")72 assert rv.data == b"0.0.0.1"73 assert flask.g.user_agent == "Bar"747576def test_client_open_environ(app, client, request):77 @app.route("/index")78 def index():79 return flask.request.remote_addr8081 builder = EnvironBuilder(app, path="/index", method="GET")82 request.addfinalizer(builder.close)8384 rv = client.open(builder)85 assert rv.data == b"127.0.0.1"8687 environ = builder.get_environ()88 client.environ_base["REMOTE_ADDR"] = "127.0.0.2"89 rv = client.open(environ)90 assert rv.data == b"127.0.0.2"919293def test_specify_url_scheme(app, client):94 @app.route("/")95 def index():96 return flask.request.url9798 ctx = app.test_request_context(url_scheme="https")99 assert ctx.request.url == "https://localhost/"100101 rv = client.get("/", url_scheme="https")102 assert rv.data == b"https://localhost/"103104105def test_path_is_url(app):106 eb = EnvironBuilder(app, "https://example.com/")107 assert eb.url_scheme == "https"108 assert eb.host == "example.com"109 assert eb.script_root == ""110 assert eb.path == "/"111112113def test_environbuilder_json_dumps(app):114 """EnvironBuilder.json_dumps() takes settings from the app."""115 app.json.ensure_ascii = False116 eb = EnvironBuilder(app, json="\u20ac")117 assert eb.input_stream.read().decode("utf8") == '"\u20ac"'118119120def test_blueprint_with_subdomain():121 app = flask.Flask(__name__, subdomain_matching=True)122 app.config["SERVER_NAME"] = "example.com:1234"123 app.config["APPLICATION_ROOT"] = "/foo"124 client = app.test_client()125126 bp = flask.Blueprint("company", __name__, subdomain="xxx")127128 @bp.route("/")129 def index():130 return flask.request.url131132 app.register_blueprint(bp)133134 ctx = app.test_request_context("/", subdomain="xxx")135 assert ctx.request.url == "http://xxx.example.com:1234/foo/"136137 with ctx:138 assert ctx.request.blueprint == bp.name139140 rv = client.get("/", subdomain="xxx")141 assert rv.data == b"http://xxx.example.com:1234/foo/"142143144def test_redirect_keep_session(app, client, app_ctx):145 @app.route("/", methods=["GET", "POST"])146 def index():147 if flask.request.method == "POST":148 return flask.redirect("/getsession")149 flask.session["data"] = "foo"150 return "index"151152 @app.route("/getsession")153 def get_session():154 return flask.session.get("data", "<missing>")155156 with client:157 rv = client.get("/getsession")158 assert rv.data == b"<missing>"159160 rv = client.get("/")161 assert rv.data == b"index"162 assert flask.session.get("data") == "foo"163164 rv = client.post("/", data={}, follow_redirects=True)165 assert rv.data == b"foo"166 assert flask.session.get("data") == "foo"167168 rv = client.get("/getsession")169 assert rv.data == b"foo"170171172def test_session_transactions(app, client):173 @app.route("/")174 def index():175 return str(flask.session["foo"])176177 with client:178 with client.session_transaction() as sess:179 assert len(sess) == 0180 sess["foo"] = [42]181 assert len(sess) == 1182 rv = client.get("/")183 assert rv.data == b"[42]"184 with client.session_transaction() as sess:185 assert len(sess) == 1186 assert sess["foo"] == [42]187188189def test_session_transactions_no_null_sessions():190 app = flask.Flask(__name__)191192 with app.test_client() as c:193 with pytest.raises(RuntimeError) as e:194 with c.session_transaction():195 pass196 assert "Session backend did not open a session" in str(e.value)197198199def test_session_transactions_keep_context(app, client, req_ctx):200 client.get("/")201 req = flask.request._get_current_object()202 assert req is not None203 with client.session_transaction():204 assert req is flask.request._get_current_object()205206207def test_session_transaction_needs_cookies(app):208 c = app.test_client(use_cookies=False)209 with pytest.raises(RuntimeError) as e:210 with c.session_transaction():211 pass212 assert "cookies" in str(e.value)213214215def test_test_client_context_binding(app, client):216 app.testing = False217218 @app.route("/")219 def index():220 flask.g.value = 42221 return "Hello World!"222223 @app.route("/other")224 def other():225 1 // 0226227 with client:228 resp = client.get("/")229 assert flask.g.value == 42230 assert resp.data == b"Hello World!"231 assert resp.status_code == 200232233 resp = client.get("/other")234 assert not hasattr(flask.g, "value")235 assert b"Internal Server Error" in resp.data236 assert resp.status_code == 500237 flask.g.value = 23238239 try:240 flask.g.value241 except (AttributeError, RuntimeError):242 pass243 else:244 raise AssertionError("some kind of exception expected")245246247def test_reuse_client(client):248 c = client249250 with c:251 assert client.get("/").status_code == 404252253 with c:254 assert client.get("/").status_code == 404255256257def test_full_url_request(app, client):258 @app.route("/action", methods=["POST"])259 def action():260 return "x"261262 with client:263 rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})264 assert rv.status_code == 200265 assert "gin" in flask.request.form266 assert "vodka" in flask.request.args267268269def test_json_request_and_response(app, client):270 @app.route("/echo", methods=["POST"])271 def echo():272 return jsonify(flask.request.get_json())273274 with client:275 json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}276 rv = client.post("/echo", json=json_data)277278 # Request should be in JSON279 assert flask.request.is_json280 assert flask.request.get_json() == json_data281282 # Response should be in JSON283 assert rv.status_code == 200284 assert rv.is_json285 assert rv.get_json() == json_data286287288@pytest.mark.skipif(blinker is None, reason="blinker is not installed")289def test_client_json_no_app_context(app, client):290 @app.route("/hello", methods=["POST"])291 def hello():292 return f"Hello, {flask.request.json['name']}!"293294 class Namespace:295 count = 0296297 def add(self, app):298 self.count += 1299300 ns = Namespace()301302 with appcontext_popped.connected_to(ns.add, app):303 rv = client.post("/hello", json={"name": "Flask"})304305 assert rv.get_data(as_text=True) == "Hello, Flask!"306 assert ns.count == 1307308309def test_subdomain():310 app = flask.Flask(__name__, subdomain_matching=True)311 app.config["SERVER_NAME"] = "example.com"312 client = app.test_client()313314 @app.route("/", subdomain="<company_id>")315 def view(company_id):316 return company_id317318 with app.test_request_context():319 url = flask.url_for("view", company_id="xxx")320321 with client:322 response = client.get(url)323324 assert 200 == response.status_code325 assert b"xxx" == response.data326327328def test_nosubdomain(app, client):329 app.config["SERVER_NAME"] = "example.com"330331 @app.route("/<company_id>")332 def view(company_id):333 return company_id334335 with app.test_request_context():336 url = flask.url_for("view", company_id="xxx")337338 with client:339 response = client.get(url)340341 assert 200 == response.status_code342 assert b"xxx" == response.data343344345def test_cli_runner_class(app):346 runner = app.test_cli_runner()347 assert isinstance(runner, FlaskCliRunner)348349 class SubRunner(FlaskCliRunner):350 pass351352 app.test_cli_runner_class = SubRunner353 runner = app.test_cli_runner()354 assert isinstance(runner, SubRunner)355356357def test_cli_invoke(app):358 @app.cli.command("hello")359 def hello_command():360 click.echo("Hello, World!")361362 runner = app.test_cli_runner()363 # invoke with command name364 result = runner.invoke(args=["hello"])365 assert "Hello" in result.output366 # invoke with command object367 result = runner.invoke(hello_command)368 assert "Hello" in result.output369370371def test_cli_custom_obj(app):372 class NS:373 called = False374375 def create_app():376 NS.called = True377 return app378379 @app.cli.command("hello")380 def hello_command():381 click.echo("Hello, World!")382383 script_info = ScriptInfo(create_app=create_app)384 runner = app.test_cli_runner()385 runner.invoke(hello_command, obj=script_info)386 assert NS.called387388389def test_client_pop_all_preserved(app, req_ctx, client):390 @app.route("/")391 def index():392 # stream_with_context pushes a third context, preserved by response393 return flask.stream_with_context("hello")394395 # req_ctx fixture pushed an initial context396 with client:397 # request pushes a second request context, preserved by client398 rv = client.get("/")399400 # close the response, releasing the context held by stream_with_context401 rv.close()402 # only req_ctx fixture should still be pushed403 assert _cv_request.get(None) is req_ctx