Skip to content

Commit

Permalink
Merge 03b917d into 1c12018
Browse files Browse the repository at this point in the history
  • Loading branch information
lyz-code committed Feb 9, 2022
2 parents 1c12018 + 03b917d commit f63f09c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/repository_orm/adapters/data/cache.py
@@ -1,30 +1,42 @@
"""Define the cache of the data repositories."""

from typing import Dict, List, Type, TypeVar
from typing import Any, Dict, List, Type, TypeVar

from ...model import Entity, EntityID
from ...model import Entity as EntityModel
from ...model import EntityID

Entity = TypeVar("Entity", bound=EntityModel)
CacheEntry = Dict[EntityID, Entity]
EntityOrEntities = TypeVar("EntityOrEntities", List[Entity], Entity)
EntityOrEntities = TypeVar("EntityOrEntities", List[EntityModel], EntityModel)


class Cache:
"""Define the cache of a repository."""
"""Define the cache of a repository.
The entries are saved in the `cache` attribute under a dictionary similar to:
{
Model_1: {
Entity_1_ID: Entity_1,
Entity_2_ID: Entity_2,
},
}
"""

def __init__(self) -> None:
"""Initialize the class."""
self.cache: Dict[Type[Entity], CacheEntry] = {}
self.cache: Dict[Type[EntityModel], CacheEntry[Any]] = {}

def add(self, entity_or_entities: EntityOrEntities) -> None:
"""Add an entity to the cache."""
if isinstance(entity_or_entities, Entity):
if isinstance(entity_or_entities, EntityModel):
entities = [entity_or_entities]
else:
entities = entity_or_entities

for entity in entities:
self.cache.setdefault(type(entity), {})
self.cache[type(entity)].setdefault(entity.id_, entity)
self.cache[type(entity)].setdefault(entity.id_, entity.copy())

def get(self, entity: Entity) -> Entity:
"""Return the cached value of an entity."""
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/test_cache.py
@@ -0,0 +1,22 @@
"""Test the implementation of the data repository cache."""

from tests.cases.model import Entity

from repository_orm.adapters.data.cache import Cache


def test_cache_is_immutable_on_external_changes() -> None:
"""
Given: An entry in the cache
When: an external function changes the entity
Then: the cached version is unchanged
"""
entity = Entity(name="Original name")
cache = Cache()
cache.add(entity)
entity.name = "Modified name"

result = cache.get(entity)

assert result.name == "Original name"
assert not cache.entity_has_not_changed(entity)

0 comments on commit f63f09c

Please sign in to comment.