test_testing.py
This file
Path
tests/test_testing.py
398 lines · 10.3 KiB · Python
Last changed by
fix devDavid Lordbefore adoption329c32b
History of this fileTake it
1import importlib.metadata23import click4import pytest56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfo9from flask.globals import _cv_app10from flask.json import jsonify11from flask.testing import EnvironBuilder12from flask.testing import FlaskCliRunner131415def test_environ_defaults_from_config(app, client):16 app.config["SERVER_NAME"] = "example.com:1234"17 app.config["APPLICATION_ROOT"] = "/foo"1819 @app.route("/")20 def index():21 return flask.request.url2223 ctx = app.test_request_context()24 assert ctx.request.url == "http://example.com:1234/foo/"2526 rv = client.get("/")27 assert rv.data == b"http://example.com:1234/foo/"282930def test_environ_defaults(app, client, app_ctx, req_ctx):31 @app.route("/")32 def index():33 return flask.request.url3435 ctx = app.test_request_context()36 assert ctx.request.url == "http://localhost/"37 with client:38 rv = client.get("/")39 assert rv.data == b"http://localhost/"404142def test_environ_base_default(app, client):43 @app.route("/")44 def index():45 flask.g.remote_addr = flask.request.remote_addr46 flask.g.user_agent = str(flask.request.user_agent)47 return ""4849 with client:50 client.get("/")51 assert flask.g.remote_addr == "127.0.0.1"52 assert flask.g.user_agent == (53 f"Werkzeug/{importlib.metadata.version('werkzeug')}"54 )555657def test_environ_base_modified(app, client):58 @app.route("/")59 def index():60 flask.g.remote_addr = flask.request.remote_addr61 flask.g.user_agent = str(flask.request.user_agent)62 return ""6364 client.environ_base["REMOTE_ADDR"] = "192.168.0.22"65 client.environ_base["HTTP_USER_AGENT"] = "Foo"6667 with client:68 client.get("/")69 assert flask.g.remote_addr == "192.168.0.22"70 assert flask.g.user_agent == "Foo"717273def test_client_open_environ(app, client, request):74 @app.route("/index")75 def index():76 return flask.request.remote_addr7778 builder = EnvironBuilder(app, path="/index", method="GET")7980 rv = client.open(builder)81 assert rv.data == b"127.0.0.1"8283 environ = builder.get_environ()84 client.environ_base["REMOTE_ADDR"] = "127.0.0.2"85 rv = client.open(environ)86 assert rv.data == b"127.0.0.2"878889def test_specify_url_scheme(app, client):90 @app.route("/")91 def index():92 return flask.request.url9394 ctx = app.test_request_context(url_scheme="https")95 assert ctx.request.url == "https://localhost/"9697 rv = client.get("/", url_scheme="https")98 assert rv.data == b"https://localhost/"99100101def test_path_is_url(app):102 eb = EnvironBuilder(app, "https://example.com/")103 assert eb.url_scheme == "https"104 assert eb.host == "example.com"105 assert eb.script_root == ""106 assert eb.path == "/"107108109def test_environbuilder_json_dumps(app):110 """EnvironBuilder.json_dumps() takes settings from the app."""111 app.json.ensure_ascii = False112 eb = EnvironBuilder(app, json="\u20ac")113 assert eb.input_stream.read().decode("utf8") == '"\u20ac"'114115116def test_blueprint_with_subdomain():117 app = flask.Flask(__name__, subdomain_matching=True)118 app.config["SERVER_NAME"] = "example.com:1234"119 app.config["APPLICATION_ROOT"] = "/foo"120 client = app.test_client()121122 bp = flask.Blueprint("company", __name__, subdomain="xxx")123124 @bp.route("/")125 def index():126 return flask.request.url127128 app.register_blueprint(bp)129130 ctx = app.test_request_context("/", subdomain="xxx")131 assert ctx.request.url == "http://xxx.example.com:1234/foo/"132133 with ctx:134 assert ctx.request.blueprint == bp.name135136 rv = client.get("/", subdomain="xxx")137 assert rv.data == b"http://xxx.example.com:1234/foo/"138139140def test_redirect_session(app, client, app_ctx):141 @app.route("/redirect")142 def index():143 flask.session["redirect"] = True144 return flask.redirect("/target")145146 @app.route("/target")147 def get_session():148 flask.session["target"] = True149 return ""150151 with client:152 client.get("/redirect", follow_redirects=True)153 assert flask.session["redirect"] is True154 assert flask.session["target"] is True155156157def test_session_transactions(app, client):158 @app.route("/")159 def index():160 return str(flask.session["foo"])161162 with client:163 with client.session_transaction() as sess:164 assert len(sess) == 0165 sess["foo"] = [42]166 assert len(sess) == 1167 rv = client.get("/")168 assert rv.data == b"[42]"169 with client.session_transaction() as sess:170 assert len(sess) == 1171 assert sess["foo"] == [42]172173174def test_session_transaction_ipv6(app):175 base_url = "http://[::1]:8000/"176 client = app.test_client()177178 @app.get("/")179 def index():180 return str(flask.session.get("value"))181182 with client.session_transaction(base_url=base_url) as sess:183 sess["value"] = 42184185 assert client.get("/", base_url=base_url).text == "42"186187188def test_session_transactions_no_null_sessions():189 app = flask.Flask(__name__)190191 with app.test_client() as c:192 with pytest.raises(RuntimeError) as e:193 with c.session_transaction():194 pass195 assert "Session backend did not open a session" in str(e.value)196197198def test_session_transactions_keep_context(app, client, req_ctx):199 client.get("/")200 req = flask.request._get_current_object()201 assert req is not None202 with client.session_transaction():203 assert req is flask.request._get_current_object()204205206def test_session_transaction_needs_cookies(app):207 c = app.test_client(use_cookies=False)208209 with pytest.raises(TypeError, match="Cookies are disabled."):210 with c.session_transaction():211 pass212213214def test_test_client_context_binding(app, client):215 app.testing = False216217 @app.route("/")218 def index():219 flask.g.value = 42220 return "Hello World!"221222 @app.route("/other")223 def other():224 raise ZeroDivisionError225226 with client:227 resp = client.get("/")228 assert flask.g.value == 42229 assert resp.data == b"Hello World!"230 assert resp.status_code == 200231232 with client:233 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 with pytest.raises(RuntimeError):240 flask.g.value # noqa: B018241242243def 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_full_url_request(app, client):254 @app.route("/action", methods=["POST"])255 def action():256 return "x"257258 with client:259 rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})260 assert rv.status_code == 200261 assert "gin" in flask.request.form262 assert "vodka" in flask.request.args263264265def test_json_request_and_response(app, client):266 @app.route("/echo", methods=["POST"])267 def echo():268 return jsonify(flask.request.get_json())269270 with client:271 json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}272 rv = client.post("/echo", json=json_data)273274 # Request should be in JSON275 assert flask.request.is_json276 assert flask.request.get_json() == json_data277278 # Response should be in JSON279 assert rv.status_code == 200280 assert rv.is_json281 assert rv.get_json() == json_data282283284def test_client_json_no_app_context(app, client):285 @app.route("/hello", methods=["POST"])286 def hello():287 return f"Hello, {flask.request.json['name']}!"288289 class Namespace:290 count = 0291292 def add(self, app):293 self.count += 1294295 ns = Namespace()296297 with appcontext_popped.connected_to(ns.add, app):298 rv = client.post("/hello", json={"name": "Flask"})299300 assert rv.get_data(as_text=True) == "Hello, Flask!"301 assert ns.count == 1302303304def test_subdomain():305 app = flask.Flask(__name__, subdomain_matching=True)306 app.config["SERVER_NAME"] = "example.com"307 client = app.test_client()308309 @app.route("/", subdomain="<company_id>")310 def view(company_id):311 return company_id312313 with app.test_request_context():314 url = flask.url_for("view", company_id="xxx")315316 with client:317 response = client.get(url)318319 assert 200 == response.status_code320 assert b"xxx" == response.data321322323def test_nosubdomain(app, client):324 app.config["SERVER_NAME"] = "example.com"325326 @app.route("/<company_id>")327 def view(company_id):328 return company_id329330 with app.test_request_context():331 url = flask.url_for("view", company_id="xxx")332333 with client:334 response = client.get(url)335336 assert 200 == response.status_code337 assert b"xxx" == response.data338339340def test_cli_runner_class(app):341 runner = app.test_cli_runner()342 assert isinstance(runner, FlaskCliRunner)343344 class SubRunner(FlaskCliRunner):345 pass346347 app.test_cli_runner_class = SubRunner348 runner = app.test_cli_runner()349 assert isinstance(runner, SubRunner)350351352def test_cli_invoke(app):353 @app.cli.command("hello")354 def hello_command():355 click.echo("Hello, World!")356357 runner = app.test_cli_runner()358 # invoke with command name359 result = runner.invoke(args=["hello"])360 assert "Hello" in result.output361 # invoke with command object362 result = runner.invoke(hello_command)363 assert "Hello" in result.output364365366def test_cli_custom_obj(app):367 class NS:368 called = False369370 def create_app():371 NS.called = True372 return app373374 @app.cli.command("hello")375 def hello_command():376 click.echo("Hello, World!")377378 script_info = ScriptInfo(create_app=create_app)379 runner = app.test_cli_runner()380 runner.invoke(hello_command, obj=script_info)381 assert NS.called382383384def test_client_pop_all_preserved(app, req_ctx, client):385 @app.route("/")386 def index():387 # stream_with_context pushes a third context, preserved by response388 return flask.stream_with_context("hello")389390 # req_ctx fixture pushed an initial context391 with client:392 # request pushes a second request context, preserved by client393 rv = client.get("/")394395 # close the response, releasing the context held by stream_with_context396 rv.close()397 # only req_ctx fixture should still be pushed398 assert _cv_app.get(None) is req_ctx