MCPcopy Create free account
hub / github.com/pallets/flask / FlaskClient

Class FlaskClient

src/flask/testing.py:108–261  ·  view source on GitHub ↗

Works like a regular Werkzeug test client but has knowledge about Flask's contexts to defer the cleanup of the request context until the end of a ``with`` block. For general information about how to use this class refer to :class:`werkzeug.test.Client`. .. versionchanged:: 0.12

Source from the content-addressed store, hash-verified

106
107
108class FlaskClient(Client):
109 """Works like a regular Werkzeug test client but has knowledge about
110 Flask's contexts to defer the cleanup of the request context until
111 the end of a ``with`` block. For general information about how to
112 use this class refer to :class:`werkzeug.test.Client`.
113
114 .. versionchanged:: 0.12
115 `app.test_client()` includes preset default environment, which can be
116 set after instantiation of the `app.test_client()` object in
117 `client.environ_base`.
118
119 Basic usage is outlined in the :doc:`/testing` chapter.
120 """
121
122 application: Flask
123
124 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
125 super().__init__(*args, **kwargs)
126 self.preserve_context = False
127 self._new_contexts: list[t.ContextManager[t.Any]] = []
128 self._context_stack = ExitStack()
129 self.environ_base = {
130 "REMOTE_ADDR": "127.0.0.1",
131 "HTTP_USER_AGENT": f"Werkzeug/{_get_werkzeug_version()}",
132 }
133
134 @contextmanager
135 def session_transaction(
136 self, *args: t.Any, **kwargs: t.Any
137 ) -> t.Iterator[SessionMixin]:
138 """When used in combination with a ``with`` statement this opens a
139 session transaction. This can be used to modify the session that
140 the test client uses. Once the ``with`` block is left the session is
141 stored back.
142
143 ::
144
145 with client.session_transaction() as session:
146 session['value'] = 42
147
148 Internally this is implemented by going through a temporary test
149 request context and since session handling could depend on
150 request variables this function accepts the same arguments as
151 :meth:`~flask.Flask.test_request_context` which are directly
152 passed through.
153 """
154 if self._cookies is None:
155 raise TypeError(
156 "Cookies are disabled. Create a client with 'use_cookies=True'."
157 )
158
159 app = self.application
160 ctx = app.test_request_context(*args, **kwargs)
161 self._add_cookies_to_wsgi(ctx.request.environ)
162
163 with ctx:
164 sess = app.session_interface.open_session(app, ctx.request)
165

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected