|
1 | 1 | import itertools |
2 | 2 | import logging |
3 | 3 | import re |
| 4 | +import threading |
4 | 5 | import time |
5 | 6 | from datetime import timedelta |
| 7 | +from http.server import BaseHTTPRequestHandler, HTTPServer |
6 | 8 | from unittest.mock import Mock, patch |
| 9 | +from urllib.error import HTTPError |
7 | 10 |
|
8 | 11 | import pytest |
9 | 12 |
|
@@ -361,6 +364,44 @@ def test_from_url(self, url, expected_port, expected_path, expected_tls): |
361 | 364 | assert strategy._path == expected_path |
362 | 365 | assert strategy._tls is expected_tls |
363 | 366 |
|
| 367 | + @pytest.mark.parametrize( |
| 368 | + "status_code,expected", |
| 369 | + [(503, False), (200, True)], |
| 370 | + ids=["unexpected_status", "expected_status"], |
| 371 | + ) |
| 372 | + def test_handle_http_error_always_closes_error(self, status_code, expected): |
| 373 | + # Regression test for #1115: HTTPError wraps the response fp and must be closed. |
| 374 | + error = Mock(spec=HTTPError) |
| 375 | + error.code = status_code |
| 376 | + strategy = HttpWaitStrategy(8080, "/health").for_status_code(200) |
| 377 | + assert strategy._handle_http_error(error) is expected |
| 378 | + error.close.assert_called_once_with() |
| 379 | + |
| 380 | + def test_try_http_request_unexpected_status(self): |
| 381 | + # End-to-end check for #1115: 503 against an expectation of 200 returns False. |
| 382 | + class _FailHandler(BaseHTTPRequestHandler): |
| 383 | + def do_GET(self): |
| 384 | + body = b"error" |
| 385 | + self.send_response(503) |
| 386 | + self.send_header("Content-Length", str(len(body))) |
| 387 | + self.end_headers() |
| 388 | + self.wfile.write(body) |
| 389 | + |
| 390 | + def log_message(self, *args): |
| 391 | + pass |
| 392 | + |
| 393 | + server = HTTPServer(("127.0.0.1", 0), _FailHandler) |
| 394 | + thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 395 | + thread.start() |
| 396 | + try: |
| 397 | + port = server.server_address[1] |
| 398 | + url = f"http://127.0.0.1:{port}/health" |
| 399 | + assert HttpWaitStrategy(port, "/health").for_status_code(200)._try_http_request(url, {}, None) is False |
| 400 | + assert HttpWaitStrategy(port, "/health").for_status_code(503)._try_http_request(url, {}, None) is True |
| 401 | + finally: |
| 402 | + server.shutdown() |
| 403 | + thread.join(timeout=5) |
| 404 | + |
364 | 405 |
|
365 | 406 | class TestHealthcheckWaitStrategy: |
366 | 407 | """Test the HealthcheckWaitStrategy class.""" |
|
0 commit comments