|
| 1 | +import pytest |
| 2 | +from httpx import ConnectTimeout, MockTransport, Request, Response, codes |
| 3 | + |
| 4 | +from mpt_api_client.http.client import MPTClient |
| 5 | + |
| 6 | +API_TOKEN = "test-token" |
| 7 | +API_URL = "https://api.example.com" |
| 8 | + |
| 9 | + |
| 10 | +@pytest.fixture |
| 11 | +def mock_transport() -> MockTransport: |
| 12 | + def handler_request(request: Request): # noqa: WPS430 |
| 13 | + if request.url.path == "/": |
| 14 | + return Response(codes.OK, json={"message": "Hello, World!"}) |
| 15 | + if request.url.path == "/timeout": |
| 16 | + raise ConnectTimeout("Mock Timeout") |
| 17 | + return Response(codes.NOT_FOUND, json={"message": "Not Found"}) |
| 18 | + |
| 19 | + return MockTransport(handler=handler_request) |
| 20 | + |
| 21 | + |
| 22 | +@pytest.fixture |
| 23 | +def mock_api_client(mocker, mock_transport: MockTransport): |
| 24 | + transport_mock = mocker.patch("mpt_api_client.http.client.httpx.HTTPTransport") |
| 25 | + transport_mock.return_value = mock_transport |
| 26 | + return MPTClient(base_url=API_URL, api_token=API_TOKEN) |
| 27 | + |
| 28 | + |
| 29 | +def test_mpt_client_initialization(): |
| 30 | + client = MPTClient(base_url=API_URL, api_token=API_TOKEN) |
| 31 | + |
| 32 | + assert client.api_token == API_TOKEN |
| 33 | + assert client.base_url == API_URL |
| 34 | + |
| 35 | + |
| 36 | +def test_mpt_client_headers(): |
| 37 | + client = MPTClient(base_url=API_URL, api_token=API_TOKEN) |
| 38 | + |
| 39 | + assert client.headers["Authorization"] == "Bearer test-token" |
| 40 | + assert client.headers["User-Agent"] == "swo-marketplace-client/1.0" |
| 41 | + |
| 42 | + |
| 43 | +def test_mpt_client_timeout_and_retries(): |
| 44 | + client = MPTClient( |
| 45 | + base_url=API_URL, |
| 46 | + api_token=API_TOKEN, |
| 47 | + timeout=12, # noqa: WPS432 |
| 48 | + retries=2, # noqa: WPS432 |
| 49 | + ) |
| 50 | + |
| 51 | + assert client._timeout.connect == 12 # noqa: WPS432, SLF001 |
| 52 | + |
| 53 | + |
| 54 | +def test_mock(mock_api_client: MPTClient): |
| 55 | + success_response = mock_api_client.get("/") |
| 56 | + |
| 57 | + with pytest.raises(ConnectTimeout): |
| 58 | + mock_api_client.get("/timeout") |
| 59 | + |
| 60 | + not_found_response = mock_api_client.get("/not-found") |
| 61 | + |
| 62 | + assert success_response.status_code == codes.OK |
| 63 | + assert success_response.json() == {"message": "Hello, World!"} |
| 64 | + assert not_found_response.status_code == codes.NOT_FOUND |
0 commit comments