Bakalarska_praca/tests/fixtures/mock_injector.py
oleh 959a391334
Some checks failed
publish docs / publish-docs (push) Has been cancelled
release-please / release-please (push) Has been cancelled
tests / setup (push) Has been cancelled
tests / ${{ matrix.quality-command }} (black) (push) Has been cancelled
tests / ${{ matrix.quality-command }} (mypy) (push) Has been cancelled
tests / ${{ matrix.quality-command }} (ruff) (push) Has been cancelled
tests / test (push) Has been cancelled
tests / all_checks_passed (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
add self code
2024-09-27 18:52:16 +02:00

43 lines
1.3 KiB
Python

from collections.abc import Callable
from typing import Any
from unittest.mock import MagicMock
import pytest
from injector import Provider, ScopeDecorator, singleton
from private_gpt.di import create_application_injector
from private_gpt.settings.settings import Settings, unsafe_settings
from private_gpt.settings.settings_loader import merge_settings
from private_gpt.utils.typing import T
class MockInjector:
def __init__(self) -> None:
self.test_injector = create_application_injector()
def bind_mock(
self,
interface: type[T],
mock: (T | (Callable[..., T] | Provider[T])) | None = None,
*,
scope: ScopeDecorator = singleton,
) -> T:
if mock is None:
mock = MagicMock()
self.test_injector.binder.bind(interface, to=mock, scope=scope)
return mock # type: ignore
def bind_settings(self, settings: dict[str, Any]) -> Settings:
merged = merge_settings([unsafe_settings, settings])
new_settings = Settings(**merged)
self.test_injector.binder.bind(Settings, new_settings)
return new_settings
def get(self, interface: type[T]) -> T:
return self.test_injector.get(interface)
@pytest.fixture()
def injector() -> MockInjector:
return MockInjector()