test_testing.py
This file
Path
tests/test_testing.py
399 lines · 10.4 KiB · Python
Last changed by
bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
History of this fileTake it
The walk stopped after 200 commits: lines older than 660994e point at it.
bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
lines 1–2why, one step back1import importlib.metadata2Merge branch '2.0.x'David Lordbefore adoption660994e
lines 3–8why, one step back3import click4import pytest56import flask7from flask import appcontext_popped8from flask.cli import ScriptInfoMerge pull request #4685 from pgjones/nameDavid Lordbefore adoption5775d1e
line 9why, one step back9from flask.globals import _cv_requestMerge branch '2.0.x'David Lordbefore adoption660994e
lines 10–41why, one step back10from 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/"4041bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
line 42why, one step back42def test_environ_base_default(app, client):Merge branch '2.0.x'David Lordbefore adoption660994e
lines 43–44why, one step back43 @app.route("/")44 def index():bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
lines 45–47why, one step back45 flask.g.remote_addr = flask.request.remote_addr46 flask.g.user_agent = flask.request.user_agent.string47 return ""Merge branch '2.0.x'David Lordbefore adoption660994e
line 48why, one step back48bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
lines 49–54why, one step back49 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 )Merge branch '2.0.x'David Lordbefore adoption660994e
lines 55–56why, one step back5556bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
line 57why, one step back57def test_environ_base_modified(app, client):Merge branch '2.0.x'David Lordbefore adoption660994e
lines 58–59why, one step back58 @app.route("/")59 def index():bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
lines 60–62why, one step back60 flask.g.remote_addr = flask.request.remote_addr61 flask.g.user_agent = flask.request.user_agent.string62 return ""Merge branch '2.0.x'David Lordbefore adoption660994e
line 63why, one step back63bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
line 64why, one step back64 client.environ_base["REMOTE_ADDR"] = "192.168.0.22"Merge branch '2.0.x'David Lordbefore adoption660994e
lines 65–66why, one step back65 client.environ_base["HTTP_USER_AGENT"] = "Foo"66bump werkzeug 2.3.7 (#5231)David Lordbefore adoption90967cc
lines 67–70why, one step back67 with client:68 client.get("/")69 assert flask.g.remote_addr == "192.168.0.22"70 assert flask.g.user_agent == "Foo"Merge branch '2.0.x'David Lordbefore adoption660994e
lines 71–111why, one step back717273def 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")79 request.addfinalizer(builder.close)8081 rv = client.open(builder)82 assert rv.data == b"127.0.0.1"8384 environ = builder.get_environ()85 client.environ_base["REMOTE_ADDR"] = "127.0.0.2"86 rv = client.open(environ)87 assert rv.data == b"127.0.0.2"888990def test_specify_url_scheme(app, client):91 @app.route("/")92 def index():93 return flask.request.url9495 ctx = app.test_request_context(url_scheme="https")96 assert ctx.request.url == "https://localhost/"9798 rv = client.get("/", url_scheme="https")99 assert rv.data == b"https://localhost/"100101102def test_path_is_url(app):103 eb = EnvironBuilder(app, "https://example.com/")104 assert eb.url_scheme == "https"105 assert eb.host == "example.com"106 assert eb.script_root == ""107 assert eb.path == "/"108109110def test_environbuilder_json_dumps(app):111 """EnvironBuilder.json_dumps() takes settings from the app."""Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
line 112why, one step back112 app.json.ensure_ascii = FalseMerge branch '2.0.x'David Lordbefore adoption660994e
lines 113–205why, one step back113 eb = EnvironBuilder(app, json="\u20ac")114 assert eb.input_stream.read().decode("utf8") == '"\u20ac"'115116117def test_blueprint_with_subdomain():118 app = flask.Flask(__name__, subdomain_matching=True)119 app.config["SERVER_NAME"] = "example.com:1234"120 app.config["APPLICATION_ROOT"] = "/foo"121 client = app.test_client()122123 bp = flask.Blueprint("company", __name__, subdomain="xxx")124125 @bp.route("/")126 def index():127 return flask.request.url128129 app.register_blueprint(bp)130131 ctx = app.test_request_context("/", subdomain="xxx")132 assert ctx.request.url == "http://xxx.example.com:1234/foo/"133134 with ctx:135 assert ctx.request.blueprint == bp.name136137 rv = client.get("/", subdomain="xxx")138 assert rv.data == b"http://xxx.example.com:1234/foo/"139140141def test_redirect_keep_session(app, client, app_ctx):142 @app.route("/", methods=["GET", "POST"])143 def index():144 if flask.request.method == "POST":145 return flask.redirect("/getsession")146 flask.session["data"] = "foo"147 return "index"148149 @app.route("/getsession")150 def get_session():151 return flask.session.get("data", "<missing>")152153 with client:154 rv = client.get("/getsession")155 assert rv.data == b"<missing>"156157 rv = client.get("/")158 assert rv.data == b"index"159 assert flask.session.get("data") == "foo"160161 rv = client.post("/", data={}, follow_redirects=True)162 assert rv.data == b"foo"163 assert flask.session.get("data") == "foo"164165 rv = client.get("/getsession")166 assert rv.data == b"foo"167168169def test_session_transactions(app, client):170 @app.route("/")171 def index():172 return str(flask.session["foo"])173174 with client:175 with client.session_transaction() as sess:176 assert len(sess) == 0177 sess["foo"] = [42]178 assert len(sess) == 1179 rv = client.get("/")180 assert rv.data == b"[42]"181 with client.session_transaction() as sess:182 assert len(sess) == 1183 assert sess["foo"] == [42]184185186def test_session_transactions_no_null_sessions():187 app = flask.Flask(__name__)188189 with app.test_client() as c:190 with pytest.raises(RuntimeError) as e:191 with c.session_transaction():192 pass193 assert "Session backend did not open a session" in str(e.value)194195196def test_session_transactions_keep_context(app, client, req_ctx):197 client.get("/")198 req = flask.request._get_current_object()199 assert req is not None200 with client.session_transaction():201 assert req is flask.request._get_current_object()202203204def test_session_transaction_needs_cookies(app):205 c = app.test_client(use_cookies=False)Merge branch '2.2.x'David Lordbefore adoptionfa0ceb6
lines 206–207why, one step back206207 with pytest.raises(TypeError, match="Cookies are disabled."):Merge branch '2.0.x'David Lordbefore adoption660994e
lines 208–387why, one step back208 with c.session_transaction():209 pass210211212def test_test_client_context_binding(app, client):213 app.testing = False214215 @app.route("/")216 def index():217 flask.g.value = 42218 return "Hello World!"219220 @app.route("/other")221 def other():222 1 // 0223224 with client:225 resp = client.get("/")226 assert flask.g.value == 42227 assert resp.data == b"Hello World!"228 assert resp.status_code == 200229230 resp = client.get("/other")231 assert not hasattr(flask.g, "value")232 assert b"Internal Server Error" in resp.data233 assert resp.status_code == 500234 flask.g.value = 23235236 try:237 flask.g.value238 except (AttributeError, RuntimeError):239 pass240 else:241 raise AssertionError("some kind of exception expected")242243244def test_reuse_client(client):245 c = client246247 with c:248 assert client.get("/").status_code == 404249250 with c:251 assert client.get("/").status_code == 404252253254def test_full_url_request(app, client):255 @app.route("/action", methods=["POST"])256 def action():257 return "x"258259 with client:260 rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})261 assert rv.status_code == 200262 assert "gin" in flask.request.form263 assert "vodka" in flask.request.args264265266def test_json_request_and_response(app, client):267 @app.route("/echo", methods=["POST"])268 def echo():269 return jsonify(flask.request.get_json())270271 with client:272 json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}273 rv = client.post("/echo", json=json_data)274275 # Request should be in JSON276 assert flask.request.is_json277 assert flask.request.get_json() == json_data278279 # Response should be in JSON280 assert rv.status_code == 200281 assert rv.is_json282 assert rv.get_json() == json_data283284285def test_client_json_no_app_context(app, client):286 @app.route("/hello", methods=["POST"])287 def hello():288 return f"Hello, {flask.request.json['name']}!"289290 class Namespace:291 count = 0292293 def add(self, app):294 self.count += 1295296 ns = Namespace()297298 with appcontext_popped.connected_to(ns.add, app):299 rv = client.post("/hello", json={"name": "Flask"})300301 assert rv.get_data(as_text=True) == "Hello, Flask!"302 assert ns.count == 1303304305def test_subdomain():306 app = flask.Flask(__name__, subdomain_matching=True)307 app.config["SERVER_NAME"] = "example.com"308 client = app.test_client()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: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.called383384385def test_client_pop_all_preserved(app, req_ctx, client):386 @app.route("/")387 def index():Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697
lines 388–389why, one step back388 # stream_with_context pushes a third context, preserved by response389 return flask.stream_with_context("hello")Merge branch '2.0.x'David Lordbefore adoption660994e
line 390why, one step back390Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697
line 391why, one step back391 # req_ctx fixture pushed an initial contextMerge branch '2.0.x'David Lordbefore adoption660994e
lines 392–393why, one step back392 with client:393 # request pushes a second request context, preserved by clientMerge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697
line 394why, one step back394 rv = client.get("/")Merge branch '2.0.x'David Lordbefore adoption660994e
line 395why, one step back395Merge pull request #4666 from pallets/debug-contextDavid Lordbefore adoption6916697
lines 396–397why, one step back396 # close the response, releasing the context held by stream_with_context397 rv.close()Merge branch '2.0.x'David Lordbefore adoption660994e
line 398why, one step back398 # only req_ctx fixture should still be pushedMerge pull request #4685 from pgjones/nameDavid Lordbefore adoption5775d1e
line 399why, one step back399 assert _cv_request.get(None) is req_ctx