|
| 1 | +# Copyright 2021 - 2025 Universität Tübingen, DKFZ, EMBL, and Universität zu Köln |
| 2 | +# for the German Human Genome-Phenome Archive (GHGA) |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""A dummy DAO""" |
| 17 | + |
| 18 | +from collections.abc import AsyncIterator, Mapping |
| 19 | +from copy import deepcopy |
| 20 | +from typing import Any, TypeVar |
| 21 | +from unittest.mock import AsyncMock, Mock |
| 22 | + |
| 23 | +from hexkit.custom_types import ID |
| 24 | +from hexkit.protocols.dao import ( |
| 25 | + MultipleHitsFoundError, |
| 26 | + NoHitsFoundError, |
| 27 | + ResourceAlreadyExistsError, |
| 28 | + ResourceNotFoundError, |
| 29 | +) |
| 30 | +from pydantic import BaseModel |
| 31 | + |
| 32 | +from uos.core.models import ResearchDataUploadBox |
| 33 | + |
| 34 | +DTO = TypeVar("DTO", bound=BaseModel) |
| 35 | + |
| 36 | + |
| 37 | +class BaseInMemDao[DTO: BaseModel]: |
| 38 | + """Base class for dummy DAOs with proper typing and in-memory storage""" |
| 39 | + |
| 40 | + _id_field: str |
| 41 | + publish_pending = AsyncMock() |
| 42 | + republish = AsyncMock() |
| 43 | + with_transaction = Mock() |
| 44 | + |
| 45 | + def __init__(self) -> None: |
| 46 | + self.resources: list[DTO] = [] |
| 47 | + |
| 48 | + @property |
| 49 | + def latest(self) -> DTO: |
| 50 | + """Return the most recently inserted resource""" |
| 51 | + return deepcopy(self.resources[-1]) |
| 52 | + |
| 53 | + async def get_by_id(self, id_: ID) -> DTO: |
| 54 | + """Get the resource via ID.""" |
| 55 | + for resource in self.resources: |
| 56 | + if id_ == getattr(resource, self._id_field): |
| 57 | + return deepcopy(resource) |
| 58 | + raise ResourceNotFoundError(id_=id_) |
| 59 | + |
| 60 | + async def find_one(self, *, mapping: Mapping[str, Any]) -> DTO: |
| 61 | + """Find the resource that matches the specified mapping.""" |
| 62 | + hits = self.find_all(mapping=mapping) |
| 63 | + try: |
| 64 | + dto = await hits.__anext__() |
| 65 | + except StopAsyncIteration as error: |
| 66 | + raise NoHitsFoundError(mapping=mapping) from error |
| 67 | + |
| 68 | + try: |
| 69 | + _ = await hits.__anext__() |
| 70 | + except StopAsyncIteration: |
| 71 | + # This is expected: |
| 72 | + return dto |
| 73 | + |
| 74 | + raise MultipleHitsFoundError(mapping=mapping) |
| 75 | + |
| 76 | + async def find_all(self, *, mapping: Mapping[str, Any]) -> AsyncIterator[DTO]: |
| 77 | + """Find all resources that match the specified mapping.""" |
| 78 | + for resource in self.resources: |
| 79 | + if all([getattr(resource, k) == v for k, v in mapping.items()]): |
| 80 | + yield deepcopy(resource) |
| 81 | + |
| 82 | + async def insert(self, dto: DTO) -> None: |
| 83 | + """Insert a resource""" |
| 84 | + dto_id = getattr(dto, self._id_field) |
| 85 | + for resource in self.resources: |
| 86 | + if getattr(resource, self._id_field) == dto_id: |
| 87 | + raise ResourceAlreadyExistsError(id_=dto_id) |
| 88 | + self.resources.append(deepcopy(dto)) |
| 89 | + |
| 90 | + async def update(self, dto: DTO) -> None: |
| 91 | + """Update a resource""" |
| 92 | + for i, resource in enumerate(self.resources): |
| 93 | + if getattr(resource, self._id_field) == getattr(dto, self._id_field): |
| 94 | + self.resources[i] = deepcopy(dto) |
| 95 | + break |
| 96 | + else: |
| 97 | + raise ResourceNotFoundError(id_=getattr(dto, self._id_field)) |
| 98 | + |
| 99 | + async def delete(self, id_: ID) -> None: |
| 100 | + """Delete a resource by ID""" |
| 101 | + for i, resource in enumerate(self.resources): |
| 102 | + if getattr(resource, self._id_field) == id_: |
| 103 | + del self.resources[i] |
| 104 | + break |
| 105 | + else: |
| 106 | + raise ResourceNotFoundError(id_=id_) |
| 107 | + |
| 108 | + async def upsert(self, dto: DTO) -> None: |
| 109 | + """Upsert a resource""" |
| 110 | + for i, resource in enumerate(self.resources): |
| 111 | + if getattr(resource, self._id_field) == getattr(dto, self._id_field): |
| 112 | + self.resources[i] = deepcopy(dto) |
| 113 | + break |
| 114 | + else: |
| 115 | + self.resources.append(deepcopy(dto)) |
| 116 | + |
| 117 | + |
| 118 | +def get_dao[DTO: BaseModel]( |
| 119 | + *, dto_model: type[DTO], id_field: str |
| 120 | +) -> type[BaseInMemDao[DTO]]: |
| 121 | + """Produce a dummy DAO for the given DTO model and id field""" |
| 122 | + |
| 123 | + class DummyDao(BaseInMemDao[DTO]): |
| 124 | + """Dummy dao that stores data in memory""" |
| 125 | + |
| 126 | + _id_field: str = id_field |
| 127 | + |
| 128 | + return DummyDao |
| 129 | + |
| 130 | + |
| 131 | +InMemBoxDao = get_dao(dto_model=ResearchDataUploadBox, id_field="id") |
0 commit comments