|
5 | 5 |
|
6 | 6 | from dataretrieval.waterdata.utils import ( |
7 | 7 | _arrange_cols, |
| 8 | + _error_body, |
8 | 9 | _format_api_dates, |
9 | 10 | _get_args, |
10 | 11 | _handle_stats_nesting, |
@@ -221,3 +222,55 @@ def test_format_api_dates_open_ended_range_with_none(): |
221 | 222 | """A None / NaN endpoint becomes '..' in the output range.""" |
222 | 223 | assert _format_api_dates(["2024-01-01", None], date=True) == "2024-01-01/.." |
223 | 224 | assert _format_api_dates([None, "2024-01-01"], date=True) == "../2024-01-01" |
| 225 | + |
| 226 | + |
| 227 | +def _make_response(status, body, reason=None, content_type="text/html"): |
| 228 | + resp = requests.Response() |
| 229 | + resp.status_code = status |
| 230 | + resp.reason = reason |
| 231 | + resp._content = body.encode("utf-8") |
| 232 | + resp.headers["Content-Type"] = content_type |
| 233 | + return resp |
| 234 | + |
| 235 | + |
| 236 | +def test_error_body_handles_non_json_html_response(): |
| 237 | + """A non-JSON 502 HTML body must be summarized, not raise JSONDecodeError.""" |
| 238 | + html = ( |
| 239 | + "<html>\r\n<head><title>502 Bad Gateway</title></head>" |
| 240 | + "<body><center><h1>502 Bad Gateway</h1></center><hr>" |
| 241 | + "<center>openresty</center></body></html>" |
| 242 | + ) |
| 243 | + resp = _make_response(502, html, reason="Bad Gateway") |
| 244 | + msg = _error_body(resp) |
| 245 | + assert "502" in msg |
| 246 | + assert "Bad Gateway" in msg |
| 247 | + |
| 248 | + |
| 249 | +def test_error_body_handles_empty_response_body(): |
| 250 | + """An empty error body returns a status/reason message without crashing.""" |
| 251 | + resp = _make_response(500, "", reason="Internal Server Error") |
| 252 | + msg = _error_body(resp) |
| 253 | + assert msg == "500: Internal Server Error." |
| 254 | + |
| 255 | + |
| 256 | +def test_error_body_truncates_long_non_json_body(): |
| 257 | + """Non-JSON bodies are truncated to 200 chars to keep the message readable.""" |
| 258 | + body = ("x" * 200) + "Y" + ("z" * 299) |
| 259 | + resp = _make_response(502, body, reason="Bad Gateway") |
| 260 | + msg = _error_body(resp) |
| 261 | + assert "x" * 200 in msg |
| 262 | + assert (("x" * 200) + "Y") not in msg |
| 263 | + |
| 264 | + |
| 265 | +def test_error_body_still_parses_well_formed_json(): |
| 266 | + """JSON error bodies continue to render code/description fields.""" |
| 267 | + resp = _make_response( |
| 268 | + 400, |
| 269 | + '{"code": "BadRequest", "description": "missing parameter"}', |
| 270 | + reason="Bad Request", |
| 271 | + content_type="application/json", |
| 272 | + ) |
| 273 | + msg = _error_body(resp) |
| 274 | + assert "400" in msg |
| 275 | + assert "BadRequest" in msg |
| 276 | + assert "missing parameter" in msg |
0 commit comments