Coverage for tests/test_ws_router.py: 100%

157 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1import functools 1bacde

2 

3import pytest 1bacde

4from fastapi import ( 1bacde

5 APIRouter, 

6 Depends, 

7 FastAPI, 

8 Header, 

9 WebSocket, 

10 WebSocketDisconnect, 

11 status, 

12) 

13from fastapi.middleware import Middleware 1bacde

14from fastapi.testclient import TestClient 1bacde

15 

16router = APIRouter() 1bacde

17prefix_router = APIRouter() 1bacde

18native_prefix_route = APIRouter(prefix="/native") 1bacde

19app = FastAPI() 1bacde

20 

21 

22@app.websocket_route("/") 1bacde

23async def index(websocket: WebSocket): 1bacde

24 await websocket.accept() 1bacde

25 await websocket.send_text("Hello, world!") 1bacde

26 await websocket.close() 1bacde

27 

28 

29@router.websocket_route("/router") 1bacde

30async def routerindex(websocket: WebSocket): 1bacde

31 await websocket.accept() 1bacde

32 await websocket.send_text("Hello, router!") 1bacde

33 await websocket.close() 1bacde

34 

35 

36@prefix_router.websocket_route("/") 1bacde

37async def routerprefixindex(websocket: WebSocket): 1bacde

38 await websocket.accept() 1bacde

39 await websocket.send_text("Hello, router with prefix!") 1bacde

40 await websocket.close() 1bacde

41 

42 

43@router.websocket("/router2") 1bacde

44async def routerindex2(websocket: WebSocket): 1bacde

45 await websocket.accept() 1bacde

46 await websocket.send_text("Hello, router!") 1bacde

47 await websocket.close() 1bacde

48 

49 

50@router.websocket("/router/{pathparam:path}") 1bacde

51async def routerindexparams(websocket: WebSocket, pathparam: str, queryparam: str): 1bacde

52 await websocket.accept() 1bacde

53 await websocket.send_text(pathparam) 1bacde

54 await websocket.send_text(queryparam) 1bacde

55 await websocket.close() 1bacde

56 

57 

58async def ws_dependency(): 1bacde

59 return "Socket Dependency" 1bacde

60 

61 

62@router.websocket("/router-ws-depends/") 1bacde

63async def router_ws_decorator_depends( 1bacde

64 websocket: WebSocket, data=Depends(ws_dependency) 

65): 

66 await websocket.accept() 1bacde

67 await websocket.send_text(data) 1bacde

68 await websocket.close() 1bacde

69 

70 

71@native_prefix_route.websocket("/") 1bacde

72async def router_native_prefix_ws(websocket: WebSocket): 1bacde

73 await websocket.accept() 1bacde

74 await websocket.send_text("Hello, router with native prefix!") 1bacde

75 await websocket.close() 1bacde

76 

77 

78async def ws_dependency_err(): 1bacde

79 raise NotImplementedError() 1bacde

80 

81 

82@router.websocket("/depends-err/") 1bacde

83async def router_ws_depends_err(websocket: WebSocket, data=Depends(ws_dependency_err)): 1bacde

84 pass # pragma: no cover 

85 

86 

87async def ws_dependency_validate(x_missing: str = Header()): 1bacde

88 pass # pragma: no cover 

89 

90 

91@router.websocket("/depends-validate/") 1bacde

92async def router_ws_depends_validate( 1bacde

93 websocket: WebSocket, data=Depends(ws_dependency_validate) 

94): 

95 pass # pragma: no cover 

96 

97 

98class CustomError(Exception): 1bacde

99 pass 1bacde

100 

101 

102@router.websocket("/custom_error/") 1bacde

103async def router_ws_custom_error(websocket: WebSocket): 1bacde

104 raise CustomError() 1bacde

105 

106 

107def make_app(app=None, **kwargs): 1bacde

108 app = app or FastAPI(**kwargs) 1bacde

109 app.include_router(router) 1bacde

110 app.include_router(prefix_router, prefix="/prefix") 1bacde

111 app.include_router(native_prefix_route) 1bacde

112 return app 1bacde

113 

114 

115app = make_app(app) 1bacde

116 

117 

118def test_app(): 1bacde

119 client = TestClient(app) 1bacde

120 with client.websocket_connect("/") as websocket: 1bacde

121 data = websocket.receive_text() 1bacde

122 assert data == "Hello, world!" 1bacde

123 

124 

125def test_router(): 1bacde

126 client = TestClient(app) 1bacde

127 with client.websocket_connect("/router") as websocket: 1bacde

128 data = websocket.receive_text() 1bacde

129 assert data == "Hello, router!" 1bacde

130 

131 

132def test_prefix_router(): 1bacde

133 client = TestClient(app) 1bacde

134 with client.websocket_connect("/prefix/") as websocket: 1bacde

135 data = websocket.receive_text() 1bacde

136 assert data == "Hello, router with prefix!" 1bacde

137 

138 

139def test_native_prefix_router(): 1bacde

140 client = TestClient(app) 1bacde

141 with client.websocket_connect("/native/") as websocket: 1bacde

142 data = websocket.receive_text() 1bacde

143 assert data == "Hello, router with native prefix!" 1bacde

144 

145 

146def test_router2(): 1bacde

147 client = TestClient(app) 1bacde

148 with client.websocket_connect("/router2") as websocket: 1bacde

149 data = websocket.receive_text() 1bacde

150 assert data == "Hello, router!" 1bacde

151 

152 

153def test_router_ws_depends(): 1bacde

154 client = TestClient(app) 1bacde

155 with client.websocket_connect("/router-ws-depends/") as websocket: 1bacde

156 assert websocket.receive_text() == "Socket Dependency" 1bacde

157 

158 

159def test_router_ws_depends_with_override(): 1bacde

160 client = TestClient(app) 1bacde

161 app.dependency_overrides[ws_dependency] = lambda: "Override" # noqa: E731 1bacde

162 with client.websocket_connect("/router-ws-depends/") as websocket: 1bacde

163 assert websocket.receive_text() == "Override" 1bacde

164 

165 

166def test_router_with_params(): 1bacde

167 client = TestClient(app) 1bacde

168 with client.websocket_connect( 1bacde

169 "/router/path/to/file?queryparam=a_query_param" 

170 ) as websocket: 

171 data = websocket.receive_text() 1bacde

172 assert data == "path/to/file" 1bacde

173 data = websocket.receive_text() 1bacde

174 assert data == "a_query_param" 1bacde

175 

176 

177def test_wrong_uri(): 1bacde

178 """ 

179 Verify that a websocket connection to a non-existent endpoing returns in a shutdown 

180 """ 

181 client = TestClient(app) 1bacde

182 with pytest.raises(WebSocketDisconnect) as e: 1bacde

183 with client.websocket_connect("/no-router/"): 1bacde

184 pass # pragma: no cover 1a

185 assert e.value.code == status.WS_1000_NORMAL_CLOSURE 1bacde

186 

187 

188def websocket_middleware(middleware_func): 1bacde

189 """ 

190 Helper to create a Starlette pure websocket middleware 

191 """ 

192 

193 def middleware_constructor(app): 1bacde

194 @functools.wraps(app) 1bacde

195 async def wrapped_app(scope, receive, send): 1bacde

196 if scope["type"] != "websocket": 1bacde

197 return await app(scope, receive, send) # pragma: no cover 

198 

199 async def call_next(): 1bacde

200 return await app(scope, receive, send) 1bacde

201 

202 websocket = WebSocket(scope, receive=receive, send=send) 1bacde

203 return await middleware_func(websocket, call_next) 1bacde

204 

205 return wrapped_app 1bacde

206 

207 return middleware_constructor 1bacde

208 

209 

210def test_depend_validation(): 1bacde

211 """ 

212 Verify that a validation in a dependency invokes the correct exception handler 

213 """ 

214 caught = [] 1bacde

215 

216 @websocket_middleware 1bacde

217 async def catcher(websocket, call_next): 1bacde

218 try: 1bacde

219 return await call_next() 1bacde

220 except Exception as e: # pragma: no cover 

221 caught.append(e) 

222 raise 

223 

224 myapp = make_app(middleware=[Middleware(catcher)]) 1bacde

225 

226 client = TestClient(myapp) 1bacde

227 with pytest.raises(WebSocketDisconnect) as e: 1bacde

228 with client.websocket_connect("/depends-validate/"): 1bacde

229 pass # pragma: no cover 1a

230 # the validation error does produce a close message 

231 assert e.value.code == status.WS_1008_POLICY_VIOLATION 1bacde

232 # and no error is leaked 

233 assert caught == [] 1bacde

234 

235 

236def test_depend_err_middleware(): 1bacde

237 """ 

238 Verify that it is possible to write custom WebSocket middleware to catch errors 

239 """ 

240 

241 @websocket_middleware 1bacde

242 async def errorhandler(websocket: WebSocket, call_next): 1bacde

243 try: 1bacde

244 return await call_next() 1bacde

245 except Exception as e: 1bacde

246 await websocket.close(code=status.WS_1006_ABNORMAL_CLOSURE, reason=repr(e)) 1bacde

247 

248 myapp = make_app(middleware=[Middleware(errorhandler)]) 1bacde

249 client = TestClient(myapp) 1bacde

250 with pytest.raises(WebSocketDisconnect) as e: 1bacde

251 with client.websocket_connect("/depends-err/"): 1bacde

252 pass # pragma: no cover 1a

253 assert e.value.code == status.WS_1006_ABNORMAL_CLOSURE 1bacde

254 assert "NotImplementedError" in e.value.reason 1bacde

255 

256 

257def test_depend_err_handler(): 1bacde

258 """ 

259 Verify that it is possible to write custom WebSocket middleware to catch errors 

260 """ 

261 

262 async def custom_handler(websocket: WebSocket, exc: CustomError) -> None: 1bacde

263 await websocket.close(1002, "foo") 1bacde

264 

265 myapp = make_app(exception_handlers={CustomError: custom_handler}) 1bacde

266 client = TestClient(myapp) 1bacde

267 with pytest.raises(WebSocketDisconnect) as e: 1bacde

268 with client.websocket_connect("/custom_error/"): 1bacde

269 pass # pragma: no cover 1a

270 assert e.value.code == 1002 1bacde

271 assert "foo" in e.value.reason 1bacde