Source code for ds_common_placeholder_py_lib.testing
"""
**File:** ``testing.py``
**Region:** ``ds-common-placeholder-py-lib``
Description
-----------
Test helpers, for tests and offline tooling. Not for code that serves runs.
"""
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING
from . import secret_store
from .functions import time
if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
[docs]
@dataclass
class FakeVault:
"""What :func:`fake_vault` serves, and every key it was asked for."""
values: dict[str, bytes | str | Exception] = field(default_factory=dict)
default: bytes | str | None = None
reads: list[str] = field(default_factory=list)
[docs]
def read(self, key: str) -> bytes | str | None:
self.reads.append(key)
value = self.values.get(key, self.default)
if isinstance(value, Exception):
raise value
return value
[docs]
@contextmanager
def fake_vault(
values: Mapping[str, bytes | str | Exception] | None = None,
*,
default: bytes | str | None = None,
) -> Iterator[FakeVault]:
"""Replace ds-vault while the block runs.
.. code-block:: python
ctx = Context.from_values({"tenant_id": "t1", "db": {"pw": "@{get_secret, /ds/vault/s/t1/k/prod}"}})
with fake_vault({"/ds/vault/s/t1/k/prod": b"c2VjcmV0"}) as vault:
ctx.resolve("db.pw")
assert vault.reads == ["/ds/vault/s/t1/k/prod"]
The tenant check still runs first, so a key of another tenant never
reaches the fake. The fake applies only to the current thread or async
task (a context variable); threads started inside the block do not see
it, and other threads keep reading ds-vault. Code that resolves in a
thread pool needs the context passed along, for example
``executor.submit(contextvars.copy_context().run, fn)``.
Args:
values: Vault key to stored value. An exception value is raised, to
simulate a failing read.
default: Value for keys not in *values*; ``None`` means not found.
Yields:
The fake, with ``reads`` recording every key read.
"""
vault = FakeVault(dict(values or {}), default)
token = secret_store._fake.set(vault.read)
try:
yield vault
finally:
secret_store._fake.reset(token)
[docs]
@contextmanager
def fixed_now(at: str | datetime) -> Iterator[None]:
"""Make the current time *at* while the block runs: for the date
functions given no time, and ``get_iso_timestamp_now`` and
``get_unix_timestamp_now``.
.. code-block:: python
ctx = Context.from_values({"tenant_id": "t1", "run": {"at": "@{get_unix_timestamp_now}"}})
with fixed_now("2026-11-03T10:15:30Z"):
ctx.resolve("run.at") # 1793700930
A date function given a time (``@{get_hour, UTC, run.logical_at}``) is
unaffected.
Like :func:`fake_vault`, it applies to the current thread or async task
only, and nests. A thread started inside the block reads the real time;
pass the context along, e.g. ``executor.submit(contextvars.copy_context().run, fn)``.
Args:
at: An aware datetime, or an ISO 8601 string with a UTC offset.
Raises:
ValueError: If *at* has no UTC offset.
"""
value = datetime.fromisoformat(at) if isinstance(at, str) else at
if value.tzinfo is None:
raise ValueError("fixed_now needs a time with a UTC offset")
token = time._FIXED_NOW.set(value)
try:
yield
finally:
time._FIXED_NOW.reset(token)