Skip to content

Commit

Permalink
refactor tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zxdavb committed Nov 9, 2024
1 parent 6ca06f6 commit 92c94b4
Show file tree
Hide file tree
Showing 13 changed files with 186 additions and 462 deletions.
1 change: 1 addition & 0 deletions requirements_dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
pytest >= 8.3.3
pytest-asyncio >= 0.24.0
# pytest-cov >= 5.0.0
pytest-freezer >= 0.4.8
pytest-sugar >= 1.0.0
pytest-xdist >= 3.6.1
syrupy >= 4.7.2
Expand Down
36 changes: 31 additions & 5 deletions tests/tests_rf/helpers.py → tests/tests_rf/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,46 @@

import asyncio
from http import HTTPMethod, HTTPStatus
from pathlib import Path
from typing import Any, Final

import aiohttp
import voluptuous as vol

import evohomeasync as evo1
import evohomeasync2 as evo2
from evohomeasync2.auth import Auth
from evohomeasync2.const import URL_BASE as URL_BASE_2
from evohomeasync2.auth import URL_BASE as URL_BASE_2, Auth

from .conftest import _DBG_DISABLE_STRICT_ASSERTS
from .const import _DBG_DISABLE_STRICT_ASSERTS

# version 1 helpers ###################################################################


class SessionManager(evo1.Auth):
"""An evohomeasync session manager."""

def __init__(
self,
client_id: str,
secret: str,
websession: aiohttp.ClientSession,
/,
token_cache: Path | None = None,
**kwargs: Any,
) -> None:
"""Initialise the session manager."""
super().__init__(client_id, secret, websession, **kwargs)

self._token_cache: Final = token_cache

async def save_session_id(self) -> None:
"""Save the (serialized) session id to a cache."""

async def load_session_id(self) -> None:
"""Save the (serialized) session id from a cache."""



async def should_work_v1(
evo: evo1.EvohomeClient,
method: HTTPMethod,
Expand All @@ -32,7 +58,7 @@ async def should_work_v1(
response: aiohttp.ClientResponse

# unlike _make_request(), make_request() incl. raise_for_status()
response = await evo.auth._make_request(method, url, data=json)
response = await evo.auth.request(method, url, data=json)
response.raise_for_status()

# TODO: perform this transform in the broker
Expand Down Expand Up @@ -65,7 +91,7 @@ async def should_fail_v1(

try:
# unlike _make_request(), make_request() incl. raise_for_status()
response = await evo.auth._make_request(method, url, data=json)
response = await evo.auth.request(method, url, data=json)
response.raise_for_status()

except aiohttp.ClientResponseError as err:
Expand Down
43 changes: 29 additions & 14 deletions tests/tests_rf/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,19 @@
import evohomeasync2 as evo2
from evohomeasync2.client import TokenManager

from .common import SessionManager # incl. support for cache file
from .const import _DBG_USE_REAL_AIOHTTP
from .faked_server import FakedServer

#
# normally, we want debug flags to be False
_DBG_USE_REAL_AIOHTTP = False
_DBG_DISABLE_STRICT_ASSERTS = False # of response content-type, schema

if TYPE_CHECKING:
import aiohttp

# used to construct the default token cache
TEST_USERNAME: Final = "[email protected]"
TEST_PASSWORD: Final = "P@ssw0rd!!" # noqa: S105
TEST_USERNAME: Final = "[email protected]" # SECRET "[email protected]"
TEST_PASSWORD: Final = "ziQajn732m5JYQ!" # "P@ssw0rd!!" # noqa: S105


_FNC = TypeVar("_F", bound=Callable[..., Any])
_FNC = TypeVar("_FNC", bound=Callable[..., Any])


# Global flag to indicate if AuthenticationFailedError has been encountered
Expand Down Expand Up @@ -66,8 +63,8 @@ async def wrapper(*args: Any, **kwargs: Any) -> Any:
return wrapper # type: ignore[return-value]


@pytest.fixture(autouse=True)
def patches_for_tests(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.fixture(autouse=False)
def zpatches_for_tests(monkeypatch: pytest.MonkeyPatch) -> None:
"""Patch the evohomeasync and evohomeasync2 modules."""

if _DBG_USE_REAL_AIOHTTP:
Expand Down Expand Up @@ -144,6 +141,24 @@ def token_cache(
return token_cache


@pytest.fixture # @pytest_asyncio.fixture(scope="session", loop_scope="session")
async def session_manager(
client_session: aiohttp.ClientSession,
credentials: tuple[str, str],
token_cache: Path,
) -> AsyncGenerator[SessionManager, None]:
"""Yield a token manager for the v1 API."""

manager = SessionManager(*credentials, client_session, token_cache=token_cache)

# await manager.load_session_id() # restoresession_id from cache

try:
yield manager
finally:
await manager.save_session_id() # save auth tokens to cache


@pytest.fixture # @pytest_asyncio.fixture(scope="session", loop_scope="session")
async def token_manager(
client_session: aiohttp.ClientSession,
Expand All @@ -152,14 +167,14 @@ async def token_manager(
) -> AsyncGenerator[TokenManager, None]:
"""Yield a token manager for the v2 API."""

token_manager = TokenManager(*credentials, client_session, token_cache=token_cache)
manager = TokenManager(*credentials, client_session, token_cache=token_cache)

await token_manager.load_access_token() # restore auth tokens from cache
# await manager.load_access_token() # restore auth tokens from cache

try:
yield token_manager
yield manager
finally:
await token_manager.save_access_token() # save auth tokens to cache
await manager.save_access_token() # save auth tokens to cache


@pytest.fixture
Expand Down
10 changes: 10 additions & 0 deletions tests/tests_rf/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python3
"""evohome-async - tests"""

from __future__ import annotations

#
# normally, we want debug flags to be False
_DBG_USE_REAL_AIOHTTP = True
_DBG_DISABLE_STRICT_ASSERTS = False # of response content-type, schema

191 changes: 0 additions & 191 deletions tests/tests_rf/test_token_mgr.py

This file was deleted.

3 changes: 2 additions & 1 deletion tests/tests_rf/test_v1_apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

import evohomeasync as evo1

from .conftest import _DBG_USE_REAL_AIOHTTP, skipif_auth_failed
from .conftest import skipif_auth_failed
from .const import _DBG_USE_REAL_AIOHTTP


async def _test_client_apis(evo: evo1.EvohomeClient) -> None:
Expand Down
Loading

0 comments on commit 92c94b4

Please sign in to comment.