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/database_repository.py

Download this file

"""Trusted MongoDB adapter with bounded queries, aggregation and index evaluation."""
from dataclasses import dataclass
from .mongo_repository import MongoAnimalRepository

INDEX_NAME = 'rescue_filter_v1'
INDEX_KEYS = [('animal_type', 1), ('breed', 1), ('sex_upon_outcome', 1),
              ('age_upon_outcome_in_weeks', 1), ('_id', 1)]

@dataclass(frozen=True)
class SearchResult:
    records: tuple
    page: int
    page_size: int
    has_next: bool

class DatabaseRepository(MongoAnimalRepository):
    def ensure_indexes(self):
        """Administrative setup only; idempotent creation does not drop existing indexes."""
        return self._run('ensure_indexes', lambda: self._collection.create_index(
            INDEX_KEYS, name=INDEX_NAME))

    def list_indexes(self):
        def action():
            cursor = self._collection.list_indexes()
            try:
                return list(cursor)
            finally:
                cursor.close()
        return self._run('list_indexes', action)

    def search(self, spec):
        def action():
            cursor = self._collection.find(spec.query, spec.projection)
            try:
                cursor.sort(list(spec.sort)).skip(spec.offset).limit(spec.page_size + 1).max_time_ms(self._timeout_ms)
                records = list(cursor)
                return SearchResult(tuple(records[:spec.page_size]), spec.page,
                                    spec.page_size, len(records) > spec.page_size)
            finally:
                cursor.close()
        return self._run('search', action)

    def rescue_summary(self, pipeline):
        def action():
            cursor = self._collection.aggregate(pipeline, maxTimeMS=self._timeout_ms, allowDiskUse=False)
            try:
                return tuple(cursor)
            finally:
                cursor.close()
        return self._run('rescue_summary', action)

    def explain(self, spec, *, hint=None):
        """Diagnostic API, accepts only a natural scan or this package's index hint."""
        if hint not in (None, 'natural', INDEX_NAME):
            raise ValueError('Unsupported diagnostic hint.')
        command = {'find': self._collection.name, 'filter': spec.query,
                   'sort': dict(spec.sort), 'skip': spec.offset,
                   'limit': spec.page_size + 1}
        if spec.projection is not None:
            command['projection'] = spec.projection
        if hint is not None:
            command['hint'] = {'$natural': 1} if hint == 'natural' else hint
        return self._run('explain', lambda: self._collection.database.command(
            'explain', command, verbosity='executionStats', maxTimeMS=self._timeout_ms))
animal_shelter/database_service.py

Download this file

"""Validated database enhancement API, retaining the Milestone Two CRUD API."""
from .service import AnimalService
from . import search

class DatabaseService(AnimalService):
    def search(self, filters=None, **options):
        self._ensure_open()
        spec = search.specification({} if filters is None else filters, **options)
        return self._repository.search(spec)

    def rescue_summary(self, filters=None, **options):
        self._ensure_open()
        pipeline = search.summary_pipeline({} if filters is None else filters, **options)
        return self._repository.rescue_summary(pipeline)
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/search.py

Download this file

"""Public search policy. MongoDB syntax is built here, never supplied by callers."""
from dataclasses import dataclass
from math import isfinite
from . import validation
from .errors import ValidationError

FIELDS = validation.TEXT_FIELDS | validation.NUMBER_FIELDS | {'_id'}
MAX_PAGE_SIZE = 100
MAX_OFFSET = 100000
# Explicit project presets; these are candidate filters, not suitability guarantees.
RESCUES = {
    'water': (('Labrador Retriever Mix', 'Chesapeake Bay Retriever', 'Newfoundland'), 26, 156),
    'mountain': (('German Shepherd', 'Alaskan Malamute', 'Old English Sheepdog',
                  'Siberian Husky', 'Rottweiler'), 26, 156),
    'disaster': (('Doberman Pinscher', 'German Shepherd', 'Golden Retriever',
                  'Bloodhound', 'Rottweiler'), 20, 300),
}

def rescue_query(category):
    if not isinstance(category, str) or category not in RESCUES:
        raise ValidationError('Rescue category must be water, mountain, or disaster.')
    breeds, low, high = RESCUES[category]
    return {'animal_type': 'Dog', 'breed': {'$in': list(breeds)},
            'sex_upon_outcome': 'Intact Male',
            'age_upon_outcome_in_weeks': {'$gte': low, '$lte': high}}

def match(filters, category=None, min_age=None, max_age=None):
    base = validation.document(filters, mode='filter')
    parts = [base] if base else []
    bounds = {}
    for key, value in (('$gte', min_age), ('$lte', max_age)):
        if value is not None:
            if type(value) not in (int, float) or not 0 <= value <= 10000 or not isfinite(value):
                raise ValidationError('Age bounds must be finite numbers from 0 to 10000.')
            bounds[key] = value
    if min_age is not None and max_age is not None and min_age > max_age:
        raise ValidationError('Minimum age cannot exceed maximum age.')
    if bounds:
        parts.append({'age_upon_outcome_in_weeks': bounds})
    if category is not None:
        parts.append(rescue_query(category))
    return {'$and': parts} if len(parts) > 1 else (parts[0] if parts else {})

@dataclass(frozen=True)
class SearchSpec:
    query: dict
    projection: dict | None
    sort: tuple
    page: int
    page_size: int

    @property
    def offset(self):
        return (self.page - 1) * self.page_size

def specification(filters, *, category=None, min_age=None, max_age=None,
                  sort_by='_id', direction=1, fields=None, page=1, page_size=25):
    query = match(filters, category, min_age, max_age)
    if not isinstance(sort_by, str) or sort_by not in FIELDS:
        raise ValidationError('Unsupported sort field.')
    if type(direction) is not int or direction not in (-1, 1):
        raise ValidationError('Sort direction must be 1 or -1.')
    if type(page) is not int or page < 1:
        raise ValidationError('Page must be a positive integer.')
    if type(page_size) is not int or not 1 <= page_size <= MAX_PAGE_SIZE:
        raise ValidationError('Page size must be an integer from 1 to 100.')
    if (page - 1) * page_size > MAX_OFFSET:
        raise ValidationError('Page offset exceeds 100000; use a narrower search.')
    projection = None
    if fields is not None:
        if (not isinstance(fields, (list, tuple)) or not fields or
            any(not isinstance(f, str) or f not in FIELDS for f in fields)):
            raise ValidationError('Projection must be a nonempty list of approved fields.')
        projection = {f: 1 for f in fields}
        projection['_id'] = 1 if '_id' in fields else 0
    sort = ((sort_by, direction),) if sort_by == '_id' else ((sort_by, direction), ('_id', direction))
    return SearchSpec(query, projection, sort, page, page_size)

def summary_pipeline(filters, *, category=None, min_age=None, max_age=None, limit=100):
    if type(limit) is not int or not 1 <= limit <= 100:
        raise ValidationError('Summary limit must be an integer from 1 to 100.')
    query = match(filters, category, min_age, max_age)
    branches = []
    for label, (breeds, low, high) in RESCUES.items():
        branches.append({'case': {'$and': [
            {'$eq': ['$animal_type', 'Dog']}, {'$in': ['$breed', list(breeds)]},
            {'$eq': ['$sex_upon_outcome', 'Intact Male']},
            {'$isNumber': '$age_upon_outcome_in_weeks'},
            {'$gte': ['$age_upon_outcome_in_weeks', low]},
            {'$lte': ['$age_upon_outcome_in_weeks', high]}]}, 'then': label})
    # With no explicit category, overlaps use water, mountain, disaster precedence.
    category_expression = {'$literal': category} if category else {'$switch': {
        'branches': branches, 'default': 'unclassified'}}
    return [{'$match': query}, {'$group': {
        '_id': {'breed': {'$ifNull': ['$breed', 'Unknown']}, 'category': category_expression},
        'count': {'$sum': 1}}}, {'$sort': {'count': -1, '_id.category': 1, '_id.breed': 1}},
        {'$limit': limit}]
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
database_demo.py

Download this file

"""Read-only demo using configured AAC data; index setup is a separate action."""
import json
from animal_shelter.config import MongoConfig
from animal_shelter.database_repository import DatabaseRepository
from animal_shelter.database_service import DatabaseService

with DatabaseService(DatabaseRepository.connect(MongoConfig.from_env())) as service:
    page = service.search(category='water', fields=['animal_id', 'breed', 'age_upon_outcome_in_weeks'],
                          sort_by='age_upon_outcome_in_weeks', page_size=10)
    print(json.dumps({'records': page.records, 'has_next': page.has_next,
                      'summary': service.rescue_summary(category='water')}, indent=2, default=str))
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())
live_verify.py

Download this file

"""Live functional checks and explain comparison on a new disposable collection.

Uses MONGODB_URI; never reads, clears, or modifies the AAC animals collection.
Writes only a uniquely named collection under cs499_verification; drops it on exit.
"""
import json
import os
from pathlib import Path
from uuid import uuid4
from bson import ObjectId
from animal_shelter.config import MongoConfig
from animal_shelter.database_repository import DatabaseRepository, INDEX_NAME
from animal_shelter.database_service import DatabaseService
from animal_shelter.search import specification

def stages(value):
    result = set()
    if isinstance(value, dict):
        if 'stage' in value:
            result.add(value['stage'])
        for child in value.values():
            result.update(stages(child))
    elif isinstance(value, list):
        for child in value:
            result.update(stages(child))
    return sorted(result)

def metrics(plan):
    stats = plan['executionStats']
    return {**{k: stats[k] for k in ('nReturned', 'totalDocsExamined',
             'totalKeysExamined', 'executionTimeMillis')}, 'stages': stages(stats['executionStages'])}

def run(output):
    collection_name = 'verify_' + uuid4().hex
    config = MongoConfig(os.environ.get('MONGODB_URI', 'mongodb://127.0.0.1:27017/'),
                         'cs499_verification', collection_name, 10000)
    repo = DatabaseRepository.connect(config)
    collection = repo._collection  # Trusted administrative fixture setup.
    try:
        documents = []
        for i in range(10000):
            candidate = i % 100 == 0
            documents.append({'_id': ObjectId(f'{i + 1:024x}'), 'animal_id': f'DEMO{i:05}',
                'animal_type': 'Dog' if candidate else 'Cat',
                'breed': 'Labrador Retriever Mix' if candidate else 'Domestic Shorthair',
                'sex_upon_outcome': 'Intact Male' if candidate else 'Spayed Female',
                'age_upon_outcome_in_weeks': 52, 'name': 'Demo', 'color': 'Black'})
        collection.insert_many(documents)
        service = DatabaseService(repo)
        checks = []
        before_indexes = repo.list_indexes()
        spec = specification({}, category='water', sort_by='age_upon_outcome_in_weeks',
                             fields=['animal_id', 'breed'], page_size=100)
        expected = tuple({'animal_id': x['animal_id'], 'breed': x['breed']}
                         for x in documents if x['animal_type'] == 'Dog')
        before_records = repo.search(spec).records
        assert before_records == expected
        before = repo.explain(spec)  # No package index exists yet.
        natural = repo.explain(spec, hint='natural')
        repo.ensure_indexes()
        repo.ensure_indexes()  # Idempotence.
        after = repo.explain(spec)
        hinted = repo.explain(spec, hint=INDEX_NAME)
        assert repo.search(spec).records == before_records
        checks.append('Same 100 candidate records and projection before and after indexing')
        gathered = []
        for page in range(1, 8):
            result = service.search(category='water', sort_by='breed', fields=['animal_id'],
                                    page=page, page_size=17)
            gathered.extend(x['animal_id'] for x in result.records)
            assert result.has_next == (page < 6)
        assert gathered == [x['animal_id'] for x in expected]
        checks.append('Stable pages have no duplicates or omissions; last and empty pages verified')
        assert service.search({'animal_type': 'Cat'}, category='water').records == ()
        checks.append('Contradictory validated filters return no candidates')
        water = service.rescue_summary(category='water')
        assert water == ({'_id': {'breed': 'Labrador Retriever Mix', 'category': 'water'}, 'count': 100},)
        all_summary = service.rescue_summary()
        assert sum(x['count'] for x in all_summary) == 10000
        assert {x['_id']['category']: x['count'] for x in all_summary} == {'unclassified': 9900, 'water': 100}
        checks.append('Server aggregation returns exact counts with and without category filters')
        # Add policy boundaries and overlapping breeds after performance measurements.
        collection.insert_many([
            {'animal_type': 'Dog', 'breed': 'Newfoundland', 'sex_upon_outcome': 'Intact Male',
             'age_upon_outcome_in_weeks': age, 'animal_id': f'BOUND{age}'} for age in (25, 26, 156, 157)])
        assert len(service.search({'breed': 'Newfoundland'}, category='water').records) == 2
        collection.insert_one({'animal_type': 'Dog', 'breed': 'German Shepherd',
            'sex_upon_outcome': 'Intact Male', 'age_upon_outcome_in_weeks': 52, 'animal_id': 'OVERLAP'})
        assert service.rescue_summary({'animal_id': 'OVERLAP'})[0]['_id']['category'] == 'mountain'
        assert service.rescue_summary({'animal_id': 'OVERLAP'}, category='disaster')[0]['_id']['category'] == 'disaster'
        checks.append('Inclusive age boundaries and documented overlap precedence verified')
        data = {'server_version': repo._client.server_info()['version'], 'driver': __import__('pymongo').version,
                'fixture_records': 10000, 'fixture': 'Generated data; not the AAC dataset',
                'checks': checks, 'indexes_before': before_indexes, 'indexes_after': repo.list_indexes(),
                'metrics': {label: metrics(plan) for label, plan in (
                    ('before_unhinted', before), ('natural_scan_control', natural),
                    ('after_unhinted', after), ('index_hint_control', hinted))},
                'limitations': ['Single selective synthetic workload; not a production benchmark',
                    'Explain bypasses plan cache; millisecond timings can round to zero',
                    'Indexes do not accelerate every sort; offset pagination slows with depth']}
        Path(output).write_text(json.dumps(data, indent=2, default=str) + '\n')
        print(json.dumps(data, indent=2, default=str))
    finally:
        collection.drop()
        repo.close()

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', default='live_results.json')
    run(parser.parse_args().output)
requirements.txt

Download this file

pymongo==4.18.1
dnspython==2.8.0
setup_indexes.py

Download this file

"""Deployment action: create the package index on the configured collection."""
from animal_shelter.config import MongoConfig
from animal_shelter.database_repository import DatabaseRepository

repo = DatabaseRepository.connect(MongoConfig.from_env())
try:
    print('Existing index names:', [x['name'] for x in repo.list_indexes()])
    print('Ensured index:', repo.ensure_indexes())
finally:
    repo.close()
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_database.py

Download this file

import unittest
from unittest.mock import MagicMock
from pymongo.errors import OperationFailure
from animal_shelter import search
from animal_shelter.errors import ValidationError, RepositoryError, ResourceClosedError
from animal_shelter.database_repository import DatabaseRepository, INDEX_NAME, INDEX_KEYS
from animal_shelter.database_service import DatabaseService

class PolicyTests(unittest.TestCase):
    def test_injection_rejected(self):
        for value in ({'$where': 'evil'}, {'breed': {'$ne': ''}}, {'breed.x': 'x'},
                      {'age_upon_outcome_in_weeks': True}):
            with self.subTest(value=value), self.assertRaises(ValidationError):
                search.specification(value)

    def test_invalid_options(self):
        for kw in ({'page': True}, {'page': 0}, {'page_size': 0}, {'page_size': 101},
                   {'page': 100002}, {'direction': True}, {'direction': 0},
                   {'sort_by': '$where'}, {'fields': 'breed'}, {'fields': []},
                   {'fields': ['$secret']}, {'category': 'unknown'},
                   {'min_age': float('nan')}, {'max_age': float('inf')},
                   {'min_age': True}, {'min_age': 50, 'max_age': 20}):
            with self.subTest(kw=kw), self.assertRaises(ValidationError):
                search.specification({}, **kw)

    def test_copy_sort_projection_and_offset(self):
        filters = {'breed': 'Labrador Retriever Mix'}
        spec = search.specification(filters, fields=['breed'], sort_by='breed', page=3, page_size=2)
        filters['breed'] = 'changed'
        self.assertEqual(spec.query['breed'], 'Labrador Retriever Mix')
        self.assertEqual(spec.sort, (('breed', 1), ('_id', 1)))
        self.assertEqual(spec.projection, {'breed': 1, '_id': 0})
        self.assertEqual(spec.offset, 4)

    def test_rescue_and_user_constraints_intersect(self):
        spec = search.specification({'animal_type': 'Cat'}, category='water', min_age=30)
        self.assertEqual(len(spec.query['$and']), 3)
        self.assertEqual(spec.query['$and'][0]['animal_type'], 'Cat')
        self.assertEqual(spec.query['$and'][2]['animal_type'], 'Dog')

    def test_summary_has_match_group_sort_limit(self):
        pipeline = search.summary_pipeline({}, category='water', limit=4)
        self.assertEqual([next(iter(x)) for x in pipeline], ['$match', '$group', '$sort', '$limit'])
        self.assertEqual(pipeline[1]['$group']['_id']['category'], {'$literal': 'water'})
        self.assertEqual(pipeline[-1], {'$limit': 4})
        with self.assertRaises(ValidationError):
            search.summary_pipeline({}, limit=True)

class AdapterTests(unittest.TestCase):
    def setUp(self):
        self.client = MagicMock()
        self.collection = MagicMock()
        self.collection.name = 'animals'
        self.repo = DatabaseRepository(self.client, self.collection, 1000)
        self.service = DatabaseService(self.repo)
        self.addCleanup(self.service.close)

    def cursor(self, records):
        cursor = MagicMock()
        for name in ('sort', 'skip', 'limit', 'max_time_ms'):
            getattr(cursor, name).return_value = cursor
        cursor.__iter__.return_value = iter(records)
        self.collection.find.return_value = cursor
        return cursor

    def test_search_bounds_and_next_page(self):
        cursor = self.cursor([{'name': 'a'}, {'name': 'b'}, {'name': 'c'}])
        result = self.service.search(page=2, page_size=2, sort_by='name', fields=['name'])
        self.assertEqual(result.records, ({'name': 'a'}, {'name': 'b'}))
        self.assertTrue(result.has_next)
        cursor.skip.assert_called_once_with(2)
        cursor.limit.assert_called_once_with(3)
        cursor.sort.assert_called_once_with([('name', 1), ('_id', 1)])
        cursor.close.assert_called_once()

    def test_empty_and_last_page(self):
        for values in ([], [{'name': 'a'}, {'name': 'b'}]):
            self.cursor(values)
            result = self.service.search(page_size=2)
            self.assertFalse(result.has_next)
            self.assertEqual(len(result.records), len(values))

    def test_failure_closes_cursor_and_hides_driver_details(self):
        cursor = self.cursor([])
        cursor.__iter__.side_effect = OperationFailure('PASSWORD_SENTINEL')
        with self.assertLogs('animal_shelter.mongo_repository', level='ERROR'):
            with self.assertRaises(RepositoryError) as e:
                self.service.search()
        self.assertNotIn('PASSWORD_SENTINEL', str(e.exception))
        cursor.close.assert_called_once()

    def test_invalid_input_never_calls_database(self):
        with self.assertRaises(ValidationError):
            self.service.search({'$where': 'evil'})
        self.collection.find.assert_not_called()

    def test_summary_closes_cursor_and_sets_timeout(self):
        cursor = MagicMock()
        cursor.__iter__.return_value = iter([{'_id': {'breed': 'X'}, 'count': 2}])
        self.collection.aggregate.return_value = cursor
        self.assertEqual(self.service.rescue_summary()[0]['count'], 2)
        self.assertEqual(self.collection.aggregate.call_args.kwargs, {'maxTimeMS': 1000, 'allowDiskUse': False})
        cursor.close.assert_called_once()

    def test_summary_failure_is_controlled(self):
        cursor = MagicMock()
        cursor.__iter__.side_effect = OperationFailure('SECRET')
        self.collection.aggregate.return_value = cursor
        with self.assertLogs('animal_shelter.mongo_repository', level='ERROR'):
            with self.assertRaises(RepositoryError):
                self.service.rescue_summary()
        cursor.close.assert_called_once()

    def test_index_creation_and_inventory(self):
        self.repo.ensure_indexes()
        self.collection.create_index.assert_called_once_with(INDEX_KEYS, name=INDEX_NAME)
        cursor = MagicMock()
        cursor.__iter__.return_value = iter([{'name': '_id_'}])
        self.collection.list_indexes.return_value = cursor
        self.assertEqual(self.repo.list_indexes(), [{'name': '_id_'}])
        cursor.close.assert_called_once()

    def test_explain_uses_same_options_and_restricted_hint(self):
        spec = search.specification({}, page=2, page_size=2, fields=['breed'])
        self.repo.explain(spec, hint='natural')
        args, kwargs = self.collection.database.command.call_args
        self.assertEqual(args[0], 'explain')
        self.assertEqual(args[1]['hint'], {'$natural': 1})
        self.assertEqual(args[1]['skip'], 2)
        self.assertEqual(args[1]['limit'], 3)
        self.assertEqual(kwargs['verbosity'], 'executionStats')
        with self.assertRaises(ValueError):
            self.repo.explain(spec, hint='$evil')

    def test_closed_service_prevents_database_search(self):
        self.service.close()
        with self.assertRaises(ResourceClosedError):
            self.service.search()
        self.collection.find.assert_not_called()

if __name__ == '__main__':
    unittest.main()
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__))