Debian Codegraph @

tests/conftest.py

raw
1 # Copyright 2023 Simone Chemelli and contributors
2 # SPDX-License-Identifier: Apache-2.0
3
4 """Shared test fixtures for aiocomelit."""
5
6 from __future__ import annotations
7
8 from http import HTTPStatus
9 from pathlib import Path
10 from typing import TYPE_CHECKING, Any, cast
11 from unittest.mock import AsyncMock
12
13 import orjson
14 import pytest
15 from aiohttp import ClientSession
16 from aioresponses import aioresponses
17
18 if TYPE_CHECKING:
19 from collections.abc import AsyncGenerator, Awaitable, Callable
20 from typing import Any
21
22 JsonScalar = str | int | float | bool | None
23 JsonValue = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]
24
25
26 def setup_api[ApiType](
27 api_factory: Callable[[str, int, str, ClientSession], ApiType],
28 host: str,
29 port: int,
30 pin: str,
31 session: ClientSession,
32 ) -> ApiType:
33 """Build a production API instance backed by a real session."""
34 return api_factory(host, port, pin, session)
35
36
37 def set_private_attr(api: object, name: str, value: object) -> None:
38 """Set private API attribute for controlled test setup."""
39 object.__setattr__(api, name, value)
40
41
42 def get_private_attr(api: object, name: str) -> object:
43 """Get private API attribute for controlled test assertions."""
44 return object.__getattribute__(api, name)
45
46
47 def set_private_mapping_item(
48 api: object,
49 name: str,
50 key: object,
51 value: object,
52 ) -> None:
53 """Set one item inside a private mapping attribute."""
54 mapping = cast("dict[object, object]", object.__getattribute__(api, name))
55 mapping[key] = value
56
57
58 def call_private_async[ReturnType](
59 api: object,
60 name: str,
61 ) -> Callable[..., Awaitable[ReturnType]]:
62 """Get a private async method with a typed callable signature."""
63 return cast(
64 "Callable[..., Awaitable[ReturnType]]",
65 object.__getattribute__(api, name),
66 )
67
68
69 def make_get_page_result_mock(
70 responses: dict[str, dict[str, object]],
71 default: dict[str, object] | None = None,
72 ) -> Callable[..., Awaitable[tuple[int, dict[str, object]]]]:
73 """Build a fake _get_page_result coroutine routing by page and query type."""
74
75 async def fake_get(
76 page: str = "",
77 query: dict[str, object] | None = None,
78 ) -> tuple[int, dict[str, object]]:
79 type_param = str((query or {}).get("type", ""))
80 lookup = f"{page}?type={type_param}" if type_param else page
81 for key, value in responses.items():
82 if lookup == key:
83 return HTTPStatus.OK, value
84 if default is not None:
85 return HTTPStatus.OK, default
86 raise AssertionError(lookup)
87
88 return fake_get
89
90
91 @pytest.fixture
92 async def mock_session() -> AsyncGenerator[ClientSession]:
93 """Return a real ClientSession for testing."""
94 session = ClientSession()
95 yield session
96 await session.close()
97
98
99 @pytest.fixture
100 def aiohttp_mock() -> aioresponses:
101 """Return aioresponses mock for HTTP calls."""
102 return aioresponses()
103
104
105 @pytest.fixture
106 def mock_get_session() -> Callable[[int, dict[str, Any] | None], AsyncMock]:
107 """Build a mocked session object for GET responses."""
108
109 def _build(status: int, json_data: dict[str, Any] | None = None) -> AsyncMock:
110 response = AsyncMock(status=status)
111 if json_data is not None:
112 response.json = AsyncMock(return_value=json_data)
113 return AsyncMock(get=AsyncMock(return_value=response))
114
115 return _build
116
117
118 @pytest.fixture
119 def fixture_loader() -> Callable[[str], dict[str, JsonValue]]:
120 """Load JSON fixtures from tests/fixtures."""
121
122 def _load(name: str) -> dict[str, JsonValue]:
123 fixture_path = Path(__file__).parent / "fixtures" / f"{name}.json"
124 return cast("dict[str, JsonValue]", orjson.loads(fixture_path.read_bytes()))
125
126 return _load