|
| 1 | +import os |
| 2 | +import unittest |
| 3 | +from typing import Callable, Optional |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +# Skip the tests in this module if Python <= 3.6 (pytest_httpserver requires Python >= 3.7): |
| 8 | +try: |
| 9 | + from http.client import HTTPResponse |
| 10 | + |
| 11 | + from pytest_httpserver import HTTPServer |
| 12 | + from werkzeug.wrappers import Request, Response |
| 13 | + |
| 14 | + ErrorHandler = Optional[Callable[[Request], Response]] |
| 15 | +except ImportError: |
| 16 | + pytest.skip(allow_module_level=True) |
| 17 | + |
| 18 | + |
| 19 | +class HTTPServerTestCase(unittest.TestCase): |
| 20 | + HTTPResponse = HTTPResponse # pyright: ignore[reportUnboundVariable] |
| 21 | + httpserver = HTTPServer() # pyright: ignore[reportUnboundVariable] |
| 22 | + |
| 23 | + @classmethod |
| 24 | + def setUpClass(cls): |
| 25 | + cls.httpserver.start() |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def tearDownClass(cls): |
| 29 | + cls.httpserver.check_assertions() |
| 30 | + cls.httpserver.stop() |
| 31 | + |
| 32 | + @classmethod |
| 33 | + def serve_file(cls, root, file_path, error_handler=None, real_path=None): |
| 34 | + # type:(str, str, Optional[Callable[[Request], Response]], Optional[str]) -> None |
| 35 | + """Expect a GET request and handle it using the local pytest_httpserver.HTTPServer""" |
| 36 | + |
| 37 | + def handle_get(request): |
| 38 | + # type:(Request) -> Response |
| 39 | + """Handle a GET request for the local pytest_httpserver.HTTPServer fixture""" |
| 40 | + if error_handler: |
| 41 | + response = error_handler(request) |
| 42 | + if response: |
| 43 | + return response |
| 44 | + filepath = root + (real_path or file_path) |
| 45 | + assert os.path.exists(path=filepath) |
| 46 | + with open(file=filepath, mode="rb") as local_testdata_file: |
| 47 | + return Response(local_testdata_file.read()) |
| 48 | + |
| 49 | + cls.httpserver.expect_request(uri="/" + file_path).respond_with_handler(func=handle_get) |
0 commit comments