Merge main (0.26.0) into the session guard; ship it as 0.26.1
The chat contract took 0.26.0 while this PR waited. The guard's code merged cleanly. The conflicts were the version and the release notes: the version is now 0.26.1, and "0.26.1 notes" follow main's 0.26.0 section in README.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1363,7 +1363,44 @@ person's token.
|
||||
it, inside the rules fence. Rules without `step_id` ask byte for byte as before (golden test
|
||||
unchanged); `build_schema` ignores the extra keys. No schema change, no migration.
|
||||
|
||||
### 0.25.1 notes
|
||||
## Chat contract (0.26.0)
|
||||
|
||||
`dredd_core.chat_contract` (opt-in, standard library only, no tables) is K4 of the Compass split:
|
||||
what a module tells the platform's chat. The chat's rule is **code finds, the model reads**: the
|
||||
browser reads each module with the asker's own session, ranks one-sentence records against the
|
||||
question and gives the best ones to the model as numbered sources, with no tools. Instead of a
|
||||
hand-written reader per module in Atrium, a module may answer
|
||||
`GET <module>/api/v1/chat/records?offset=&limit=` with:
|
||||
|
||||
```json
|
||||
{"version": 1, "module": "galena", "as_of": "2026-11-25T10:00:00+00:00", "next_offset": null,
|
||||
"records": [{"key": "galena:umowa:1f0c", "kind": "umowa", "title": "UM-2026-0017 Najem biura",
|
||||
"text": "Umowa UM-2026-0017 „Najem biura”, kontrahent ACME, obowiązuje do 2027-01-31.",
|
||||
"link": "cards/1f0c", "labels": ["UM-2026-0017", "ACME"],
|
||||
"at": "2026-11-25T10:00:00+00:00"}]}
|
||||
```
|
||||
|
||||
* **Authorisation stays in the module**: a page holds only what the caller may read.
|
||||
* A record is one sentence about one thing: `key` (`<module>:<kind>:<id>`), `kind` (a lower-case
|
||||
word the chat may name), `title`, `text`, `link` (the search contract's link rule, so every cited
|
||||
source opens), optional `labels`, `at`, `members`. Bounded: 500 records a page, `next_offset`
|
||||
pages on (`null` on the last, and a page without the key is refused), title 300 and text 2000
|
||||
(both cut at a word with `…` by `make_record`), 10 labels of 200, 200 members of 300.
|
||||
* **Text is content and stays with the asker**: it goes to the asker's browser and the model they
|
||||
chose, nowhere else. Actions (a contract check, an approval run) are not records; the chat routes
|
||||
them in code.
|
||||
* Module side: `make_record`, `make_page(module, records, total=..., offset=...)` (both validate;
|
||||
`total` is required, so a module cannot forget it and end pagination after one page),
|
||||
`page_params` (clamped offset and limit),
|
||||
`validate_page` for conformance tests. The consumer is Atrium's console (JavaScript).
|
||||
|
||||
### 0.26.0 notes
|
||||
|
||||
* New, opt-in: `dredd_core.chat_contract`. No schema change, no migration.
|
||||
* `search_contract.link_ok` is public (the link rule every contract shares); `_link_ok` stays as an
|
||||
alias.
|
||||
|
||||
### 0.26.1 notes
|
||||
|
||||
* New: `schema.session_update_guard_sql(identity_schema, *, owner_role, writer_role)`, one `DO`
|
||||
block for the identity owner's revision, after `shared_identity_grants_sql`. It closes a gap the
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""The family's chat contract: ONE shape for what a module tells the platform's chat (K4).
|
||||
|
||||
Atrium's chat answers questions about the firm's data by the rule its measurements set (2026-10-28:
|
||||
9-10 of 10 answers right, against 2 of 10 when a model called the modules' APIs itself): **code
|
||||
finds, the model reads**. The browser reads every module the asker may read, with the asker's own
|
||||
session, turns each record into one sentence, ranks them against the question and hands the best
|
||||
ones to the model as numbered sources. Until now each module had a hand-written reader in Atrium
|
||||
(`chatSygna`, `chatCounsel`, `chatGalena` …); this contract lets a module say its records itself, in
|
||||
one shape, so the chat reads any module the same way:
|
||||
|
||||
GET <module>/api/v1/chat/records?offset=0&limit=500
|
||||
|
||||
answered with
|
||||
|
||||
{"version": 1, "module": "galena", "as_of": ISO-8601,
|
||||
"records": [Record, ...], "next_offset": int | null}
|
||||
|
||||
Rules of the contract, in order of importance:
|
||||
|
||||
1. **Authorisation stays in the module.** A page holds only records the CALLER may read, by the
|
||||
same checks the module's own screens make. The chat never filters or re-checks; it reads what it
|
||||
is given, with the person's session (`credentials: same-origin`), never a service account.
|
||||
2. **A record is one sentence about one thing**, written by the module in its own language:
|
||||
``{"key", "kind", "title", "text", "link"}`` plus optional ``"labels"`` (names a question may
|
||||
use for it: a number, a counterparty, a case signature), ``"at"`` (ISO-8601, when it happened or
|
||||
was last changed) and ``"members"`` (keys of records it groups, for a summary record).
|
||||
``key`` is ``<module>:<kind>:<id>`` and unique in the module; ``kind`` is a lower-case word the
|
||||
chat may name (``umowa``, ``sprawa``, ``termin``); ``link`` is a route in the module's console,
|
||||
relative to its root (the search contract's link rule: ``"cards/<id>"``, opened as
|
||||
``<module root>#/cards/<id>``), so every source the model cites can be opened and checked.
|
||||
3. **Text is content, and stays with the asker.** Unlike stats and events, a record carries names,
|
||||
titles and figures: what the person could read on the screen anyway. It travels to the asker's
|
||||
browser and from there to the model the asker chose; a module never sends it anywhere else, and
|
||||
the chat neither stores nor forwards it beyond that conversation.
|
||||
4. **Bounded.** At most :data:`MAX_RECORDS` records a page; a longer list pages through
|
||||
``next_offset`` (``null`` on the last page). ``title`` ≤ :data:`MAX_TITLE`, ``text`` ≤
|
||||
:data:`MAX_TEXT` characters, at most :data:`MAX_LABELS` labels and :data:`MAX_MEMBERS` members.
|
||||
|
||||
Actions (ordering a contract check, starting an approval run) are NOT records: the chat routes them
|
||||
in code, module by module. Extra top-level keys are allowed and ignored (a module may grow); extra
|
||||
record keys are not.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
from .search_contract import link_ok
|
||||
|
||||
__all__ = [
|
||||
"VERSION",
|
||||
"PATH",
|
||||
"MAX_RECORDS",
|
||||
"MAX_TITLE",
|
||||
"MAX_TEXT",
|
||||
"MAX_LABELS",
|
||||
"MAX_LABEL",
|
||||
"MAX_MEMBERS",
|
||||
"MAX_MEMBER",
|
||||
"Record",
|
||||
"RecordsPage",
|
||||
"ContractError",
|
||||
"make_record",
|
||||
"make_page",
|
||||
"page_params",
|
||||
"validate_record",
|
||||
"validate_page",
|
||||
]
|
||||
|
||||
VERSION = 1
|
||||
#: The path every module answers, under its ``/api/v1``.
|
||||
PATH = "/chat/records"
|
||||
MAX_RECORDS = 500
|
||||
MAX_TITLE = 300
|
||||
MAX_TEXT = 2000
|
||||
MAX_LABELS = 10
|
||||
MAX_LABEL = 200
|
||||
MAX_MEMBERS = 200
|
||||
#: The longest member key (a record key: module, kind and id with their separators).
|
||||
MAX_MEMBER = 300
|
||||
|
||||
#: The family's module slug, as `module_permission.module_slug` holds it: hyphens, never underscores.
|
||||
_MODULE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||||
_KIND = re.compile(r"^[a-ząćęłńóśźż][a-ząćęłńóśźż0-9_]{0,39}$")
|
||||
_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
||||
_FIELDS = frozenset({"key", "kind", "title", "text", "link", "labels", "at", "members"})
|
||||
|
||||
|
||||
class Record(TypedDict):
|
||||
key: str
|
||||
kind: str
|
||||
title: str
|
||||
text: str
|
||||
link: str
|
||||
labels: NotRequired[list[str]]
|
||||
at: NotRequired[str]
|
||||
members: NotRequired[list[str]]
|
||||
|
||||
|
||||
class RecordsPage(TypedDict):
|
||||
version: int
|
||||
module: str
|
||||
as_of: str
|
||||
records: list[Record]
|
||||
next_offset: int | None
|
||||
|
||||
|
||||
class ContractError(ValueError):
|
||||
"""A page or record that does not conform to the contract."""
|
||||
|
||||
|
||||
def _iso(value: Any) -> str:
|
||||
if value is None:
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
||||
if isinstance(value, dt.datetime):
|
||||
if value.tzinfo is None:
|
||||
raise ContractError("a time must carry its timezone")
|
||||
return value.isoformat(timespec="seconds")
|
||||
if isinstance(value, dt.date):
|
||||
return value.isoformat()
|
||||
return str(value)
|
||||
|
||||
|
||||
def _is_iso(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
try:
|
||||
dt.datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _one_line(value: str) -> str:
|
||||
return re.sub(r"\s+", " ", value).strip()
|
||||
|
||||
|
||||
def _cut(value: str, most: int) -> str:
|
||||
"""`value` folded to one line and, when longer than `most`, cut at a word with an ellipsis."""
|
||||
value = _one_line(value)
|
||||
if len(value) > most:
|
||||
value = value[:most - 1].rsplit(" ", 1)[0] + "…"
|
||||
return value
|
||||
|
||||
|
||||
def make_record(*, module: str, kind: str, id: Any, title: str, text: str, link: str, # noqa: A002
|
||||
labels: Iterable[str] = (), at: Any = None,
|
||||
members: Iterable[str] = ()) -> Record:
|
||||
"""One record, its key built as ``<module>:<kind>:<id>``, whitespace folded, validated.
|
||||
A title longer than :data:`MAX_TITLE` and text longer than :data:`MAX_TEXT` are cut at a word
|
||||
with an ellipsis rather than refused: a long note is still a record, and the chat reads its
|
||||
beginning. Labels and members are folded the same way and blank ones dropped; one over its
|
||||
length limit is refused (a cut label or key would no longer name anything)."""
|
||||
record: Record = {"key": f"{module}:{kind}:{id}", "kind": kind,
|
||||
"title": _cut(title, MAX_TITLE), "text": _cut(text, MAX_TEXT), "link": link}
|
||||
labels = [_one_line(x) for x in labels if x and _one_line(x)]
|
||||
if labels:
|
||||
record["labels"] = labels
|
||||
if at is not None:
|
||||
record["at"] = _iso(at)
|
||||
members = [_one_line(x) for x in members if x and _one_line(x)]
|
||||
if members:
|
||||
record["members"] = members
|
||||
validate_record(record, module=module)
|
||||
return record
|
||||
|
||||
|
||||
def make_page(module: str, records: list[Record], *, total: int, offset: int = 0,
|
||||
as_of: Any = None) -> RecordsPage:
|
||||
"""The response for one page: ``next_offset`` is ``offset + len(records)`` while `total` (how
|
||||
many records the caller may read in all) says more remain, ``None`` once this page reaches it.
|
||||
`total` is required, so a module cannot leave it out and silently end pagination after the
|
||||
first page. Validated."""
|
||||
more = offset + len(records) < total
|
||||
page: RecordsPage = {"version": VERSION, "module": module, "as_of": _iso(as_of),
|
||||
"records": records,
|
||||
"next_offset": offset + len(records) if more and records else None}
|
||||
validate_page(page)
|
||||
return page
|
||||
|
||||
|
||||
def page_params(offset: Any = 0, limit: Any = MAX_RECORDS) -> tuple[int, int]:
|
||||
"""The request's ``offset`` and ``limit`` as a module should read them: integers, ``offset`` ≥ 0,
|
||||
``limit`` within 1..:data:`MAX_RECORDS` (clamped, not refused)."""
|
||||
try:
|
||||
off = max(0, int(offset))
|
||||
except (TypeError, ValueError):
|
||||
off = 0
|
||||
try:
|
||||
lim = min(MAX_RECORDS, max(1, int(limit)))
|
||||
except (TypeError, ValueError):
|
||||
lim = MAX_RECORDS
|
||||
return off, lim
|
||||
|
||||
|
||||
def _strings(record: Mapping[str, Any], field: str, most: int, longest: int) -> None:
|
||||
value = record.get(field)
|
||||
if value is None:
|
||||
return
|
||||
if not isinstance(value, list) or not all(isinstance(x, str) and x for x in value):
|
||||
raise ContractError(f"record.{field} is not a list of non-empty strings")
|
||||
if len(value) > most:
|
||||
raise ContractError(f"record.{field} has {len(value)} items, over {most}")
|
||||
if any(len(x) > longest for x in value):
|
||||
raise ContractError(f"record.{field} has an item over {longest} characters")
|
||||
|
||||
|
||||
def validate_record(record: Any, *, module: str | None = None) -> None:
|
||||
"""Raise :class:`ContractError` unless `record` conforms; with `module`, its key must be that
|
||||
module's."""
|
||||
if not isinstance(record, dict):
|
||||
raise ContractError("record is not an object")
|
||||
extra = set(record) - _FIELDS
|
||||
if extra:
|
||||
raise ContractError(f"record has keys outside the contract: {sorted(extra)}")
|
||||
for field in ("key", "kind", "title", "text", "link"):
|
||||
if not isinstance(record.get(field), str):
|
||||
raise ContractError(f"record.{field} missing or not a string")
|
||||
kind = record["kind"]
|
||||
if not _KIND.match(kind):
|
||||
raise ContractError(f"record.kind is not a lower-case word: {kind!r}")
|
||||
parts = record["key"].split(":", 2)
|
||||
if (len(parts) != 3 or not _MODULE.match(parts[0]) or parts[1] != kind
|
||||
or not _ID.match(parts[2])):
|
||||
raise ContractError(f"record.key is not <module>:<kind>:<id>: {record['key']!r}")
|
||||
if module is not None and parts[0] != module:
|
||||
raise ContractError(f"record.key names module {parts[0]!r}, not {module!r}")
|
||||
if not record["title"].strip() or len(record["title"]) > MAX_TITLE:
|
||||
raise ContractError(f"record.title is empty or over {MAX_TITLE} characters")
|
||||
if not record["text"].strip() or len(record["text"]) > MAX_TEXT:
|
||||
raise ContractError(f"record.text is empty or over {MAX_TEXT} characters")
|
||||
if not link_ok(record["link"]):
|
||||
raise ContractError(f"record.link is not a console route: {record['link']!r}")
|
||||
_strings(record, "labels", MAX_LABELS, MAX_LABEL)
|
||||
_strings(record, "members", MAX_MEMBERS, MAX_MEMBER)
|
||||
if "at" in record and not _is_iso(record["at"]):
|
||||
raise ContractError("record.at is not an ISO-8601 string")
|
||||
|
||||
|
||||
def validate_page(body: Any) -> None:
|
||||
"""Raise :class:`ContractError` unless `body` conforms (extra top-level keys are allowed)."""
|
||||
if not isinstance(body, dict):
|
||||
raise ContractError("page is not an object")
|
||||
if body.get("version") != VERSION:
|
||||
raise ContractError(f"page.version is not {VERSION}: {body.get('version')!r}")
|
||||
module = body.get("module")
|
||||
if not isinstance(module, str) or not _MODULE.match(module):
|
||||
raise ContractError(f"page.module is not a module slug: {module!r}")
|
||||
if not _is_iso(body.get("as_of")):
|
||||
raise ContractError("page.as_of missing or not an ISO-8601 string")
|
||||
records = body.get("records")
|
||||
if not isinstance(records, list):
|
||||
raise ContractError("page.records missing or not a list")
|
||||
if len(records) > MAX_RECORDS:
|
||||
raise ContractError(f"page carries {len(records)} records, over {MAX_RECORDS}")
|
||||
if "next_offset" not in body:
|
||||
raise ContractError("page.next_offset is missing (it is null on the last page)")
|
||||
nxt = body["next_offset"]
|
||||
if nxt is not None and (isinstance(nxt, bool) or not isinstance(nxt, int) or nxt < 1):
|
||||
raise ContractError("page.next_offset is neither null nor a positive integer")
|
||||
seen: set[str] = set()
|
||||
for record in records:
|
||||
validate_record(record, module=module)
|
||||
if record["key"] in seen:
|
||||
raise ContractError(f"record key {record['key']!r} appears twice")
|
||||
seen.add(record["key"])
|
||||
@@ -59,6 +59,7 @@ __all__ = [
|
||||
"validate_hit",
|
||||
"validate_response",
|
||||
"ContractError",
|
||||
"link_ok",
|
||||
]
|
||||
|
||||
VERSION = 1
|
||||
@@ -153,7 +154,9 @@ def empty_response(q: str = "") -> SearchResponse:
|
||||
return {"version": VERSION, "q": q, "hits": [], "truncated": False}
|
||||
|
||||
|
||||
def _link_ok(link: Any) -> bool:
|
||||
def link_ok(link: Any) -> bool:
|
||||
"""True for a console route relative to the module root (``"cards/<id>"``): not absolute, not a
|
||||
fragment, no scheme. The rule every contract's ``link`` follows."""
|
||||
if not isinstance(link, str) or not link.strip():
|
||||
return False
|
||||
if link.startswith(("/", "#")) or "://" in link or link.lower().startswith("javascript:"):
|
||||
@@ -161,6 +164,10 @@ def _link_ok(link: Any) -> bool:
|
||||
return "undefined" not in link and "null" not in link.split("/") and "None" not in link.split("/")
|
||||
|
||||
|
||||
#: Kept for modules that imported the private name before :func:`link_ok` was public.
|
||||
_link_ok = link_ok
|
||||
|
||||
|
||||
def validate_hit(hit: Any) -> None:
|
||||
if not isinstance(hit, dict):
|
||||
raise ContractError(f"hit is not an object: {hit!r}")
|
||||
@@ -173,7 +180,7 @@ def validate_hit(hit: Any) -> None:
|
||||
raise ContractError(f"hit.title is empty: {hit!r}")
|
||||
if not hit["id"]:
|
||||
raise ContractError(f"hit.id is empty: {hit!r}")
|
||||
if not _link_ok(hit["link"]):
|
||||
if not link_ok(hit["link"]):
|
||||
raise ContractError(f"hit.link is not a module-relative route: {hit['link']!r}")
|
||||
if "kind_label" in hit and not isinstance(hit["kind_label"], str):
|
||||
raise ContractError("hit.kind_label is not a string")
|
||||
|
||||
@@ -43,7 +43,7 @@ from collections.abc import Callable, Iterable, Mapping
|
||||
from concurrent.futures import ThreadPoolExecutor, wait
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
from .search_contract import _link_ok
|
||||
from .search_contract import link_ok
|
||||
|
||||
__all__ = [
|
||||
"VERSION",
|
||||
@@ -162,7 +162,7 @@ def validate_tile(tile: Any) -> None:
|
||||
count = tile.get("count")
|
||||
if isinstance(count, bool) or not isinstance(count, int) or not 0 <= count <= MAX_COUNT:
|
||||
raise ContractError(f"tile.count is not a non-negative integer: {count!r}")
|
||||
if not _link_ok(tile["link"]):
|
||||
if not link_ok(tile["link"]):
|
||||
raise ContractError(f"tile.link is not a module-relative route: {tile['link']!r}")
|
||||
if "as_of" in tile and not _is_iso(tile["as_of"]):
|
||||
raise ContractError("tile.as_of is not an ISO-8601 string")
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "dredd-core"
|
||||
version = "0.25.1"
|
||||
version = "0.26.1"
|
||||
description = "Dredd core — the shared identity/session/auth/audit/ORM foundation for the family (Galena, Sygna, Counsel Scorecard, Galena Connect). Modules import it; it never imports a module."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""dredd_core.chat_contract — DB-free: the record and page shapes, their helpers and validators."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
import pytest
|
||||
|
||||
from dredd_core import chat_contract as cc
|
||||
|
||||
T = dt.datetime(2026, 11, 25, 10, 0, tzinfo=dt.timezone.utc)
|
||||
|
||||
|
||||
def _record(**over):
|
||||
kw = dict(module="galena", kind="umowa", id="1f0c", title="UM-2026-0017 Najem biura",
|
||||
text="Umowa UM-2026-0017 „Najem biura”,\n kontrahent ACME, obowiązuje do 2027-01-31.",
|
||||
link="cards/1f0c", labels=["UM-2026-0017", "ACME"], at=T)
|
||||
kw.update(over)
|
||||
return cc.make_record(**kw)
|
||||
|
||||
|
||||
def test_a_record_is_one_sentence_keyed_by_module_kind_and_id():
|
||||
r = _record()
|
||||
assert r == {"key": "galena:umowa:1f0c", "kind": "umowa", "title": "UM-2026-0017 Najem biura",
|
||||
"text": "Umowa UM-2026-0017 „Najem biura”, kontrahent ACME, obowiązuje do 2027-01-31.",
|
||||
"link": "cards/1f0c", "labels": ["UM-2026-0017", "ACME"],
|
||||
"at": "2026-11-25T10:00:00+00:00"}
|
||||
|
||||
|
||||
def test_optional_parts_are_left_out_and_long_text_is_cut_at_a_word():
|
||||
r = _record(labels=["", " "], at=None, text="słowo " * 1000)
|
||||
assert "labels" not in r and "at" not in r and "members" not in r
|
||||
assert len(r["text"]) <= cc.MAX_TEXT and r["text"].endswith("…")
|
||||
assert not r["text"][:-1].endswith(" ")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("over, message", [
|
||||
({"kind": "Umowa"}, "kind"),
|
||||
({"id": "a b"}, "key"),
|
||||
({"title": " "}, "title"),
|
||||
({"text": ""}, "text"),
|
||||
({"link": "#/cards/1"}, "link"),
|
||||
({"link": "https://evil.example/x"}, "link"),
|
||||
({"labels": ["x" * (cc.MAX_LABEL + 1)]}, "labels"),
|
||||
({"at": dt.datetime(2026, 11, 25)}, "timezone"),
|
||||
])
|
||||
def test_a_bad_record_is_refused_where_it_is_made(over, message):
|
||||
with pytest.raises(cc.ContractError, match=message):
|
||||
_record(**over)
|
||||
|
||||
|
||||
def test_a_record_with_keys_outside_the_contract_is_refused():
|
||||
r = dict(_record(), body="the whole contract")
|
||||
with pytest.raises(cc.ContractError, match="outside the contract"):
|
||||
cc.validate_record(r)
|
||||
|
||||
|
||||
def test_a_page_pages_through_next_offset():
|
||||
records = [_record(id=str(i)) for i in range(3)]
|
||||
first = cc.make_page("galena", records, offset=0, total=5, as_of=T)
|
||||
assert first["next_offset"] == 3 and first["version"] == 1
|
||||
last = cc.make_page("galena", records[:2], offset=3, total=5, as_of=T)
|
||||
assert last["next_offset"] is None
|
||||
assert cc.make_page("galena", [], total=0, as_of=T)["next_offset"] is None
|
||||
|
||||
|
||||
def test_a_page_holds_only_its_modules_records_each_once():
|
||||
with pytest.raises(cc.ContractError, match="names module"):
|
||||
cc.make_page("sygna", [_record()], total=1, as_of=T)
|
||||
with pytest.raises(cc.ContractError, match="twice"):
|
||||
cc.make_page("galena", [_record(), _record()], total=2, as_of=T)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("over", [
|
||||
{"version": 2}, {"module": "Galena"}, {"as_of": "yesterday"}, {"records": {}},
|
||||
{"next_offset": 0}, {"next_offset": True}, {"next_offset": "3"},
|
||||
])
|
||||
def test_a_bad_page_is_refused(over):
|
||||
page = dict(cc.make_page("galena", [_record()], total=1, as_of=T), **over)
|
||||
with pytest.raises(cc.ContractError):
|
||||
cc.validate_page(page)
|
||||
|
||||
|
||||
def test_next_offset_is_required_and_extra_top_level_keys_are_not_refused():
|
||||
page = cc.make_page("galena", [_record()], total=1, as_of=T)
|
||||
cc.validate_page(dict(page, hint="a module may grow"))
|
||||
page.pop("next_offset")
|
||||
with pytest.raises(cc.ContractError, match="next_offset is missing"):
|
||||
cc.validate_page(page)
|
||||
|
||||
|
||||
def test_too_many_records_on_a_page():
|
||||
page = cc.make_page("galena", [_record()], total=1, as_of=T)
|
||||
page["records"] = [_record(id=str(i)) for i in range(cc.MAX_RECORDS + 1)]
|
||||
with pytest.raises(cc.ContractError, match="over"):
|
||||
cc.validate_page(page)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, read", [
|
||||
((None, None), (0, cc.MAX_RECORDS)), (("-5", "0"), (0, 1)), (("20", "9999"), (20, cc.MAX_RECORDS)),
|
||||
(("x", "y"), (0, cc.MAX_RECORDS)), ((10, 50), (10, 50)),
|
||||
])
|
||||
def test_page_params_clamp_rather_than_refuse(raw, read):
|
||||
assert cc.page_params(*raw) == read
|
||||
|
||||
|
||||
def test_the_module_is_a_family_slug():
|
||||
with pytest.raises(cc.ContractError, match="slug"):
|
||||
cc.make_page("my_module", [], total=0, as_of=T)
|
||||
assert cc.make_page("m2", [], total=0, as_of=T)["module"] == "m2"
|
||||
|
||||
|
||||
def test_total_is_required_so_pagination_cannot_stop_silently():
|
||||
with pytest.raises(TypeError):
|
||||
cc.make_page("galena", [_record()], as_of=T) # type: ignore[call-arg]
|
||||
|
||||
|
||||
def test_a_long_title_is_cut_at_a_word_like_text():
|
||||
r = _record(title="tytuł " * 100)
|
||||
assert len(r["title"]) <= cc.MAX_TITLE and r["title"].endswith("…")
|
||||
assert not r["title"][:-1].endswith(" ")
|
||||
|
||||
|
||||
def test_members_are_folded_and_blank_ones_dropped_like_labels():
|
||||
r = _record(members=["galena:umowa:1", " ", "", " galena:umowa:2 "])
|
||||
assert r["members"] == ["galena:umowa:1", "galena:umowa:2"]
|
||||
with pytest.raises(cc.ContractError, match="members"):
|
||||
_record(members=["x" * (cc.MAX_MEMBER + 1)])
|
||||
|
||||
|
||||
def test_link_ok_is_public_and_the_private_name_still_works():
|
||||
from dredd_core import search_contract as sc
|
||||
assert sc.link_ok("cards/1") and not sc.link_ok("#/cards/1")
|
||||
assert sc._link_ok is sc.link_ok
|
||||
Reference in New Issue
Block a user