Coverage for tests/test_ws_router.py: 100%

157 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-01-13 13:38 +0000

1import functools 1abcde

2 

3import pytest 1abcde

4from fastapi import ( 1abcde

5 APIRouter, 

6 Depends, 

7 FastAPI, 

8 Header, 

9 WebSocket, 

10 WebSocketDisconnect, 

11 status, 

12) 

13from fastapi.middleware import Middleware 1abcde

14from fastapi.testclient import TestClient 1abcde

15 

16router = APIRouter() 1abcde

17prefix_router = APIRouter() 1abcde

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

19app = FastAPI() 1abcde

20 

21 

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

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

24 await websocket.accept() 1zABCD

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

26 await websocket.close() 1zABCD

27 

28 

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

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

31 await websocket.accept() 1EFGHI

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

33 await websocket.close() 1EFGHI

34 

35 

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

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

38 await websocket.accept() 1JKLMN

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

40 await websocket.close() 1JKLMN

41 

42 

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

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

45 await websocket.accept() 1OPQRS

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

47 await websocket.close() 1OPQRS

48 

49 

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

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

52 await websocket.accept() 1uvwxy

53 await websocket.send_text(pathparam) 1uvwxy

54 await websocket.send_text(queryparam) 1uvwxy

55 await websocket.close() 1uvwxy

56 

57 

58async def ws_dependency(): 1abcde

59 return "Socket Dependency" 1TUVWX

60 

61 

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

63async def router_ws_decorator_depends( 1abcde

64 websocket: WebSocket, data=Depends(ws_dependency) 

65): 

66 await websocket.accept() 1TYUZV0W1X2

67 await websocket.send_text(data) 1TYUZV0W1X2

68 await websocket.close() 1TYUZV0W1X2

69 

70 

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

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

73 await websocket.accept() 134567

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

75 await websocket.close() 134567

76 

77 

78async def ws_dependency_err(): 1abcde

79 raise NotImplementedError() 1gfhij

80 

81 

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

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

84 pass # pragma: no cover 

85 

86 

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

88 pass # pragma: no cover 

89 

90 

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

92async def router_ws_depends_validate( 1abcde

93 websocket: WebSocket, data=Depends(ws_dependency_validate) 

94): 

95 pass # pragma: no cover 

96 

97 

98class CustomError(Exception): 1abcde

99 pass 1abcde

100 

101 

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

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

104 raise CustomError() 1qprst

105 

106 

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

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

109 app.include_router(router) 1aqglbpfkcrhmdsinetjo

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

111 app.include_router(native_prefix_route) 1aqglbpfkcrhmdsinetjo

112 return app 1aqglbpfkcrhmdsinetjo

113 

114 

115app = make_app(app) 1abcde

116 

117 

118def test_app(): 1abcde

119 client = TestClient(app) 1zABCD

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

121 data = websocket.receive_text() 1zABCD

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

123 

124 

125def test_router(): 1abcde

126 client = TestClient(app) 1EFGHI

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

128 data = websocket.receive_text() 1EFGHI

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

130 

131 

132def test_prefix_router(): 1abcde

133 client = TestClient(app) 1JKLMN

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

135 data = websocket.receive_text() 1JKLMN

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

137 

138 

139def test_native_prefix_router(): 1abcde

140 client = TestClient(app) 134567

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

142 data = websocket.receive_text() 134567

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

144 

145 

146def test_router2(): 1abcde

147 client = TestClient(app) 1OPQRS

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

149 data = websocket.receive_text() 1OPQRS

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

151 

152 

153def test_router_ws_depends(): 1abcde

154 client = TestClient(app) 1TUVWX

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

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

157 

158 

159def test_router_ws_depends_with_override(): 1abcde

160 client = TestClient(app) 1YZ012

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

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

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

164 

165 

166def test_router_with_params(): 1abcde

167 client = TestClient(app) 1uvwxy

168 with client.websocket_connect( 1uvwxy

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

170 ) as websocket: 

171 data = websocket.receive_text() 1uvwxy

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

173 data = websocket.receive_text() 1uvwxy

174 assert data == "a_query_param" 1uvwxy

175 

176 

177def test_wrong_uri(): 1abcde

178 """ 

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

180 """ 

181 client = TestClient(app) 198!#$

182 with pytest.raises(WebSocketDisconnect) as e: 198!#$

183 with client.websocket_connect("/no-router/"): 198!#$

184 pass # pragma: no cover 18

185 assert e.value.code == status.WS_1000_NORMAL_CLOSURE 198!#$

186 

187 

188def websocket_middleware(middleware_func): 1abcde

189 """ 

190 Helper to create a Starlette pure websocket middleware 

191 """ 

192 

193 def middleware_constructor(app): 1glfkhminjo

194 @functools.wraps(app) 1glfkhminjo

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

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

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

198 

199 async def call_next(): 1glfkhminjo

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

201 

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

203 return await middleware_func(websocket, call_next) 1glfkhminjo

204 

205 return wrapped_app 1glfkhminjo

206 

207 return middleware_constructor 1glfkhminjo

208 

209 

210def test_depend_validation(): 1abcde

211 """ 

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

213 """ 

214 caught = [] 1lkmno

215 

216 @websocket_middleware 1lkmno

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

218 try: 1lkmno

219 return await call_next() 1lkmno

220 except Exception as e: # pragma: no cover 

221 caught.append(e) 

222 raise 

223 

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

225 

226 client = TestClient(myapp) 1lkmno

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

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

229 pass # pragma: no cover 1k

230 # the validation error does produce a close message 

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

232 # and no error is leaked 

233 assert caught == [] 1lkmno

234 

235 

236def test_depend_err_middleware(): 1abcde

237 """ 

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

239 """ 

240 

241 @websocket_middleware 1gfhij

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

243 try: 1gfhij

244 return await call_next() 1gfhij

245 except Exception as e: 1gfhij

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

247 

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

249 client = TestClient(myapp) 1gfhij

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

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

252 pass # pragma: no cover 1f

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

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

255 

256 

257def test_depend_err_handler(): 1abcde

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: 1qprst

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

264 

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

266 client = TestClient(myapp) 1qprst

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

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

269 pass # pragma: no cover 1p

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

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