Merge branch '2.2.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 67c4c7b, 694183c · Browse files · 4 files·+47 added−58 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+47 added−58 removed
- tests:+12 added−27 removed
- other:+35 added−31 removed
Provenance
- Commit
fa0ceb6- Tree
a1fa2bf- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
67c4c7b- Parent 2
694183c
4 files changed+47 added−58 removed
modified:src/flask/testing.py+35 added-31 removed
9 unmodified lines10 from werkzeug.test import Client11 from werkzeug.wrappers import Request as BaseRequest12 13 from .cli import ScriptInfo14-from .globals import _cv_request14 from .sessions import SessionMixin15 16 if t.TYPE_CHECKING: # pragma: no cover17 from werkzeug.test import TestResponse117 unmodified lines135 request variables this function accepts the same arguments as136 :meth:`~flask.Flask.test_request_context` which are directly137 passed through.138 """140- if self.cookie_jar is None:141- raise RuntimeError(142- "Session transactions only make sense with cookies enabled."139+ # new cookie interface for Werkzeug >= 2.3140+ cookie_storage = self._cookies if hasattr(self, "_cookies") else self.cookie_jar141+142+ if cookie_storage is None:143+ raise TypeError(144+ "Cookies are disabled. Create a client with 'use_cookies=True'."145 )146+147 app = self.application145- environ_overrides = kwargs.setdefault("environ_overrides", {})146- self.cookie_jar.inject_wsgi(environ_overrides)147- outer_reqctx = _cv_request.get(None)148- with app.test_request_context(*args, **kwargs) as c:149- session_interface = app.session_interface150- sess = session_interface.open_session(app, c.request)151- if sess is None:152- raise RuntimeError(153- "Session backend did not open a session. Check the configuration"154- )148+ ctx = app.test_request_context(*args, **kwargs)149 156- # Since we have to open a new request context for the session157- # handling we want to make sure that we hide out own context158- # from the caller. By pushing the original request context159- # (or None) on top of this and popping it we get exactly that160- # behavior. It's important to not use the push and pop161- # methods of the actual request context object since that would162- # mean that cleanup handlers are called163- token = _cv_request.set(outer_reqctx) # type: ignore[arg-type]164- try:165- yield sess166- finally:167- _cv_request.reset(token)150+ if hasattr(self, "_add_cookies_to_wsgi"):151+ self._add_cookies_to_wsgi(ctx.request.environ)152+ else:153+ self.cookie_jar.inject_wsgi(ctx.request.environ) # type: ignore[union-attr]154 169- resp = app.response_class()170- if not session_interface.is_null_session(sess):171- session_interface.save_session(app, sess, resp)172- headers = resp.get_wsgi_headers(c.request.environ)173- self.cookie_jar.extract_wsgi(c.request.environ, headers)155+ with ctx:156+ sess = app.session_interface.open_session(app, ctx.request)157 158+ if sess is None:159+ raise RuntimeError("Session backend did not open a session.")160+161+ yield sess162+ resp = app.response_class()163+164+ if app.session_interface.is_null_session(sess):165+ return166+167+ with ctx:168+ app.session_interface.save_session(app, sess, resp)169+170+ if hasattr(self, "_update_cookies_from_response"):171+ self._update_cookies_from_response(172+ ctx.request.host.partition(":")[0], resp.headers.getlist("Set-Cookie")173+ )174+ else:175+ self.cookie_jar.extract_wsgi( # type: ignore[union-attr]176+ ctx.request.environ, resp.headers177+ )178+179 def _copy_environ(self, other):180 out = {**self.environ_base, **other}181 182 if self.preserve_context:108 unmodified linesmodified:tests/test_basic.py+10 added-6 removed
258 unmodified lines259 flask.session["testing"] = 42260 return "Hello World"261 262 rv = client.get("/", "http://example.com/")263- assert "domain=.example.com" in rv.headers["set-cookie"].lower()264- assert "httponly" in rv.headers["set-cookie"].lower()263+ cookie = rv.headers["set-cookie"].lower()264+ # or condition for Werkzeug < 2.3265+ assert "domain=example.com" in cookie or "domain=.example.com" in cookie266 267 268 def test_session_using_server_name_and_port(app, client):269 app.config.update(SERVER_NAME="example.com:8080")3 unmodified lines273 flask.session["testing"] = 42274 return "Hello World"275 276 rv = client.get("/", "http://example.com:8080/")276- assert "domain=.example.com" in rv.headers["set-cookie"].lower()277- assert "httponly" in rv.headers["set-cookie"].lower()277+ cookie = rv.headers["set-cookie"].lower()278+ # or condition for Werkzeug < 2.3279+ assert "domain=example.com" in cookie or "domain=.example.com" in cookie280 281 282 def test_session_using_server_name_port_and_path(app, client):283 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")53 unmodified lines337 return "Goodbye World"338 339 rv = client.get("/", "http://www.example.com:8080/test/")340 cookie = rv.headers["set-cookie"].lower()341+ # or condition for Werkzeug < 2.3339- assert "domain=.example.com" in cookie342+ assert "domain=example.com" in cookie or "domain=.example.com" in cookie343 assert "path=/" in cookie344 assert "secure" in cookie345 assert "httponly" not in cookie346 assert "samesite" in cookie347 348 rv = client.get("/clear", "http://www.example.com:8080/test/")349 cookie = rv.headers["set-cookie"].lower()350 assert "session=;" in cookie351+ # or condition for Werkzeug < 2.3348- assert "domain=.example.com" in cookie352+ assert "domain=example.com" in cookie or "domain=.example.com" in cookie353 assert "path=/" in cookie354 assert "secure" in cookie355 assert "samesite" in cookie356 1567 unmodified linesmodified:tests/test_json.py-19 removed
265 unmodified lines266 except LookupError:267 return False268 269 270-@pytest.mark.skipif(271- not _has_encoding("euc-kr"), reason="The euc-kr encoding is required."272-)273-def test_modified_url_encoding(app, client):274- class ModifiedRequest(flask.Request):275- url_charset = "euc-kr"276-277- app.request_class = ModifiedRequest278- app.url_map.charset = "euc-kr"279-280- @app.route("/")281- def index():282- return flask.request.args["foo"]283-284- rv = client.get("/", query_string={"foo": "정상처리"}, charset="euc-kr")285- assert rv.status_code == 200286- assert rv.get_data(as_text=True) == "정상처리"287-288-270 def test_json_key_sorting(app, client):271 app.debug = True272 assert app.json.sort_keys273 d = dict.fromkeys(range(20), "foo")73 unmodified linesmodified:tests/test_testing.py+2 added-2 removed
204 unmodified lines205 206 207 def test_session_transaction_needs_cookies(app):208 c = app.test_client(use_cookies=False)209- with pytest.raises(RuntimeError) as e:209+210+ with pytest.raises(TypeError, match="Cookies are disabled."):211 with c.session_transaction():212 pass212- assert "cookies" in str(e.value)213 214 215 def test_test_client_context_binding(app, client):216 app.testing = False187 unmodified lines