Skip to content
This repository has been archived by the owner on Sep 12, 2023. It is now read-only.

Commit

Permalink
fix: Fix for usage of mock repo.
Browse files Browse the repository at this point in the history
  • Loading branch information
peterschutt committed Nov 30, 2022
1 parent 62737ba commit dddf1e2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 31 deletions.
14 changes: 7 additions & 7 deletions src/starlite_saqlalchemy/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ class GenericMockRepository(AbstractRepository[ModelT], Generic[ModelT]):
Uses a `dict` for storage.
"""

_collections: MutableMapping[type[ModelT], MutableMapping[Hashable, ModelT]] = {}
collection: MutableMapping[Hashable, ModelT] = {}
model_type: type[ModelT]

def __init__(self, id_factory: Callable[[], Any] = uuid4, **_: Any) -> None:
super().__init__()
self._id_factory = id_factory
self.collection = self._collections[self.model_type]

@classmethod
def __class_getitem__(cls: type[MockRepoT], item: type[ModelT]) -> type[MockRepoT]:
Expand All @@ -41,8 +41,9 @@ def __class_getitem__(cls: type[MockRepoT], item: type[ModelT]) -> type[MockRepo
Args:
item: The type that the class has been parametrized with.
"""
cls._collections.setdefault(item, {})
return cls
return type( # pyright:ignore
f"{cls.__name__}[{item.__name__}]", (cls,), {"collection": {}, "model_type": item}
)

def _find_or_raise_not_found(self, id_: Any) -> ModelT:
return self.check_not_found(self.collection.get(id_))
Expand Down Expand Up @@ -161,11 +162,10 @@ def seed_collection(cls, instances: Iterable[ModelT]) -> None:
Args:
instances: the instances to be added to the collection.
"""
collection = cls._collections[cls.model_type]
for instance in instances:
collection[cls.get_id_attribute_value(instance)] = instance
cls.collection[cls.get_id_attribute_value(instance)] = instance

@classmethod
def clear_collection(cls) -> None:
"""Empty the collection for repository type."""
cls._collections[cls.model_type] = {}
cls.collection = {}
19 changes: 4 additions & 15 deletions tests/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,27 +47,16 @@ def _patch_worker() -> abc.Iterator:
monkeypatch.undo()


@pytest.fixture(autouse=True)
def _clear_mock_repo_collections() -> None:
"""Ensure all tests start with fresh collections."""
# pylint: disable=protected-access
GenericMockRepository._collections = {} # type:ignore[misc]


@pytest.fixture(name="author_repository_type")
def fx_author_repository_type(
authors: list[Author], monkeypatch: pytest.MonkeyPatch
) -> type[GenericMockRepository[Author]]:
"""Mock Author repository, pre-seeded with collection data."""

class AuthorRepository(GenericMockRepository[Author]):
"""Mock Author repo."""

model_type = Author

AuthorRepository.seed_collection(authors)
monkeypatch.setattr(AuthorService, "repository_type", AuthorRepository)
return AuthorRepository
repo = GenericMockRepository[Author]
repo.seed_collection(authors)
monkeypatch.setattr(AuthorService, "repository_type", repo)
return repo


@pytest.fixture(name="author_repository")
Expand Down
15 changes: 6 additions & 9 deletions tests/unit/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,23 @@ async def test_repo_raises_conflict_if_add_with_id(

def test_generic_mock_repository_parametrization() -> None:
"""Test that the mock repository handles multiple types."""
# pylint: disable=pointless-statement,protected-access
testing.GenericMockRepository[Author]
testing.GenericMockRepository[Book]
assert Author in testing.GenericMockRepository._collections # type:ignore[misc]
assert Book in testing.GenericMockRepository._collections # type:ignore[misc]
author_repo = testing.GenericMockRepository[Author]
book_repo = testing.GenericMockRepository[Book]
assert author_repo.model_type is Author # type:ignore[misc]
assert book_repo.model_type is Book # type:ignore[misc]


def test_generic_mock_repository_seed_collection(
author_repository_type: type[testing.GenericMockRepository[Author]],
) -> None:
"""Test seeding instances."""
author_repository_type.seed_collection([Author(id="abc")])
# pylint: disable=protected-access
assert "abc" in author_repository_type._collections[Author]
assert "abc" in author_repository_type.collection


def test_generic_mock_repository_clear_collection(
author_repository_type: type[testing.GenericMockRepository[Author]],
) -> None:
"""Test clearing collection for type."""
author_repository_type.clear_collection()
# pylint: disable=protected-access
assert not author_repository_type._collections[Author]
assert not author_repository_type.collection

0 comments on commit dddf1e2

Please sign in to comment.