Enhanced files

Category overview

animal_shelter/__init__.py

Download this file

"""CS 499 software design enhancement for the CS 340 animal shelter artifact."""
from .service import AnimalService
from .errors import ShelterError, ConfigurationError, ValidationError, RepositoryError, ResourceClosedError
from .models import CreateResult, ReadResult, UpdateResult, DeleteResult

__all__ = ['AnimalService', 'ShelterError', 'ConfigurationError', 'ValidationError',
           'RepositoryError', 'ResourceClosedError', 'CreateResult', 'ReadResult',
           'UpdateResult', 'DeleteResult']
animal_shelter/config.py

Download this file

"""Environment configuration is isolated from domain and database operations."""
import os
import re
from dataclasses import dataclass, field
from typing import Mapping
from .errors import ConfigurationError

@dataclass(frozen=True)
class MongoConfig:
    uri: str = field(repr=False)
    database: str = 'aac'
    collection: str = 'animals'
    timeout_ms: int = 5000

    def __post_init__(self) -> None:
        if not isinstance(self.uri, str) or not self.uri.startswith(('mongodb://', 'mongodb+srv://')):
            raise ConfigurationError('Set MONGODB_URI to a valid MongoDB connection URI.')
        for name in (self.database, self.collection):
            if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,63}', name):
                raise ConfigurationError('Database and collection names must use 1–64 safe characters.')
        if type(self.timeout_ms) is not int or not 100 <= self.timeout_ms <= 60000:
            raise ConfigurationError('Timeout must be an integer from 100 to 60000 milliseconds.')

    @classmethod
    def from_env(cls, env: Mapping[str, str] | None = None) -> 'MongoConfig':
        source = os.environ if env is None else env
        try:
            timeout = int(source.get('MONGODB_TIMEOUT_MS', '5000'))
        except (TypeError, ValueError):
            raise ConfigurationError('MONGODB_TIMEOUT_MS must be an integer.') from None
        return cls(source.get('MONGODB_URI', ''), source.get('MONGODB_DATABASE', 'aac'),
                   source.get('MONGODB_COLLECTION', 'animals'), timeout)
animal_shelter/errors.py

Download this file

"""Stable, application-facing errors; messages never include driver details."""

class ShelterError(Exception):
    """Base exception callers may handle at the application boundary."""

class ConfigurationError(ShelterError):
    """Missing or invalid connection configuration."""

class ValidationError(ShelterError):
    """Input violates the service contract."""

class RepositoryError(ShelterError):
    """A database operation failed; this is not an empty result."""

class ResourceClosedError(ShelterError):
    """An operation was attempted after the service or repository closed."""
animal_shelter/memory_repository.py

Download this file

"""Offline demo/test adapter. Not persistent and not a MongoDB emulator."""
from copy import deepcopy
from bson import ObjectId
from .errors import ResourceClosedError
from .models import Document, CreateResult, ReadResult, UpdateResult, DeleteResult

class MemoryAnimalRepository:
    def __init__(self) -> None:
        self._records: dict[ObjectId, Document] = {}
        self._closed = False

    def _ensure_open(self) -> None:
        if self._closed:
            raise ResourceClosedError('Memory repository is closed.')

    def create(self, data: Document) -> CreateResult:
        self._ensure_open()
        identity = ObjectId()
        self._records[identity] = {**deepcopy(data), '_id': identity}
        return CreateResult(str(identity))

    def read(self, filters: Document, limit: int) -> ReadResult:
        self._ensure_open()
        records = []
        for row in self._records.values():
            if all(row.get(key) == value for key, value in filters.items()):
                records.append(deepcopy(row))
                if len(records) > limit:
                    break
        return ReadResult(tuple(records[:limit]), len(records) > limit)

    def update(self, record_id: ObjectId, changes: Document) -> UpdateResult:
        self._ensure_open()
        record = self._records.get(record_id)
        if record is None:
            return UpdateResult(0, 0)
        modified = any(record.get(key) != value for key, value in changes.items())
        record.update(deepcopy(changes))
        return UpdateResult(1, int(modified))

    def delete(self, record_id: ObjectId) -> DeleteResult:
        self._ensure_open()
        return DeleteResult(int(self._records.pop(record_id, None) is not None))

    def close(self) -> None:
        self._closed = True
animal_shelter/models.py

Download this file

"""Explicit results preserve the difference between success, no match and failure."""
from dataclasses import dataclass
from typing import Any

Document = dict[str, Any]

@dataclass(frozen=True)
class CreateResult:
    inserted_id: str

@dataclass(frozen=True)
class ReadResult:
    records: tuple[Document, ...]
    truncated: bool = False

@dataclass(frozen=True)
class UpdateResult:
    matched_count: int
    modified_count: int

@dataclass(frozen=True)
class DeleteResult:
    deleted_count: int
animal_shelter/mongo_repository.py

Download this file

"""PyMongo adapter: driver errors stop here rather than becoming empty results."""
import logging
from typing import Any, Callable, TypeVar
from bson import ObjectId
from pymongo import MongoClient
from pymongo.errors import PyMongoError
from .config import MongoConfig
from .errors import ConfigurationError, RepositoryError, ResourceClosedError
from .models import Document, CreateResult, ReadResult, UpdateResult, DeleteResult

logger = logging.getLogger(__name__)
T = TypeVar('T')

class MongoAnimalRepository:
    """Internal adapter; application callers should use the validating service."""
    def __init__(self, client: Any, collection: Any, timeout_ms: int) -> None:
        self._client = client
        self._collection = collection
        self._timeout_ms = timeout_ms
        self._closed = False

    @classmethod
    def connect(cls, config: MongoConfig, *, client_factory: Callable[..., Any] = MongoClient) -> 'MongoAnimalRepository':
        client = None
        try:
            client = client_factory(config.uri, serverSelectionTimeoutMS=config.timeout_ms,
                connectTimeoutMS=config.timeout_ms, socketTimeoutMS=config.timeout_ms,
                timeoutMS=config.timeout_ms, w=1)
            client.admin.command('ping')
            collection = client[config.database][config.collection]
            return cls(client, collection, config.timeout_ms)
        except (PyMongoError, ValueError, TypeError):
            if client is not None:
                client.close()
            logger.error('shelter_connection_failed', extra={'operation': 'connect', 'status': 'failure'})
            raise ConfigurationError('MongoDB connection failed. Check configuration and availability.') from None

    def _run(self, operation: str, action: Callable[[], T]) -> T:
        if self._closed:
            raise ResourceClosedError('MongoDB repository is closed.')
        try:
            return action()
        except PyMongoError:
            # Deliberately omit driver error text, query values and exception traces.
            logger.error('shelter_operation_failed', extra={'operation': operation, 'status': 'failure'})
            raise RepositoryError(f'MongoDB {operation} failed.') from None

    def create(self, data: Document) -> CreateResult:
        def action() -> CreateResult:
            result = self._collection.insert_one(dict(data))
            if not result.acknowledged:
                raise RepositoryError('MongoDB create was not acknowledged.')
            return CreateResult(str(result.inserted_id))
        return self._run('create', action)

    def read(self, filters: Document, limit: int) -> ReadResult:
        def action() -> ReadResult:
            cursor = self._collection.find(dict(filters)).limit(limit + 1).max_time_ms(self._timeout_ms)
            try:
                records = list(cursor)
            finally:
                cursor.close()
            return ReadResult(tuple(records[:limit]), len(records) > limit)
        return self._run('read', action)

    def update(self, record_id: ObjectId, changes: Document) -> UpdateResult:
        def action() -> UpdateResult:
            result = self._collection.update_one({'_id': record_id}, {'$set': dict(changes)})
            if not result.acknowledged:
                raise RepositoryError('MongoDB update was not acknowledged.')
            return UpdateResult(result.matched_count, result.modified_count)
        return self._run('update', action)

    def delete(self, record_id: ObjectId) -> DeleteResult:
        def action() -> DeleteResult:
            result = self._collection.delete_one({'_id': record_id})
            if not result.acknowledged:
                raise RepositoryError('MongoDB delete was not acknowledged.')
            return DeleteResult(result.deleted_count)
        return self._run('delete', action)

    def close(self) -> None:
        if not self._closed:
            self._client.close()
            self._closed = True
animal_shelter/repository.py

Download this file

"""Repository contract; the service depends on this interface, not MongoClient."""
from typing import Protocol
from bson import ObjectId
from .models import Document, CreateResult, ReadResult, UpdateResult, DeleteResult

class AnimalRepository(Protocol):
    """Inputs are validated by AnimalService. Implementations own their resources."""
    def create(self, data: Document) -> CreateResult: ...
    def read(self, filters: Document, limit: int) -> ReadResult: ...
    def update(self, record_id: ObjectId, changes: Document) -> UpdateResult: ...
    def delete(self, record_id: ObjectId) -> DeleteResult: ...
    def close(self) -> None: ...
animal_shelter/service.py

Download this file

"""Application API with validation, typed results and explicit resource ownership."""
import logging
from types import TracebackType
from typing import Type
from . import validation
from .errors import ResourceClosedError
from .models import CreateResult, ReadResult, UpdateResult, DeleteResult
from .repository import AnimalRepository

logger = logging.getLogger(__name__)

class AnimalService:
    """Own the injected repository; use one service per repository lifecycle."""
    def __init__(self, repository: AnimalRepository) -> None:
        self._repository = repository
        self._closed = False

    def _ensure_open(self) -> None:
        if self._closed:
            raise ResourceClosedError('Animal service is closed.')

    def create(self, data: object) -> CreateResult:
        self._ensure_open()
        result = self._repository.create(validation.document(data, mode='create'))
        logger.info('shelter_operation', extra={'operation': 'create', 'status': 'success'})
        return result

    def read(self, filters: object, *, limit: int = 100) -> ReadResult:
        self._ensure_open()
        query = validation.document(filters, mode='filter')
        count = validation.result_limit(limit)
        result = self._repository.read(query, count)
        logger.info('shelter_operation', extra={'operation': 'read', 'status': 'success',
                    'record_count': len(result.records), 'truncated': result.truncated})
        return result

    def update(self, record_id: object, changes: object) -> UpdateResult:
        """Update only the unique MongoDB _id, never an arbitrary bulk filter."""
        self._ensure_open()
        identity = validation.object_id(record_id)
        values = validation.document(changes, mode='update')
        result = self._repository.update(identity, values)
        logger.info('shelter_operation', extra={'operation': 'update', 'status': 'success',
                    'matched_count': result.matched_count, 'modified_count': result.modified_count})
        return result

    def delete(self, record_id: object) -> DeleteResult:
        self._ensure_open()
        result = self._repository.delete(validation.object_id(record_id))
        logger.info('shelter_operation', extra={'operation': 'delete', 'status': 'success',
                    'deleted_count': result.deleted_count})
        return result

    def close(self) -> None:
        if not self._closed:
            self._repository.close()
            self._closed = True

    def __enter__(self) -> 'AnimalService':
        self._ensure_open()
        return self

    def __exit__(self, exc_type: Type[BaseException] | None, exc: BaseException | None,
                 traceback: TracebackType | None) -> None:
        self.close()
animal_shelter/validation.py

Download this file

"""A deliberately narrow, equality-only AAC service boundary.

Supported fields can be extended here with explicit types. Raw MongoDB operators,
arrays and nested documents are never accepted through the public service API.
"""
import math
from bson import ObjectId
from .errors import ValidationError
from .models import Document

TEXT_FIELDS = frozenset({'animal_id', 'animal_type', 'breed', 'name', 'color',
    'sex_upon_outcome', 'outcome_type', 'outcome_subtype', 'date_of_birth',
    'datetime', 'monthyear', 'age_upon_outcome'})
NUMBER_FIELDS = frozenset({'age_upon_outcome_in_weeks', 'location_lat', 'location_long'})
REQUIRED_FIELDS = frozenset({'animal_id', 'animal_type'})
MAX_TEXT_LENGTH = 256
MAX_RESULTS = 1000


def object_id(value: object) -> ObjectId:
    if isinstance(value, ObjectId):
        return value
    if isinstance(value, str) and ObjectId.is_valid(value):
        return ObjectId(value)
    raise ValidationError('Record id must be a valid 24-character MongoDB ObjectId.')


def document(value: object, *, mode: str) -> Document:
    """Return a new validated dictionary; never mutate caller-owned input."""
    if mode not in {'create', 'update', 'filter'}:
        raise ValueError('Unknown validation mode.')
    if not isinstance(value, dict) or (not value and mode != 'filter'):
        raise ValidationError('Expected a nonempty dictionary (empty read filters are allowed).')
    allowed = TEXT_FIELDS | NUMBER_FIELDS | ({'_id'} if mode == 'filter' else set())
    result: Document = {}
    for key, item in value.items():
        if not isinstance(key, str) or key not in allowed:
            raise ValidationError('An unsupported field or query operator was provided.')
        if key == '_id':
            result[key] = object_id(item)
        elif key in TEXT_FIELDS:
            if not isinstance(item, str) or len(item) > MAX_TEXT_LENGTH or '\x00' in item:
                raise ValidationError('Text fields must be strings of at most 256 characters without NUL.')
            if key in REQUIRED_FIELDS and not item.strip():
                raise ValidationError('Animal id and animal type cannot be blank.')
            result[key] = item
        else:
            # bool is a subclass of int, but not a valid measurement.
            if type(item) not in (int, float):
                raise ValidationError('Measurement fields must be finite numbers.')
            try:
                finite = math.isfinite(item)
            except OverflowError:
                finite = False
            if not finite:
                raise ValidationError('Measurement fields must be finite numbers.')
            low, high = (0, 10000) if key == 'age_upon_outcome_in_weeks' else ((-90, 90) if key == 'location_lat' else (-180, 180))
            if not low <= item <= high:
                raise ValidationError('Measurement is outside the supported range.')
            result[key] = item
    if mode == 'create' and not REQUIRED_FIELDS.issubset(result):
        raise ValidationError('Create requires animal_id and animal_type.')
    return result


def result_limit(value: object) -> int:
    if type(value) is not int or not 1 <= value <= MAX_RESULTS:
        raise ValidationError('Read limit must be an integer from 1 to 1000.')
    return value
demo.py

Download this file

"""Run a deterministic offline workflow with synthetic animal records."""
from animal_shelter import AnimalService, ValidationError
from animal_shelter.memory_repository import MemoryAnimalRepository


def main() -> None:
    with AnimalService(MemoryAnimalRepository()) as shelter:
        created = shelter.create({'animal_id': 'DEMO001', 'animal_type': 'Dog', 'name': 'Scout'})
        print('Created synthetic record:', bool(created.inserted_id))
        print('Read matching records:', len(shelter.read({'animal_type': 'Dog'}).records))
        print('Changed name:', shelter.update(created.inserted_id, {'name': 'Scout II'}))
        print('Repeated same update:', shelter.update(created.inserted_id, {'name': 'Scout II'}))
        try:
            shelter.read({'animal_type': {'$ne': None}})
        except ValidationError:
            print('Rejected nested query operator: True')
        print('Deleted record:', shelter.delete(created.inserted_id))
        print('Read after deletion:', len(shelter.read({}).records))
    print('Context manager closed the service.')

if __name__ == '__main__':
    main()
live_read.py

Download this file

"""Optional read-only smoke check against the user's configured MongoDB."""
from animal_shelter import AnimalService, ShelterError
from animal_shelter.config import MongoConfig
from animal_shelter.mongo_repository import MongoAnimalRepository


def main() -> int:
    try:
        with AnimalService(MongoAnimalRepository.connect(MongoConfig.from_env())) as shelter:
            result = shelter.read({}, limit=5)
            print(f'Connected. Returned {len(result.records)} records; truncated={result.truncated}.')
        return 0
    except ShelterError as error:
        print(f'Controlled error: {error}')
        return 1

if __name__ == '__main__':
    raise SystemExit(main())
requirements.txt

Download this file

pymongo==4.18.1
dnspython==2.8.0
tests/test_config.py

Download this file

import unittest
from animal_shelter.config import MongoConfig
from animal_shelter.errors import ConfigurationError

class ConfigurationTests(unittest.TestCase):
    def test_environment_loads_defaults_and_hides_uri_from_repr(self):
        config = MongoConfig.from_env({'MONGODB_URI': 'mongodb://user:SECRET@localhost/'})
        self.assertEqual(config.database, 'aac')
        self.assertEqual(config.timeout_ms, 5000)
        self.assertNotIn('SECRET', repr(config))

    def test_custom_names_and_timeout(self):
        config = MongoConfig.from_env({'MONGODB_URI': 'mongodb://localhost/',
             'MONGODB_DATABASE': 'aac_test', 'MONGODB_COLLECTION': 'animals_test', 'MONGODB_TIMEOUT_MS': '1000'})
        self.assertEqual((config.database, config.collection, config.timeout_ms), ('aac_test', 'animals_test', 1000))

    def test_missing_uri_wrong_scheme_and_invalid_timeout(self):
        for env in ({}, {'MONGODB_URI': 'https://example.com'},
                    {'MONGODB_URI': 'mongodb://localhost/', 'MONGODB_TIMEOUT_MS': 'bad'},
                    {'MONGODB_URI': 'mongodb://localhost/', 'MONGODB_TIMEOUT_MS': '0'}):
            with self.subTest(env=env), self.assertRaises(ConfigurationError):
                MongoConfig.from_env(env)

    def test_direct_configuration_is_validated(self):
        for kwargs in ({'database': 'bad.name'}, {'collection': '$bad'}, {'timeout_ms': True}, {'timeout_ms': 60001}):
            with self.subTest(kwargs=kwargs), self.assertRaises(ConfigurationError):
                MongoConfig('mongodb://localhost/', **kwargs)
tests/test_mongo_repository.py

Download this file

"""Adapter contract tests use real PyMongo result/error types with mocked I/O.

These tests do not claim to validate a live MongoDB server or credentials.
"""
import traceback
import unittest
from unittest.mock import MagicMock, Mock
from bson import ObjectId
from pymongo.errors import OperationFailure, ServerSelectionTimeoutError
from pymongo.results import InsertOneResult, UpdateResult as MongoUpdateResult, DeleteResult as MongoDeleteResult
from animal_shelter.config import MongoConfig
from animal_shelter.errors import ConfigurationError, RepositoryError, ResourceClosedError
from animal_shelter.models import UpdateResult, DeleteResult
from animal_shelter.mongo_repository import MongoAnimalRepository

class MongoAdapterTests(unittest.TestCase):
    def setUp(self):
        self.client = MagicMock()
        self.collection = MagicMock()
        self.repo = MongoAnimalRepository(self.client, self.collection, 1000)
        self.addCleanup(self.repo.close)
        self.identity = ObjectId()

    def test_create_copies_input_and_returns_inserted_id(self):
        data = {'animal_id': 'A', 'animal_type': 'Dog'}
        def insert(copy):
            copy['_id'] = self.identity
            return InsertOneResult(self.identity, True)
        self.collection.insert_one.side_effect = insert
        self.assertEqual(self.repo.create(data).inserted_id, str(self.identity))
        self.assertNotIn('_id', data)

    def test_update_uses_id_set_and_preserves_matched_vs_modified(self):
        self.collection.update_one.return_value = MongoUpdateResult({'n': 1, 'nModified': 0}, True)
        self.assertEqual(self.repo.update(self.identity, {'name': 'Same'}), UpdateResult(1, 0))
        self.collection.update_one.assert_called_once_with({'_id': self.identity}, {'$set': {'name': 'Same'}})
        self.collection.update_many.assert_not_called()

    def test_delete_uses_unique_id_and_one_operation(self):
        self.collection.delete_one.return_value = MongoDeleteResult({'n': 1}, True)
        self.assertEqual(self.repo.delete(self.identity), DeleteResult(1))
        self.collection.delete_one.assert_called_once_with({'_id': self.identity})
        self.collection.delete_many.assert_not_called()

    def _cursor(self, documents):
        cursor = MagicMock()
        self.collection.find.return_value = cursor
        cursor.limit.return_value = cursor
        cursor.max_time_ms.return_value = cursor
        cursor.__iter__.return_value = iter(documents)
        return cursor

    def test_read_caps_results_and_closes_cursor(self):
        cursor = self._cursor([{'name': 'a'}, {'name': 'b'}, {'name': 'c'}])
        result = self.repo.read({}, 2)
        self.assertEqual(len(result.records), 2)
        self.assertTrue(result.truncated)
        cursor.limit.assert_called_once_with(3)
        cursor.max_time_ms.assert_called_once_with(1000)
        cursor.close.assert_called_once()

    def test_cursor_failure_closes_cursor_and_raises_safe_error(self):
        cursor = self._cursor([])
        cursor.__iter__.side_effect = OperationFailure('SECRET_DRIVER_TEXT')
        with self.assertLogs('animal_shelter.mongo_repository', level='ERROR') as logs:
            with self.assertRaises(RepositoryError) as raised:
                self.repo.read({}, 2)
        cursor.close.assert_called_once()
        self.assertNotIn('SECRET_DRIVER_TEXT', str(raised.exception))
        self.assertNotIn('SECRET_DRIVER_TEXT', str(logs.records[0].__dict__))

    def test_all_driver_operation_failures_are_translated(self):
        calls = [('create', 'insert_one', ({'animal_id': 'A'},)),
                 ('read', 'find', ({}, 2)), ('update', 'update_one', (self.identity, {'name': 'X'})),
                 ('delete', 'delete_one', (self.identity,))]
        for operation, method, args in calls:
            with self.subTest(operation=operation):
                getattr(self.collection, method).side_effect = OperationFailure('PASSWORD_SENTINEL')
                with self.assertLogs('animal_shelter.mongo_repository', level='ERROR') as logs:
                    try:
                        getattr(self.repo, operation)(*args)
                    except RepositoryError as error:
                        formatted = ''.join(traceback.format_exception(error))
                        self.assertNotIn('PASSWORD_SENTINEL', formatted)
                    else:
                        self.fail('Expected RepositoryError')
                self.assertEqual(logs.records[0].operation, operation)
                self.assertNotIn('PASSWORD_SENTINEL', str(logs.records[0].__dict__))

    def test_unacknowledged_writes_are_not_reported_as_success(self):
        self.collection.insert_one.return_value = InsertOneResult(self.identity, False)
        self.collection.update_one.return_value = MongoUpdateResult({}, False)
        self.collection.delete_one.return_value = MongoDeleteResult({}, False)
        for action in (lambda: self.repo.create({}), lambda: self.repo.update(self.identity, {}), lambda: self.repo.delete(self.identity)):
            with self.assertRaises(RepositoryError):
                action()

    def test_connect_pings_and_sets_finite_timeouts_and_acknowledgement(self):
        factory = Mock(return_value=self.client)
        config = MongoConfig('mongodb://localhost/', timeout_ms=1000)
        repo = MongoAnimalRepository.connect(config, client_factory=factory)
        self.addCleanup(repo.close)
        self.client.admin.command.assert_called_once_with('ping')
        self.assertEqual(factory.call_args.kwargs, {'serverSelectionTimeoutMS': 1000,
            'connectTimeoutMS': 1000, 'socketTimeoutMS': 1000, 'timeoutMS': 1000, 'w': 1})

    def test_connect_failure_closes_partial_client_and_hides_secrets(self):
        self.client.admin.command.side_effect = ServerSelectionTimeoutError('URI_PASSWORD_SENTINEL')
        with self.assertLogs('animal_shelter.mongo_repository', level='ERROR') as logs:
            with self.assertRaises(ConfigurationError) as raised:
                MongoAnimalRepository.connect(MongoConfig('mongodb://localhost/'), client_factory=Mock(return_value=self.client))
        self.client.close.assert_called_once()
        self.assertNotIn('URI_PASSWORD_SENTINEL', str(raised.exception))
        self.assertNotIn('URI_PASSWORD_SENTINEL', str(logs.records[0].__dict__))

    def test_malformed_uri_factory_error_becomes_configuration_error(self):
        with self.assertLogs('animal_shelter.mongo_repository', level='ERROR'):
            with self.assertRaises(ConfigurationError):
                MongoAnimalRepository.connect(MongoConfig('mongodb://'), client_factory=Mock(side_effect=ValueError('bad URI')))

    def test_close_is_idempotent_and_blocks_later_operations(self):
        self.repo.close()
        self.repo.close()
        self.client.close.assert_called_once()
        with self.assertRaises(ResourceClosedError):
            self.repo.read({}, 1)
tests/test_service.py

Download this file

"""Behavior tests exercise real validation with an injected offline repository."""
import unittest
from unittest.mock import Mock
from bson import ObjectId
from animal_shelter import AnimalService, ValidationError, ResourceClosedError, RepositoryError
from animal_shelter.memory_repository import MemoryAnimalRepository
from animal_shelter.models import UpdateResult, DeleteResult

class ServiceTests(unittest.TestCase):
    def setUp(self):
        self.service = AnimalService(MemoryAnimalRepository())
        self.addCleanup(self.service.close)
        self.data = {'animal_id': 'TEST1', 'animal_type': 'Dog', 'name': 'Scout'}

    def test_full_crud_workflow_preserves_other_records(self):
        one = self.service.create(self.data)
        two = self.service.create({**self.data, 'animal_id': 'TEST2'})
        self.assertEqual(self.service.update(one.inserted_id, {'name': 'New'}), UpdateResult(1, 1))
        self.assertEqual(self.service.read({'_id': one.inserted_id}).records[0]['name'], 'New')
        self.assertEqual(self.service.read({'_id': two.inserted_id}).records[0]['name'], 'Scout')
        self.assertEqual(self.service.delete(one.inserted_id), DeleteResult(1))
        self.assertEqual(len(self.service.read({}).records), 1)

    def test_unchanged_update_is_distinct_from_missing_record(self):
        created = self.service.create(self.data)
        self.assertEqual(self.service.update(created.inserted_id, {'name': 'Scout'}), UpdateResult(1, 0))
        self.assertEqual(self.service.update(ObjectId(), {'name': 'Scout'}), UpdateResult(0, 0))

    def test_empty_result_is_success(self):
        result = self.service.read({'animal_type': 'Cat'})
        self.assertEqual(result.records, ())
        self.assertFalse(result.truncated)
        self.assertEqual(self.service.delete(ObjectId()), DeleteResult(0))

    def test_limit_reports_truncation_without_hiding_it(self):
        for _ in range(3):
            self.service.create(self.data)
        result = self.service.read({}, limit=2)
        self.assertEqual(len(result.records), 2)
        self.assertTrue(result.truncated)
        self.assertFalse(self.service.read({}, limit=3).truncated)

    def test_create_and_read_do_not_expose_mutable_stored_data(self):
        created = self.service.create(self.data)
        self.assertNotIn('_id', self.data)
        self.data['name'] = 'Changed outside'
        records = self.service.read({}).records
        records[0]['name'] = 'Changed result'
        self.assertEqual(self.service.read({'_id': created.inserted_id}).records[0]['name'], 'Scout')

    def test_reject_missing_required_fields(self):
        for data in ({}, None, [], {'animal_id': 'A'}, {'animal_type': 'Dog'}, {'animal_id': ' ', 'animal_type': 'Dog'}):
            with self.subTest(data=data), self.assertRaises(ValidationError):
                self.service.create(data)

    def test_operator_and_unknown_field_inputs_never_reach_repository(self):
        repo = Mock()
        service = AnimalService(repo)
        for data in ({'$where': 'code'}, {'name': {'$ne': None}}, {'name.x': 'bad'}, {'unknown': 'bad'}, {1: 'bad'}, {'name': ['bad']}):
            with self.subTest(data=data), self.assertRaises(ValidationError):
                service.read(data)
        repo.read.assert_not_called()

    def test_invalid_measurements_are_rejected(self):
        for value in (True, '2', float('nan'), float('inf'), -1, 10001, 10**1000):
            with self.subTest(value=str(value)[:30]), self.assertRaises(ValidationError):
                self.service.create({**self.data, 'age_upon_outcome_in_weeks': value})
        for key,value in [('location_lat', 91), ('location_long', -181)]:
            with self.subTest(key=key), self.assertRaises(ValidationError):
                self.service.create({**self.data, key: value})

    def test_measurement_boundaries_and_optional_empty_name(self):
        created = self.service.create({**self.data, 'name': '', 'age_upon_outcome_in_weeks': 0,
                                       'location_lat': -90, 'location_long': 180})
        self.assertTrue(created.inserted_id)

    def test_reject_oversized_or_nul_text(self):
        for name in ('x' * 257, 'a\x00b'):
            with self.subTest(name=name), self.assertRaises(ValidationError):
                self.service.create({**self.data, 'name': name})

    def test_invalid_limits_never_reach_repository(self):
        for value in (0, -1, True, 1001, '10', 1.5):
            with self.subTest(value=value), self.assertRaises(ValidationError):
                self.service.read({}, limit=value)

    def test_mutations_reject_broad_filters_and_invalid_ids(self):
        for identity in ({}, {'animal_type': 'Dog'}, 'invalid', None):
            with self.subTest(identity=identity), self.assertRaises(ValidationError):
                self.service.update(identity, {'name': 'bad'})
            with self.subTest(identity=identity), self.assertRaises(ValidationError):
                self.service.delete(identity)

    def test_update_rejects_empty_changes_operators_and_id_mutation(self):
        identity = ObjectId()
        for changes in ({}, {'_id': ObjectId()}, {'$set': {'name': 'bad'}}, {'animal_type': ''}):
            with self.subTest(changes=changes), self.assertRaises(ValidationError):
                self.service.update(identity, changes)

    def test_context_manager_closes_repository_after_exception(self):
        repo = Mock()
        service = AnimalService(repo)
        with self.assertRaisesRegex(RuntimeError, 'body failed'):
            with service:
                raise RuntimeError('body failed')
        service.close()
        repo.close.assert_called_once()
        with self.assertRaises(ResourceClosedError):
            service.read({})

    def test_repository_failure_is_not_an_empty_result(self):
        repo = Mock()
        repo.read.side_effect = RepositoryError('Database unavailable')
        with self.assertRaises(RepositoryError):
            AnimalService(repo).read({})

    def test_logs_contain_metadata_but_not_record_values(self):
        with self.assertLogs('animal_shelter.service', level='INFO') as captured:
            self.service.create({**self.data, 'name': 'PRIVATE_SENTINEL'})
        record = captured.records[0]
        self.assertEqual(record.operation, 'create')
        self.assertEqual(record.status, 'success')
        self.assertNotIn('PRIVATE_SENTINEL', str(record.__dict__))