Skip to content

Commit 39f9b75

Browse files
tests/httpserver_testcase.py: Add common base class for HTTP tests
Add a common base class for HTTP tests using pytest_httpserver: - tests/test_httpaccessor.py (self-contained HTTP test for xcp.accessor) - tests/test_httprepository.py (self-contained HTTP test for xcp.repository) Signed-off-by: Bernhard Kaindl <bernhard.kaindl@cloud.com>
1 parent c734982 commit 39f9b75

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

stubs/werkzeug/wrappers.pyi

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
from _typeshed import Incomplete
1+
from _typeshed import Incomplete # pylint: disable=import-error,no-name-in-module
2+
Request = Incomplete
23
Response = Incomplete

tests/httpserver_testcase.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)