import asyncio from datetime import datetime from typing import TYPE_CHECKING, Generator, Type import pytest from freezegun import freeze_time from getstream_connector import AsyncStreamClient, SyncStreamClient, config from tests import constants, utils if TYPE_CHECKING: from unittest.mock import Mock from getstream_connector.client.base import BaseExtendedClient from getstream_connector.feed.base import BaseExtendedFeed @pytest.fixture def stream_client(request) -> Generator["BaseExtendedClient", None, None]: client_kwargs = constants.DEFAULT_CLIENT_KWARGS.copy() param = getattr(request, "param", None) if param: client_kwargs.update(request.param) if asyncio.iscoroutinefunction(request.function): client_cls = AsyncStreamClient else: client_cls = SyncStreamClient client = client_cls(**client_kwargs) yield client @pytest.fixture def stream_feed(request, stream_client) -> Generator["BaseExtendedFeed", None, None]: feed_kwargs = constants.DEFAULT_FEED_KWARGS.copy() param = getattr(request, "param", None) if param: feed_kwargs.update(request.param) feed = stream_client.feed(**feed_kwargs) yield feed @pytest.fixture(autouse=True) def config_mock(mocker) -> Generator[None, None, None]: mocker.patch.object(config, "TRACE_CONTEXT_KEY", constants.TRACE_CONTEXT_KEY) mocker.patch.object(config, "CORRELATION_ID_KEY", constants.CORRELATION_ID_KEY) mocker.patch.object(config, "RATELIMIT_LIMIT_HEADER", constants.RATELIMIT_LIMIT_HEADER) mocker.patch.object(config, "RATELIMIT_REMAINING_HEADER", constants.RATELIMIT_REMAINING_HEADER) mocker.patch.object(config, "RATELIMIT_RESET_HEADER", constants.RATELIMIT_RESET_HEADER) mocker.patch.object(config, "SERVICE_NAME", constants.SERVICE_NAME) yield @pytest.fixture(scope="session") def frozen_time() -> Generator[int, None, None]: with freeze_time(datetime.utcfromtimestamp(constants.TIMESTAMP)): yield constants.TIMESTAMP @pytest.fixture def sleep_mock(request, mocker) -> Generator["Mock", None, None]: if asyncio.iscoroutinefunction(request.function): target = "asyncio.sleep" else: target = "time.sleep" yield mocker.patch(target) @pytest.fixture def request_mock(request) -> Generator[utils.RequestManager, None, None]: # For some unknown reason mypy run by 'pre-commit' complains about abstract type of # 'AsyncRequestManager' and 'SyncRequestManager' # However mypy run by 'make' or directly from cli doesn't. # I've tried to clean cache, checked versions and arguments and those looks ok. # Moreover, code looks logit and works like it suppose to. # So just ignore this error for now. manager_cls: Type[utils.RequestManager] if asyncio.iscoroutinefunction(request.function): manager_cls = utils.AsyncRequestManager # type: ignore[type-abstract] else: manager_cls = utils.SyncRequestManager # type: ignore[type-abstract] with manager_cls() as mock: if hasattr(request, "param"): for request_ in request.param: mock.add(**request_) yield mock