Coverage for fastapi_restly/testing/_client.py: 95%

104 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-09 21:47 +0000

1from __future__ import annotations 

2 

3import json 

4from typing import TYPE_CHECKING, Any, Literal 

5 

6try: 

7 from fastapi.testclient import TestClient 

8except RuntimeError as exc: # pragma: no cover -- exercised via subprocess 

9 # Starlette >=1.x raises RuntimeError (not ModuleNotFoundError) at import 

10 # when neither httpx2 nor httpx is installed. Normalize it to a missing 

11 # module so the importing namespaces surface the [testing] extras hint 

12 # instead of Starlette's bare "pip install httpx2" message. 

13 if "httpx" not in str(exc): 

14 raise 

15 raise ModuleNotFoundError(name="httpx2") from exc 

16 

17if TYPE_CHECKING: 

18 # httpx2 is a drop-in rename of httpx 0.28.1 with identical stubs, so we 

19 # type-check against httpx and let runtime pick whichever is installed. 

20 import httpx 

21else: 

22 # Match Starlette's TestClient, which prefers httpx2 and only falls back to 

23 # httpx (with a deprecation warning) when httpx2 is absent. Aligning our 

24 # reference keeps httpx.Response/httpx.URL the same classes the parent 

25 # TestClient yields. 

26 try: 

27 import httpx2 as httpx 

28 except ModuleNotFoundError: 

29 import httpx 

30 

31# httpx accepts either a string or a `httpx.URL` for request URLs. The base 

32# class' `URLTypes` alias is private, so we replicate the public union here. 

33URLTypes = httpx.URL | str 

34 

35# What a request method checks: "2xx" for any success status, an int for that 

36# exact status, or None for no check. 

37ExpectedStatus = int | Literal["2xx"] | None 

38 

39 

40class _StatusAssertions: 

41 def assert_status( 

42 self, response: httpx.Response, expected_code: ExpectedStatus = "2xx" 

43 ) -> None: 

44 """Check the status code of a response. 

45 

46 ``"2xx"``, the default, accepts any success status. An int accepts only 

47 that status. ``None`` accepts every status. 

48 """ 

49 __tracebackhide__ = True 

50 

51 status_code = response.status_code 

52 

53 if expected_code is None or status_code == expected_code: 

54 return 

55 if expected_code == "2xx" and 200 <= status_code < 300: 

56 return 

57 

58 # Raise AssertionError with detailed error message 

59 try: 

60 response_content = response.json() 

61 except (ValueError, TypeError, json.JSONDecodeError): 

62 response_content = response.content.decode(errors="ignore") 

63 

64 content_str_raw = str(response_content) 

65 if len(content_str_raw) > 1000: 65 ↛ 66line 65 didn't jump to line 66 because the condition on line 65 was never true

66 content_str_raw = content_str_raw[:1000] + "...(truncated)" 

67 content_str = f"Response JSON: {content_str_raw}" 

68 

69 # Safe method/URL extraction 

70 try: 

71 method = response.request.method.upper() 

72 url = str(response.request.url) 

73 request_info = f"{method} {url}" 

74 except Exception: 

75 request_info = "(request info unavailable)" 

76 

77 raise AssertionError( 

78 f"Expected {request_info} to return {expected_code}, got {status_code}\n" 

79 f"{content_str}" 

80 ) 

81 

82 

83class RestlyTestClient(_StatusAssertions, TestClient): 

84 """Synchronous test client with Restly's response status assertions.""" 

85 

86 def __init__( 

87 self, app: Any, *args: Any, _transport_app: Any | None = None, **kwargs: Any 

88 ) -> None: 

89 """Build a client while optionally exposing a different public app. 

90 

91 Managed database isolation wraps the ASGI lifespan internally, but 

92 callers have always used ``client.app`` as the original ``FastAPI`` 

93 instance (including to register a view after constructing the client). 

94 ``_transport_app`` lets the fixture keep that contract while Starlette's 

95 transport and lifespan run the internal wrapper. 

96 """ 

97 self._restly_public_app = app 

98 self._restly_transport_app = app if _transport_app is None else _transport_app 

99 super().__init__(self._restly_transport_app, *args, **kwargs) 

100 self.app = self._restly_public_app 

101 

102 def __enter__(self) -> RestlyTestClient: 

103 # Starlette's lifespan coroutine reads ``self.app`` when __enter__ starts 

104 # it. Temporarily expose the transport wrapper, then restore the public 

105 # FastAPI app after startup has completed. The request transport already 

106 # captured the wrapper in TestClient.__init__. 

107 self.app = self._restly_transport_app 

108 try: 

109 super().__enter__() 

110 finally: 

111 self.app = self._restly_public_app 

112 return self 

113 

114 def get( 

115 self, 

116 url: URLTypes, 

117 *, 

118 assert_status_code: ExpectedStatus = "2xx", 

119 **kwargs: Any, 

120 ) -> httpx.Response: 

121 """Make a GET request and check its status. 

122 

123 By default the status must be a success (2xx). Pass an int to require 

124 that exact status, or ``None`` to skip the check. 

125 """ 

126 __tracebackhide__ = True 

127 response = super().get(url, **kwargs) 

128 self.assert_status(response, assert_status_code) 

129 return response 

130 

131 def post( 

132 self, 

133 url: URLTypes, 

134 *, 

135 assert_status_code: ExpectedStatus = "2xx", 

136 **kwargs: Any, 

137 ) -> httpx.Response: 

138 """Make a POST request and check its status. 

139 

140 By default the status must be a success (2xx). Pass an int to require 

141 that exact status, or ``None`` to skip the check. 

142 """ 

143 __tracebackhide__ = True 

144 response = super().post(url, **kwargs) 

145 self.assert_status(response, assert_status_code) 

146 return response 

147 

148 def put( 

149 self, 

150 url: URLTypes, 

151 *, 

152 assert_status_code: ExpectedStatus = "2xx", 

153 **kwargs: Any, 

154 ) -> httpx.Response: 

155 """Make a PUT request and check its status. 

156 

157 By default the status must be a success (2xx). Pass an int to require 

158 that exact status, or ``None`` to skip the check. 

159 """ 

160 __tracebackhide__ = True 

161 response = super().put(url, **kwargs) 

162 self.assert_status(response, assert_status_code) 

163 return response 

164 

165 def patch( 

166 self, 

167 url: URLTypes, 

168 *, 

169 assert_status_code: ExpectedStatus = "2xx", 

170 **kwargs: Any, 

171 ) -> httpx.Response: 

172 """Make a PATCH request and check its status. 

173 

174 By default the status must be a success (2xx). Pass an int to require 

175 that exact status, or ``None`` to skip the check. 

176 """ 

177 __tracebackhide__ = True 

178 response = super().patch(url, **kwargs) 

179 self.assert_status(response, assert_status_code) 

180 return response 

181 

182 def delete( 

183 self, 

184 url: URLTypes, 

185 *, 

186 assert_status_code: ExpectedStatus = "2xx", 

187 **kwargs: Any, 

188 ) -> httpx.Response: 

189 """Make a DELETE request and check its status. 

190 

191 By default the status must be a success (2xx). Pass an int to require 

192 that exact status, or ``None`` to skip the check. 

193 """ 

194 __tracebackhide__ = True 

195 response = super().delete(url, **kwargs) 

196 self.assert_status(response, assert_status_code) 

197 return response 

198 

199 

200class AsyncRestlyTestClient(_StatusAssertions, httpx.AsyncClient): 

201 """Async test client with the same response assertions as the sync client.""" 

202 

203 def __init__( 

204 self, app: Any, *args: Any, _transport_app: Any | None = None, **kwargs: Any 

205 ) -> None: 

206 self.app = app 

207 transport_app = app if _transport_app is None else _transport_app 

208 kwargs.setdefault("transport", httpx.ASGITransport(app=transport_app)) 

209 kwargs.setdefault("base_url", "http://testserver") 

210 kwargs.setdefault("follow_redirects", True) 

211 super().__init__(*args, **kwargs) 

212 

213 async def get( 

214 self, 

215 url: URLTypes, 

216 *, 

217 assert_status_code: ExpectedStatus = "2xx", 

218 **kwargs: Any, 

219 ) -> httpx.Response: 

220 """Make a GET request and check its status. 

221 

222 By default the status must be a success (2xx). Pass an int to require 

223 that exact status, or ``None`` to skip the check. 

224 """ 

225 __tracebackhide__ = True 

226 response = await super().get(url, **kwargs) 

227 self.assert_status(response, assert_status_code) 

228 return response 

229 

230 async def post( 

231 self, 

232 url: URLTypes, 

233 *, 

234 assert_status_code: ExpectedStatus = "2xx", 

235 **kwargs: Any, 

236 ) -> httpx.Response: 

237 """Make a POST request and check its status. 

238 

239 By default the status must be a success (2xx). Pass an int to require 

240 that exact status, or ``None`` to skip the check. 

241 """ 

242 __tracebackhide__ = True 

243 response = await super().post(url, **kwargs) 

244 self.assert_status(response, assert_status_code) 

245 return response 

246 

247 async def put( 

248 self, 

249 url: URLTypes, 

250 *, 

251 assert_status_code: ExpectedStatus = "2xx", 

252 **kwargs: Any, 

253 ) -> httpx.Response: 

254 """Make a PUT request and check its status. 

255 

256 By default the status must be a success (2xx). Pass an int to require 

257 that exact status, or ``None`` to skip the check. 

258 """ 

259 __tracebackhide__ = True 

260 response = await super().put(url, **kwargs) 

261 self.assert_status(response, assert_status_code) 

262 return response 

263 

264 async def patch( 

265 self, 

266 url: URLTypes, 

267 *, 

268 assert_status_code: ExpectedStatus = "2xx", 

269 **kwargs: Any, 

270 ) -> httpx.Response: 

271 """Make a PATCH request and check its status. 

272 

273 By default the status must be a success (2xx). Pass an int to require 

274 that exact status, or ``None`` to skip the check. 

275 """ 

276 __tracebackhide__ = True 

277 response = await super().patch(url, **kwargs) 

278 self.assert_status(response, assert_status_code) 

279 return response 

280 

281 async def delete( 

282 self, 

283 url: URLTypes, 

284 *, 

285 assert_status_code: ExpectedStatus = "2xx", 

286 **kwargs: Any, 

287 ) -> httpx.Response: 

288 """Make a DELETE request and check its status. 

289 

290 By default the status must be a success (2xx). Pass an int to require 

291 that exact status, or ``None`` to skip the check. 

292 """ 

293 __tracebackhide__ = True 

294 response = await super().delete(url, **kwargs) 

295 self.assert_status(response, assert_status_code) 

296 return response