Skip to content
Merged
18 changes: 18 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import contextlib
import importlib
import os
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
Expand All @@ -26,6 +27,23 @@
from dudamel.db import Database


@pytest.fixture(autouse=True)
def _restore_environ():
"""Give every test the process environment it started with, whatever it wrote.

`cli._load_dotenv_into_environ` writes `DUDAMEL_WEB_TOKEN` and friends into
the REAL `os.environ`. A `monkeypatch.delenv(var, raising=False)` guard does
NOT undo that: when the var is absent, pytest records nothing, so the later
write is never reverted and leaks into every following test (it silently
voided the "no token configured" precondition of web-auth tests that ran
after the CLI tests). A snapshot/restore covers writes however they happen.
"""
snapshot = dict(os.environ)
yield
os.environ.clear()
os.environ.update(snapshot)


def _freeze_app_clock(monkeypatch: pytest.MonkeyPatch, instant: str) -> None:
"""Pin `App.today()`'s clock.

Expand Down
9 changes: 4 additions & 5 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,10 @@ def _clean_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
DUDAMEL_WEB_TOKEN, and `run`/`doctor` load that .env into the REAL
process environment (see `cli._load_dotenv_into_environ` -- required
because web/telegram token resolution reads `os.environ` directly, not
a `Settings` field). `monkeypatch.delenv` here registers each var's
CURRENT (absent-or-not) state for restoration, so whatever the CLI
later writes into `os.environ` is undone at teardown regardless -- this
keeps that mutation from leaking into unrelated tests later in the same
pytest process."""
a `Settings` field). The `delenv` below only CLEARS a host-set value so the
test starts without one; it does NOT undo later writes (for an absent var
pytest records nothing to restore). Undoing those is the job of the
session-wide `_restore_environ` fixture in conftest.py."""
for var in ("DUDAMEL_WEB_TOKEN", "DUDAMEL_TELEGRAM_TOKEN", "ANTHROPIC_API_KEY"):
monkeypatch.delenv(var, raising=False)

Expand Down
70 changes: 69 additions & 1 deletion tests/test_display_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
which is the same surface disagreement already fixed one field to the left.
"""

from dudamel.contract.renderers import validate_widget_payload
import pytest

from dudamel.contract.renderers import (
DISPLAY_TEXT_MAX,
clean_action_label,
clean_display_text,
validate_widget_payload,
)


def _one(title: str = "t", subtitle: str | None = None):
Expand Down Expand Up @@ -114,3 +121,64 @@ def test_a_tables_headers_and_string_cells_are_cleaned():
assert "‮" not in payload.columns[0]
assert "‮" not in payload.rows[0][0]
assert payload.rows[0][1:] == [5, 3.5, None]


# Every range in UNSAFE_DISPLAY_CHARS, as (first, last): the codepoints at and
# just inside each edge must go, the ones just outside each edge must stay.
_STRIPPED = [
0x00, # NUL, first of C0
0x09, # TAB: inside the class even though str.strip() would also take it at an edge
0x1F, # US, last of C0
0x7F, # DEL
0x80, # first of C1
0x9F, # APC, last of C1
0x2028, # LINE SEPARATOR
0x2029, # PARAGRAPH SEPARATOR
0x202A, # LRE, first of the embedding/override run
0x202D,
0x202E, # RLO, last of the run
0x2066, # LRI, first of the isolates
0x2069, # PDI, last of the isolates
]
_SURVIVING = [
0x20, # SPACE: one past the end of C0
0x7E, # TILDE: one before DEL
0xA0, # NBSP: one past the end of C1
0x2027, # one before LINE SEPARATOR
0x202F, # NARROW NBSP: one past RLO
0x2065, # one before LRI
0x206A, # one past PDI
0x200E, # LRM -- deliberately NOT in the class (see the comment on it)
0x200F, # RLM -- likewise
]


@pytest.mark.parametrize("cp", _STRIPPED, ids=lambda cp: f"U+{cp:04X}")
@pytest.mark.parametrize("clean", [clean_action_label, clean_display_text])
def test_every_edge_of_the_unsafe_class_is_stripped(cp: int, clean) -> None:
assert clean(f"Ar{chr(cp)}chive") == "Archive"


@pytest.mark.parametrize("cp", _SURVIVING, ids=lambda cp: f"U+{cp:04X}")
@pytest.mark.parametrize("clean", [clean_action_label, clean_display_text])
def test_characters_just_outside_the_unsafe_class_survive(cp: int, clean) -> None:
"""The other half of a boundary: an over-wide class would delete legitimate
text (a space between words, a non-breaking space in a price)."""
text = f"Ar{chr(cp)}chive"
assert clean(text) == text


def test_overrides_are_removed_before_the_outer_whitespace_is_trimmed() -> None:
"""Order matters: stripping first would leave the space that only becomes
outer once the override in front of it is gone."""
assert clean_action_label("\u202e Archive") == "Archive"
assert clean_display_text("\u202e Archive \u202e") == "Archive"


def test_display_text_is_truncated_only_past_the_maximum() -> None:
exact = "x" * DISPLAY_TEXT_MAX
assert clean_display_text(exact) == exact

over = clean_display_text("x" * (DISPLAY_TEXT_MAX + 1))
assert over == "x" * (DISPLAY_TEXT_MAX - 1) + "\u2026"
assert len(over) == DISPLAY_TEXT_MAX
54 changes: 50 additions & 4 deletions tests/test_llm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,58 @@ async def test_the_budget_day_rolls_over_in_the_framework_zone(db: Database, mon
assert (await client.complete([Message(role="user", text="x")])).message.text == "ok"


async def test_the_budget_day_rolls_over_ahead_of_utc_too(db: Database, monkeypatch) -> None:
"""The mirror image for a zone AHEAD of UTC, at an instant where the local
date (Jan 17, Tokyo) is later than the UTC one (Jan 16).

The Tokyo day began at 15:00Z on Jan 16, so spend at 14:59Z belongs to
yesterday and must not count; a day taken from the UTC date would start a
day too early and count it. (The New York test above cannot catch that: at
14:00Z both zones share a date.)
"""
async with db.session() as s:
s.add(
LlmCall(
tier="standard",
provider="fake",
model="m",
tokens_in=900,
tokens_out=200,
created_at=datetime(2026, 1, 16, 14, 59),
)
)
_freeze_client_clock(monkeypatch, datetime(2026, 1, 16, 20, 0, tzinfo=UTC))
client = make_client(
db,
[fake_text("ok")],
budget=BudgetConfig(daily_tokens=1000),
timezone=ZoneInfo("Asia/Tokyo"),
)
assert (await client.complete([Message(role="user", text="x")])).message.text == "ok"


@pytest.mark.parametrize(
"now",
[
datetime(2026, 1, 16, 14, 0, tzinfo=UTC),
# 21:00 on Jan 16 in New York but already Jan 17 in UTC. Here the local
# date and the UTC (or naive wall-clock) date DISAGREE, which is the only
# kind of instant at which "which date is today" can be told apart: at
# 14:00Z both zones say Jan 16 and any date source gives the same window.
datetime(2026, 1, 17, 2, 0, tzinfo=UTC),
],
ids=["same-date-in-both-zones", "utc-is-already-tomorrow"],
)
async def test_spend_inside_the_local_day_still_exhausts_the_budget(
db: Database, monkeypatch
db: Database, monkeypatch, now: datetime
) -> None:
"""The other half of the boundary. 06:00Z on 2026-01-16 IS 2026-01-16 in
"""The other half of the boundary. 10:00Z on 2026-01-16 IS 2026-01-16 in
New York, so it must count -- without this row, an implementation that
simply counts nothing satisfies the test above.

Run at an instant where UTC has already rolled to Jan 17: the day the cap
measures must be the LOCAL one (Jan 16, which began 05:00Z), not the UTC or
wall-clock one, whose window would start at 00:00Z Jan 17 and miss the row.
"""
async with db.session() as s:
s.add(
Expand All @@ -173,10 +219,10 @@ async def test_spend_inside_the_local_day_still_exhausts_the_budget(
model="m",
tokens_in=900,
tokens_out=200,
created_at=datetime(2026, 1, 16, 6, 0),
created_at=datetime(2026, 1, 16, 10, 0),
)
)
_freeze_client_clock(monkeypatch, datetime(2026, 1, 16, 14, 0, tzinfo=UTC))
_freeze_client_clock(monkeypatch, now)
client = make_client(
db,
[fake_text("should never run")],
Expand Down
3 changes: 2 additions & 1 deletion tests/test_release_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def _clean_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
"""Mirrors test_cli.py's fixture of the same purpose: `new`/`db migrate`
write/read a real .env, and `_load_dotenv_into_environ` loads it into the
REAL process environment -- scrub first so a leftover host-env token
can't shadow the one this test generates and reads back."""
can't shadow the one this test generates and reads back. (Restoring what
the CLI writes afterwards is conftest's `_restore_environ`, not this.)"""
for var in ("DUDAMEL_WEB_TOKEN", "DUDAMEL_TELEGRAM_TOKEN", "ANTHROPIC_API_KEY"):
monkeypatch.delenv(var, raising=False)

Expand Down
Loading
Loading