Skip to content
Myr

test_reqctx.py

This file

Path

tests/test_reqctx.py

249 lines · 6.5 KiB · Python

Last changed by

separate copy per callDavid Lordbefore adoption06ea505

History of this file

Take it

The walk stopped after 200 commits: lines older than 73739a2 point at it.

separate copy per callDavid Lordbefore adoption06ea505

lines 1–3why, one step back
1from __future__ import annotations
23import collections.abc as cabc

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 4why, one step back
4import warnings

separate copy per callDavid Lordbefore adoption06ea505

line 5why, one step back
5from concurrent import futures

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 6–11why, one step back
6
7import pytest89import flask10from flask.sessions import SecureCookieSessionInterface11from flask.sessions import SessionInterface

separate copy per callDavid Lordbefore adoption06ea505

line 12why, one step back
12from flask.testing import FlaskClient

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 13–146why, one step back
13
1415def test_teardown_on_pop(app):16 buffer = []1718 @app.teardown_request19 def end_of_request(exception):20 buffer.append(exception)2122 ctx = app.test_request_context()23 ctx.push()24 assert buffer == []25 ctx.pop()26 assert buffer == [None]272829def test_teardown_with_previous_exception(app):30 buffer = []3132 @app.teardown_request33 def end_of_request(exception):34 buffer.append(exception)3536 try:37 raise Exception("dummy")38 except Exception:39 pass4041 with app.test_request_context():42 assert buffer == []43 assert buffer == [None]444546def test_teardown_with_handled_exception(app):47 buffer = []4849 @app.teardown_request50 def end_of_request(exception):51 buffer.append(exception)5253 with app.test_request_context():54 assert buffer == []55 try:56 raise Exception("dummy")57 except Exception:58 pass59 assert buffer == [None]606162def test_proper_test_request_context(app):63 app.config.update(SERVER_NAME="localhost.localdomain:5000")6465 @app.route("/")66 def index():67 return None6869 @app.route("/", subdomain="foo")70 def sub():71 return None7273 with app.test_request_context("/"):74 assert (75 flask.url_for("index", _external=True)76 == "http://localhost.localdomain:5000/"77 )7879 with app.test_request_context("/"):80 assert (81 flask.url_for("sub", _external=True)82 == "http://foo.localhost.localdomain:5000/"83 )8485 # suppress Werkzeug 0.15 warning about name mismatch86 with warnings.catch_warnings():87 warnings.filterwarnings(88 "ignore", "Current server name", UserWarning, "flask.app"89 )90 with app.test_request_context(91 "/", environ_overrides={"HTTP_HOST": "localhost"}92 ):93 pass9495 app.config.update(SERVER_NAME="localhost")96 with app.test_request_context("/", environ_overrides={"SERVER_NAME": "localhost"}):97 pass9899 app.config.update(SERVER_NAME="localhost:80")100 with app.test_request_context(101 "/", environ_overrides={"SERVER_NAME": "localhost:80"}102 ):103 pass104105106def test_context_binding(app):107 @app.route("/")108 def index():109 return f"Hello {flask.request.args['name']}!"110111 @app.route("/meh")112 def meh():113 return flask.request.url114115 with app.test_request_context("/?name=World"):116 assert index() == "Hello World!"117 with app.test_request_context("/meh"):118 assert meh() == "http://localhost/meh"119 assert not flask.request120121122def test_context_test(app):123 assert not flask.request124 assert not flask.has_request_context()125 ctx = app.test_request_context()126 ctx.push()127 try:128 assert flask.request129 assert flask.has_request_context()130 finally:131 ctx.pop()132133134def test_manual_context_binding(app):135 @app.route("/")136 def index():137 return f"Hello {flask.request.args['name']}!"138139 ctx = app.test_request_context("/?name=World")140 ctx.push()141 assert index() == "Hello World!"142 ctx.pop()143 with pytest.raises(RuntimeError):144 index()145146

separate copy per callDavid Lordbefore adoption06ea505

lines 147–152why, one step back
147def test_copy_context_thread(
148 request: pytest.FixtureRequest, app: flask.Flask, client: FlaskClient149) -> None:150 executor = futures.ThreadPoolExecutor(max_workers=2)151 request.addfinalizer(lambda: executor.shutdown(cancel_futures=True))152 result: cabc.Iterator[int] | None = None

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 153why, one step back
153

separate copy per callDavid Lordbefore adoption06ea505

lines 154–156why, one step back
154 @app.route("/")
155 def index():156 flask.session["fizz"] = "buzz"

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 157why, one step back
157

separate copy per callDavid Lordbefore adoption06ea505

lines 158–164why, one step back
158 @flask.copy_current_request_context
159 def work(n: int) -> int:160 assert flask.current_app == app161 assert flask.request.path == "/"162 assert flask.request.args["foo"] == "bar"163 assert flask.session["fizz"] == "buzz"164 return n

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 165why, one step back
165

separate copy per callDavid Lordbefore adoption06ea505

lines 166–168why, one step back
166 nonlocal result
167 result = executor.map(work, range(10))168 return "Hello World!"

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 169why, one step back
169

separate copy per callDavid Lordbefore adoption06ea505

lines 170–171why, one step back
170 rv = client.get(query_string={"foo": "bar"})
171 assert rv.text == "Hello World!"

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 172why, one step back
172

separate copy per callDavid Lordbefore adoption06ea505

lines 173–174why, one step back
173 assert result is not None
174 assert set(result) == set(range(10))

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 175–249why, one step back
175
176177def test_session_error_pops_context():178 class SessionError(Exception):179 pass180181 class FailingSessionInterface(SessionInterface):182 def open_session(self, app, request):183 raise SessionError()184185 class CustomFlask(flask.Flask):186 session_interface = FailingSessionInterface()187188 app = CustomFlask(__name__)189190 @app.route("/")191 def index():192 # shouldn't get here193 AssertionError()194195 response = app.test_client().get("/")196 assert response.status_code == 500197 assert not flask.request198 assert not flask.current_app199200201def test_session_dynamic_cookie_name():202 # This session interface will use a cookie with a different name if the203 # requested url ends with the string "dynamic_cookie"204 class PathAwareSessionInterface(SecureCookieSessionInterface):205 def get_cookie_name(self, app):206 if flask.request.url.endswith("dynamic_cookie"):207 return "dynamic_cookie_name"208 else:209 return super().get_cookie_name(app)210211 class CustomFlask(flask.Flask):212 session_interface = PathAwareSessionInterface()213214 app = CustomFlask(__name__)215 app.secret_key = "secret_key"216217 @app.route("/set", methods=["POST"])218 def set():219 flask.session["value"] = flask.request.form["value"]220 return "value set"221222 @app.route("/get")223 def get():224 v = flask.session.get("value", "None")225 return v226227 @app.route("/set_dynamic_cookie", methods=["POST"])228 def set_dynamic_cookie():229 flask.session["value"] = flask.request.form["value"]230 return "value set"231232 @app.route("/get_dynamic_cookie")233 def get_dynamic_cookie():234 v = flask.session.get("value", "None")235 return v236237 test_client = app.test_client()238239 # first set the cookie in both /set urls but each with a different value240 assert test_client.post("/set", data={"value": "42"}).data == b"value set"241 assert (242 test_client.post("/set_dynamic_cookie", data={"value": "616"}).data243 == b"value set"244 )245246 # now check that the relevant values come back - meaning that different247 # cookies are being used for the urls that end with "dynamic cookie"248 assert test_client.get("/get").data == b"42"249 assert test_client.get("/get_dynamic_cookie").data == b"616"