forked from encode/starlette
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_testclient.py
153 lines (114 loc) Β· 4.32 KB
/
test_testclient.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import anyio
import pytest
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
from starlette.websockets import WebSocket, WebSocketDisconnect
mock_service = Starlette()
@mock_service.route("/")
def mock_service_endpoint(request):
return JSONResponse({"mock": "example"})
app = Starlette()
@app.route("/")
def homepage(request):
client = TestClient(mock_service)
response = client.get("/")
return JSONResponse(response.json())
startup_error_app = Starlette()
@startup_error_app.on_event("startup")
def startup():
raise RuntimeError()
def test_use_testclient_in_endpoint():
"""
We should be able to use the test client within applications.
This is useful if we need to mock out other services,
during tests or in development.
"""
client = TestClient(app)
response = client.get("/")
assert response.json() == {"mock": "example"}
def test_use_testclient_as_contextmanager():
with TestClient(app):
pass
def test_error_on_startup():
with pytest.raises(RuntimeError):
with TestClient(startup_error_app):
pass # pragma: no cover
def test_exception_in_middleware():
class MiddlewareException(Exception):
pass
class BrokenMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
raise MiddlewareException()
broken_middleware = Starlette(middleware=[Middleware(BrokenMiddleware)])
with pytest.raises(MiddlewareException):
with TestClient(broken_middleware):
pass # pragma: no cover
def test_testclient_asgi2():
def app(scope):
async def inner(receive, send):
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/plain"]],
}
)
await send({"type": "http.response.body", "body": b"Hello, world!"})
return inner
client = TestClient(app)
response = client.get("/")
assert response.text == "Hello, world!"
def test_testclient_asgi3():
async def app(scope, receive, send):
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/plain"]],
}
)
await send({"type": "http.response.body", "body": b"Hello, world!"})
client = TestClient(app)
response = client.get("/")
assert response.text == "Hello, world!"
def test_websocket_blocking_receive():
def app(scope):
async def respond(websocket):
await websocket.send_json({"message": "test"})
async def asgi(receive, send):
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
async with anyio.create_task_group() as task_group:
task_group.start_soon(respond, websocket)
try:
# this will block as the client does not send us data
# it should not prevent `respond` from executing though
await websocket.receive_json()
except WebSocketDisconnect:
pass
return asgi
client = TestClient(app)
with client.websocket_connect("/") as websocket:
data = websocket.receive_json()
assert data == {"message": "test"}
def test_backend_name(request):
"""
Test that the tests are defaulting to the correct backend and that a new
instance of TestClient can be created using different backend options.
"""
# client created using monkeypatched async_backend
client1 = TestClient(mock_service)
if "trio" in request.keywords:
client2 = TestClient(mock_service, backend="asyncio")
assert client1.async_backend["backend"] == "trio"
assert client2.async_backend["backend"] == "asyncio"
elif "asyncio" in request.keywords:
client2 = TestClient(mock_service, backend="trio")
assert client1.async_backend["backend"] == "asyncio"
assert client2.async_backend["backend"] == "trio"
else:
pytest.fail("Unknown backend") # pragma: nocover