Flask Test Client API

FlaskClient is a simulated browser that can send requests and verify responses without starting a server.

Throughapp.test_client()Create instance.


Create test client

Method Description
app.test_client(use_cookies=True) Standard creation method. use_cookies=False disables cookie handling
with app.test_client() as client: Context manager. Automatically cleans up the request context on exit.

Request Method

All methods returnTestResponseObject (inherits from Response).

Methods Description
get(path, **kwargs) Send GET request
post(path, **kwargs) Send POST request
put(path, **kwargs) Send PUT request
delete(path, **kwargs) Send DELETE request
patch(path, **kwargs) Send PATCH request
open(path, method, **kwargs) Generic request method; the method must be explicitly specified.

Request parameters (kwargs)

Parameter Description
data Request body (string or bytes). Used for form submission.
json JSON data, automatically serialized with Content-Type: application/json set
query_string URL query parameter string or dictionary
headers Request Headers Dictionary
content_type Custom Content-Type
follow_redirects bool, whether to automatically follow redirects. Default is False.
buffered bool, whether to buffer the response. Default is False.

Response object (TestResponse)

Attributes/Methods Description
status_code HTTP status code (int)
status HTTP status text, such as "200 OK"
data Response body (bytes)
text Get the response body as text (str).
get_json() Parse the response body as JSON. Returns a dict or list.
headers Response headers (Headers object)
location Redirect target URL (only for 3xx responses).
json_module Module used for JSON serialization (default is app.json).

Session Test

Methods Description
session_transaction(**kwargs) Context manager for directly reading and writing the session. Returns a SessionMixin object.

Code Examples

Example

from app import create_app

app = create_app()
app.config["TESTING"] = True

def test_api():
    with app.test_client() as client:
        # GET Request
        resp = client.get("/api/posts")
        assert resp.status_code == 200
        data = resp.get_json()
        assert isinstance(data, list)

        # POST JSON Request
        resp = client.post("/api/posts", json={
            "title": "EXAMPLE Tutorial",
            "body": "Getting Started Content"
        })
        assert resp.status_code == 201
        assert resp.get_json()["title"] == "EXAMPLE Tutorial"

        # Request with Query Parameters
        resp = client.get("/search?q=flask")
        assert b"flask" in resp.data

        # Simulate Logged-In State
        with client.session_transaction() as sess:
            sess["username"] = "example"
        resp = client.get("/dashboard")
        assert b"example" in resp.data

        # Follow Redirects
        resp = client.post("/login", data={
            "username": "admin"
        }, follow_redirects=True)
        assert resp.status_code == 200
other extensions