|
| 1 | +""" |
| 2 | +MIT License |
| 3 | +
|
| 4 | +Copyright (c) 2019-present Luc1412 |
| 5 | +
|
| 6 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +of this software and associated documentation files (the "Software"), to deal |
| 8 | +in the Software without restriction, including without limitation the rights |
| 9 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +copies of the Software, and to permit persons to whom the Software is |
| 11 | +furnished to do so, subject to the following conditions: |
| 12 | +
|
| 13 | +The above copyright notice and this permission notice shall be included in all |
| 14 | +copies or substantial portions of the Software. |
| 15 | +
|
| 16 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | +SOFTWARE. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +import inspect |
| 28 | +import logging |
| 29 | +from collections.abc import Callable, Coroutine |
| 30 | +from typing import TYPE_CHECKING, Any, Concatenate, Generic, TypeAlias, TypeVar |
| 31 | + |
| 32 | +import pytest |
| 33 | +import requests |
| 34 | +from typing_extensions import ParamSpec |
| 35 | + |
| 36 | +import fortnite_api |
| 37 | +from fortnite_api import ReconstructAble |
| 38 | + |
| 39 | +P = ParamSpec('P') |
| 40 | +T = TypeVar('T') |
| 41 | + |
| 42 | +if TYPE_CHECKING: |
| 43 | + Client: TypeAlias = fortnite_api.Client |
| 44 | + SyncClient = fortnite_api.SyncClient |
| 45 | + |
| 46 | + CoroFunc = Callable[P, Coroutine[Any, Any, T]] |
| 47 | + |
| 48 | +log = logging.getLogger(__name__) |
| 49 | + |
| 50 | + |
| 51 | +class HybridMethodProxy(Generic[P, T]): |
| 52 | + def __init__( |
| 53 | + self, |
| 54 | + hybrid_client: ClientHybrid, |
| 55 | + sync_client: SyncClient, |
| 56 | + async_method: CoroFunc[Concatenate[Client, P], T], |
| 57 | + sync_method: Callable[Concatenate[SyncClient, P], T], |
| 58 | + ) -> None: |
| 59 | + self.__hybrid_client = hybrid_client |
| 60 | + self.__sync_client = sync_client |
| 61 | + |
| 62 | + self.__async_method = async_method |
| 63 | + self.__sync_method = sync_method |
| 64 | + |
| 65 | + @property |
| 66 | + def __name__(self) -> str: |
| 67 | + return self.__async_method.__name__ |
| 68 | + |
| 69 | + def _validate_results(self, async_res: T, sync_res: T) -> None: |
| 70 | + assert type(async_res) is type(sync_res), f"Expected {type(async_res)}, got {type(sync_res)}" |
| 71 | + |
| 72 | + if isinstance(async_res, fortnite_api.Hashable): |
| 73 | + assert isinstance(sync_res, fortnite_api.Hashable) |
| 74 | + assert async_res == sync_res |
| 75 | + log.debug('Hashable comparison passed for method %s.', self.__async_method.__name__) |
| 76 | + |
| 77 | + if isinstance(async_res, fortnite_api.ReconstructAble): |
| 78 | + assert isinstance(sync_res, fortnite_api.ReconstructAble) |
| 79 | + |
| 80 | + sync_res_narrowed: ReconstructAble[Any, fortnite_api.SyncHTTPClient] = sync_res |
| 81 | + async_res_narrowed: ReconstructAble[Any, fortnite_api.HTTPClient] = async_res |
| 82 | + |
| 83 | + async_raw_data = sync_res_narrowed.to_dict() |
| 84 | + sync_raw_data = sync_res_narrowed.to_dict() |
| 85 | + assert async_raw_data == sync_raw_data |
| 86 | + log.debug('Raw data equality passed for method %s', self.__async_method.__name__) |
| 87 | + |
| 88 | + async_reconstructed = type(async_res_narrowed).from_dict(async_raw_data, client=self.__hybrid_client) |
| 89 | + sync_reconstructed = type(sync_res_narrowed).from_dict(sync_raw_data, client=self.__sync_client) |
| 90 | + |
| 91 | + assert isinstance(async_reconstructed, type(sync_reconstructed)) |
| 92 | + assert type(async_reconstructed) is type(async_res_narrowed) |
| 93 | + assert type(sync_reconstructed) is type(sync_res_narrowed) |
| 94 | + log.debug('Reconstructed data equality passed for method %s', self.__async_method.__name__) |
| 95 | + |
| 96 | + async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: |
| 97 | + # Call the sync method first |
| 98 | + sync_result = self.__sync_method(self.__sync_client, *args, **kwargs) |
| 99 | + |
| 100 | + # Call the async method |
| 101 | + async_result = await self.__async_method(self.__hybrid_client, *args, **kwargs) |
| 102 | + |
| 103 | + log.debug('Validating results for %s', self.__async_method.__name__) |
| 104 | + self._validate_results(async_result, sync_result) |
| 105 | + return async_result |
| 106 | + |
| 107 | + |
| 108 | +class ClientHybrid(fortnite_api.Client): |
| 109 | + """Denotes a "client-hybrid" that calls both a async and sync |
| 110 | + client when a method is called. |
| 111 | +
|
| 112 | + Pytest tests are not called in parallel, so although this is a |
| 113 | + blocking operation it will not affect the overall performance of |
| 114 | + the tests. |
| 115 | + """ |
| 116 | + |
| 117 | + def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 118 | + super().__init__(*args, **kwargs) |
| 119 | + |
| 120 | + kwargs.pop('session', None) |
| 121 | + session = requests.Session() |
| 122 | + self.__sync_client: fortnite_api.SyncClient = fortnite_api.SyncClient(*args, session=session, **kwargs) |
| 123 | + self.__inject_hybrid_methods() |
| 124 | + |
| 125 | + def __inject_hybrid_methods(self) -> None: |
| 126 | + # Walks through all the public coroutine methods in this class. If it finds one, |
| 127 | + # it will mark it as a hybrid proxy method with it and its sync counterpart. |
| 128 | + for key, value in fortnite_api.Client.__dict__.items(): |
| 129 | + if inspect.iscoroutinefunction(value): |
| 130 | + sync_value = getattr(fortnite_api.SyncClient, key, None) |
| 131 | + if sync_value is not None and inspect.isfunction(sync_value): |
| 132 | + setattr(self, key, HybridMethodProxy(self, self.__sync_client, value, sync_value)) |
| 133 | + |
| 134 | + async def __aexit__(self, *args: Any) -> None: |
| 135 | + # We need to ensure that the sync client is also closed |
| 136 | + self.__sync_client.__exit__(*args) |
| 137 | + return await super().__aexit__(*args) |
| 138 | + |
| 139 | + |
| 140 | +@pytest.mark.asyncio |
| 141 | +async def test_hybrid_client(): |
| 142 | + hybrid_client = ClientHybrid() |
| 143 | + |
| 144 | + # Walk through all coroutines in the normal client - ensure that |
| 145 | + # every coro on the normal is a proxy method on the hybrid client. |
| 146 | + for key, value in fortnite_api.Client.__dict__.items(): |
| 147 | + if inspect.iscoroutinefunction(value) and not key.startswith('_'): |
| 148 | + assert hasattr(hybrid_client, key) |
| 149 | + |
| 150 | + method = getattr(hybrid_client, key) |
| 151 | + assert isinstance(method, HybridMethodProxy) |
0 commit comments