aboutsummaryrefslogtreecommitdiffstats
path: root/tests/common_wsgi.py
blob: 845ca171faeda9759df266e64cb9a15075e630f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from dataclasses import dataclass
from types import TracebackType
from typing import Union
from wsgiref.util import setup_testing_defaults


@dataclass
class Response:
    data: bytes
    status: str
    headers: list[tuple[str, str]]
    exc_info: Union[
        None,
        tuple[type[BaseException], BaseException, TracebackType],
        tuple[None, None, None],
    ]


def call_app(app, environ={}):
    def write(_):
        raise AssertionError("write was called, but should not have been")

    status = None
    headers = None
    exc_info = None

    def start_response(s, h, e_i=None):
        nonlocal status, headers, exc_info
        if isinstance(headers, list) and e_i is None:
            raise AssertionError("Start response called twice")
        status = s
        headers = h
        exc_info = e_i
        return write

    setup_testing_defaults(environ)
    if "QUERY_STRING" not in environ:
        environ["QUERY_STRING"] = ""
    resp_iter = app(environ, start_response)
    assert isinstance(status, str)
    assert isinstance(headers, list)
    resp = b"".join(resp_iter)
    if hasattr(resp_iter, "close"):
        resp_iter.close()
    return Response(
        resp,
        status,
        headers,
        exc_info,
    )