Skip to content
Myr

update test cookie handling for Werkzeug 2.3

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 · parent a30b6e7 · 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

4 files+47 added−58 removed

modified:src/flask/testing.py+35 added-31 removed
9 unmodified lines
10from werkzeug.test import Client11from werkzeug.wrappers import Request as BaseRequest1213from .cli import ScriptInfo14from .globals import _cv_request14from .sessions import SessionMixin1516if t.TYPE_CHECKING: # pragma: no cover17 from werkzeug.test import TestResponse
117 unmodified lines
135 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_jar141142 if cookie_storage is None:143 raise TypeError(144 "Cookies are disabled. Create a client with 'use_cookies=True'."145 )146147 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)149156 # 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]154169 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)157158 if sess is None:159 raise RuntimeError("Session backend did not open a session.")160161 yield sess162 resp = app.response_class()163164 if app.session_interface.is_null_session(sess):165 return166167 with ctx:168 app.session_interface.save_session(app, sess, resp)169170 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 )178179 def _copy_environ(self, other):180 out = {**self.environ_base, **other}181182 if self.preserve_context:
108 unmodified lines
modified:tests/test_basic.py+10 added-6 removed
259 unmodified lines
260 flask.session["testing"] = 42261 return "Hello World"262263 rv = client.get("/", "http://example.com/")264 assert "domain=.example.com" in rv.headers["set-cookie"].lower()265 assert "httponly" in rv.headers["set-cookie"].lower()264 cookie = rv.headers["set-cookie"].lower()265 # or condition for Werkzeug < 2.3266 assert "domain=example.com" in cookie or "domain=.example.com" in cookie267268269def test_session_using_server_name_and_port(app, client):270 app.config.update(SERVER_NAME="example.com:8080")
3 unmodified lines
274 flask.session["testing"] = 42275 return "Hello World"276277 rv = client.get("/", "http://example.com:8080/")277 assert "domain=.example.com" in rv.headers["set-cookie"].lower()278 assert "httponly" in rv.headers["set-cookie"].lower()278 cookie = rv.headers["set-cookie"].lower()279 # or condition for Werkzeug < 2.3280 assert "domain=example.com" in cookie or "domain=.example.com" in cookie281282283def test_session_using_server_name_port_and_path(app, client):284 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")
53 unmodified lines
338 return "Goodbye World"339340 rv = client.get("/", "http://www.example.com:8080/test/")341 cookie = rv.headers["set-cookie"].lower()342 # or condition for Werkzeug < 2.3340 assert "domain=.example.com" in cookie343 assert "domain=example.com" in cookie or "domain=.example.com" in cookie344 assert "path=/" in cookie345 assert "secure" in cookie346 assert "httponly" not in cookie347 assert "samesite" in cookie348349 rv = client.get("/clear", "http://www.example.com:8080/test/")350 cookie = rv.headers["set-cookie"].lower()351 assert "session=;" in cookie352 # or condition for Werkzeug < 2.3349 assert "domain=.example.com" in cookie353 assert "domain=example.com" in cookie or "domain=.example.com" in cookie354 assert "path=/" in cookie355 assert "secure" in cookie356 assert "samesite" in cookie357
1605 unmodified lines
modified:tests/test_json.py-19 removed
265 unmodified lines
266 except LookupError:267 return False268269270@pytest.mark.skipif(271 not _has_encoding("euc-kr"), reason="The euc-kr encoding is required."272)273def test_modified_url_encoding(app, client):274 class ModifiedRequest(flask.Request):275 url_charset = "euc-kr"276277 app.request_class = ModifiedRequest278 app.url_map.charset = "euc-kr"279280 @app.route("/")281 def index():282 return flask.request.args["foo"]283284 rv = client.get("/", query_string={"foo": "정상처리"}, charset="euc-kr")285 assert rv.status_code == 200286 assert rv.get_data(as_text=True) == "정상처리"287288270def test_json_key_sorting(app, client):271 app.debug = True272 assert app.json.sort_keys273 d = dict.fromkeys(range(20), "foo")
73 unmodified lines
modified:tests/test_testing.py+2 added-2 removed
204 unmodified lines
205206207def test_session_transaction_needs_cookies(app):208 c = app.test_client(use_cookies=False)209 with pytest.raises(RuntimeError) as e:209210 with pytest.raises(TypeError, match="Cookies are disabled."):211 with c.session_transaction():212 pass212 assert "cookies" in str(e.value)213214215def test_test_client_context_binding(app, client):216 app.testing = False
187 unmodified lines