resource-engine 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- resource_engine/__init__.py +96 -0
- resource_engine/application/__init__.py +1 -0
- resource_engine/application/actions.py +48 -0
- resource_engine/application/context.py +111 -0
- resource_engine/application/events.py +54 -0
- resource_engine/application/hooks.py +272 -0
- resource_engine/application/idempotency.py +277 -0
- resource_engine/application/manager.py +1987 -0
- resource_engine/application/query.py +47 -0
- resource_engine/application/registry.py +137 -0
- resource_engine/application/relations.py +470 -0
- resource_engine/application/resource.py +984 -0
- resource_engine/application/searching.py +162 -0
- resource_engine/application/settings.py +169 -0
- resource_engine/application/slots.py +67 -0
- resource_engine/application/state_machines.py +177 -0
- resource_engine/application/timers.py +347 -0
- resource_engine/application/transaction.py +100 -0
- resource_engine/application/views.py +239 -0
- resource_engine/audit/__init__.py +40 -0
- resource_engine/audit/export.py +280 -0
- resource_engine/audit/history.py +165 -0
- resource_engine/audit/janitor.py +257 -0
- resource_engine/audit/model.py +98 -0
- resource_engine/audit/recorder.py +145 -0
- resource_engine/audit/resource.py +68 -0
- resource_engine/audit/seal.py +327 -0
- resource_engine/audit/sink.py +69 -0
- resource_engine/authz/__init__.py +72 -0
- resource_engine/authz/apikeys.py +300 -0
- resource_engine/authz/base.py +143 -0
- resource_engine/authz/catalog.py +291 -0
- resource_engine/authz/conditions.py +416 -0
- resource_engine/authz/config.py +77 -0
- resource_engine/authz/evaluator.py +382 -0
- resource_engine/authz/external.py +249 -0
- resource_engine/authz/fields.py +44 -0
- resource_engine/authz/model.py +145 -0
- resource_engine/authz/resources.py +289 -0
- resource_engine/authz/roles.py +101 -0
- resource_engine/cache.py +144 -0
- resource_engine/calls.py +100 -0
- resource_engine/capabilities.py +145 -0
- resource_engine/composite.py +295 -0
- resource_engine/documents/__init__.py +69 -0
- resource_engine/documents/content.py +57 -0
- resource_engine/documents/events.py +49 -0
- resource_engine/documents/janitor.py +93 -0
- resource_engine/documents/machine.py +38 -0
- resource_engine/documents/manager.py +704 -0
- resource_engine/documents/model.py +91 -0
- resource_engine/documents/pipeline.py +98 -0
- resource_engine/documents/processors.py +320 -0
- resource_engine/documents/resource.py +39 -0
- resource_engine/domain/__init__.py +10 -0
- resource_engine/domain/events.py +50 -0
- resource_engine/domain/exceptions.py +23 -0
- resource_engine/email.py +417 -0
- resource_engine/errors.py +562 -0
- resource_engine/explorer.py +133 -0
- resource_engine/exports.py +687 -0
- resource_engine/generation.py +233 -0
- resource_engine/i18n.py +251 -0
- resource_engine/identity.py +46 -0
- resource_engine/integration.py +80 -0
- resource_engine/jobs.py +390 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/logs.py +201 -0
- resource_engine/messaging/__init__.py +73 -0
- resource_engine/messaging/asyncapi.py +529 -0
- resource_engine/messaging/cloudevents.py +98 -0
- resource_engine/messaging/consumer.py +165 -0
- resource_engine/messaging/delivery.py +115 -0
- resource_engine/messaging/envelope.py +193 -0
- resource_engine/messaging/hub.py +148 -0
- resource_engine/messaging/inbound.py +76 -0
- resource_engine/messaging/inspection.py +113 -0
- resource_engine/messaging/janitor.py +136 -0
- resource_engine/messaging/live.py +179 -0
- resource_engine/messaging/processing.py +357 -0
- resource_engine/messaging/publishing.py +318 -0
- resource_engine/messaging/relay.py +84 -0
- resource_engine/messaging/worker.py +166 -0
- resource_engine/nosql.py +394 -0
- resource_engine/ports/__init__.py +13 -0
- resource_engine/ports/activity.py +171 -0
- resource_engine/ports/audit.py +42 -0
- resource_engine/ports/authz.py +132 -0
- resource_engine/ports/cache.py +41 -0
- resource_engine/ports/email.py +118 -0
- resource_engine/ports/event_publisher.py +34 -0
- resource_engine/ports/idempotency.py +69 -0
- resource_engine/ports/identity.py +112 -0
- resource_engine/ports/locks.py +28 -0
- resource_engine/ports/messaging.py +197 -0
- resource_engine/ports/observability.py +60 -0
- resource_engine/ports/ratelimit.py +59 -0
- resource_engine/ports/repository.py +56 -0
- resource_engine/ports/storage.py +93 -0
- resource_engine/ports/templates.py +54 -0
- resource_engine/ports/tracing.py +61 -0
- resource_engine/ports/unit_of_work.py +46 -0
- resource_engine/processes.py +408 -0
- resource_engine/py.typed +0 -0
- resource_engine/querying.py +319 -0
- resource_engine/ratelimit.py +217 -0
- resource_engine/reporting.py +230 -0
- resource_engine/schema_examples.py +51 -0
- resource_engine/templates.py +143 -0
- resource_engine/tenancy.py +68 -0
- resource_engine/testing/__init__.py +34 -0
- resource_engine/testing/activity.py +123 -0
- resource_engine/testing/contracts.py +1416 -0
- resource_engine/testing/email.py +36 -0
- resource_engine/testing/engine.py +40 -0
- resource_engine/testing/memory.py +603 -0
- resource_engine/testing/storage.py +110 -0
- resource_engine/testing/tracing.py +100 -0
- resource_engine/tracing.py +156 -0
- resource_engine/translatable.py +80 -0
- resource_engine/versions.py +189 -0
- resource_engine-0.1.0.dist-info/METADATA +36 -0
- resource_engine-0.1.0.dist-info/RECORD +128 -0
- resource_engine-0.1.0.dist-info/WHEEL +4 -0
- resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,1416 @@
|
|
|
1
|
+
"""Contract tests that every adapter must pass.
|
|
2
|
+
|
|
3
|
+
Subclass a contract in your adapter's test suite and provide its fixtures::
|
|
4
|
+
|
|
5
|
+
class TestMyRepository(RepositoryContract):
|
|
6
|
+
@pytest.fixture
|
|
7
|
+
def contract_uow_factory(self):
|
|
8
|
+
return my_uow_factory # serving the resource CONTRACT_RESOURCE
|
|
9
|
+
|
|
10
|
+
Requires ``pytest`` and ``pytest-asyncio`` (``asyncio_mode = "auto"``).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from datetime import UTC, datetime, timedelta
|
|
19
|
+
from typing import TYPE_CHECKING, Any
|
|
20
|
+
|
|
21
|
+
import pytest
|
|
22
|
+
|
|
23
|
+
from resource_engine.application.query import ListQuery
|
|
24
|
+
from resource_engine.application.settings import Access, Versioned
|
|
25
|
+
from resource_engine.messaging.envelope import EventEnvelope
|
|
26
|
+
from resource_engine.ports.messaging import SupportsInbox, SupportsOutbox
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from resource_engine.ports.storage import BlobStore
|
|
30
|
+
|
|
31
|
+
CONTRACT_RESOURCE = "contract_items"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class ContractItem:
|
|
36
|
+
"""Entity used by the repository contract. Map it in your adapter's tests."""
|
|
37
|
+
|
|
38
|
+
name: str
|
|
39
|
+
rank: int
|
|
40
|
+
group: str = "a"
|
|
41
|
+
id: int | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def contract_envelope(n: int = 0, **overrides: Any) -> EventEnvelope:
|
|
45
|
+
"""An event envelope for the contract tests, numbered ``n``."""
|
|
46
|
+
data: dict[str, Any] = {
|
|
47
|
+
"type": "ContractEvent",
|
|
48
|
+
"payload": {"n": n, "amount": "12.50", "text": "àèï €"},
|
|
49
|
+
"occurred_at": datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
|
|
50
|
+
"correlation_id": f"corr-{n}",
|
|
51
|
+
"resource": CONTRACT_RESOURCE,
|
|
52
|
+
"key": f"{CONTRACT_RESOURCE}:{n}",
|
|
53
|
+
}
|
|
54
|
+
data.update(overrides)
|
|
55
|
+
return EventEnvelope(**data)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def missing_capabilities(
|
|
59
|
+
uow: Any, *, rollback: bool = False, atomic: bool = False, **query: Any
|
|
60
|
+
) -> list[str]:
|
|
61
|
+
"""What the unit of work, or its ``CONTRACT_RESOURCE`` repository, declares
|
|
62
|
+
it can't do of what a test needs: undo uncommitted writes (``rollback``:
|
|
63
|
+
a transaction or compensations), keep them private and exact until the
|
|
64
|
+
commit (``atomic``: a real transaction), filter or sort by fields, or page
|
|
65
|
+
to an offset (``filters=``, ``order_by=``, ``offset=``). Empty when it can
|
|
66
|
+
do all of it."""
|
|
67
|
+
from resource_engine.capabilities import capabilities
|
|
68
|
+
|
|
69
|
+
caps = capabilities(uow.repository(CONTRACT_RESOURCE), uow)
|
|
70
|
+
missing: list[str] = []
|
|
71
|
+
# "partition" stores buffer writes until the commit: they undo and stay
|
|
72
|
+
# private like a transaction (only a commit across partitions isn't atomic)
|
|
73
|
+
undoes = ("unit_of_work", "partition", "compensated")
|
|
74
|
+
private = ("unit_of_work", "partition")
|
|
75
|
+
if (atomic and caps.transaction_scope not in private) or (
|
|
76
|
+
rollback and caps.transaction_scope not in undoes
|
|
77
|
+
):
|
|
78
|
+
missing.append(f"transaction_scope={caps.transaction_scope!r}")
|
|
79
|
+
if caps.filterable is not None:
|
|
80
|
+
missing += [
|
|
81
|
+
f"filterable lacks {f!r}" for f in query.get("filters", ()) if f not in caps.filterable
|
|
82
|
+
]
|
|
83
|
+
if caps.sortable is not None:
|
|
84
|
+
missing += [
|
|
85
|
+
f"sortable lacks {o.lstrip('-')!r}"
|
|
86
|
+
for o in query.get("order_by", ())
|
|
87
|
+
if o.lstrip("-") not in caps.sortable
|
|
88
|
+
]
|
|
89
|
+
if caps.max_offset is not None and query.get("offset", 0) > caps.max_offset:
|
|
90
|
+
missing.append(f"max_offset={caps.max_offset}")
|
|
91
|
+
return missing
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def require_capability(uow: Any, **needs: Any) -> None:
|
|
95
|
+
"""Skip the running test, naming what the adapter declares it lacks
|
|
96
|
+
(see ``missing_capabilities``)."""
|
|
97
|
+
missing = missing_capabilities(uow, **needs)
|
|
98
|
+
if missing:
|
|
99
|
+
pytest.skip("the adapter declares " + ", ".join(missing))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class UnitOfWorkContract:
|
|
103
|
+
"""Commit and rollback. Rollback cases are skipped, by name, for units of
|
|
104
|
+
work that declare they can't undo writes (``transaction_scope="none"``,
|
|
105
|
+
remote APIs); cases that need writes kept private until the commit also
|
|
106
|
+
for ``"compensated"`` (``CompositeStore`` over a remote store).
|
|
107
|
+
|
|
108
|
+
Entities are only guaranteed usable inside the unit of work that loaded
|
|
109
|
+
them (SQLAlchemy expires them when it ends without a commit): the engine
|
|
110
|
+
reads what it needs before leaving, and so do these tests."""
|
|
111
|
+
|
|
112
|
+
@pytest.fixture
|
|
113
|
+
def contract_uow_factory(self) -> Callable[[], Any]:
|
|
114
|
+
"""Override: a factory of units of work serving ``CONTRACT_RESOURCE``."""
|
|
115
|
+
raise NotImplementedError("Provide a unit of work factory serving CONTRACT_RESOURCE")
|
|
116
|
+
|
|
117
|
+
async def _transactional(self, factory: Callable[[], Any], *, atomic: bool = False) -> None:
|
|
118
|
+
async with factory() as uow:
|
|
119
|
+
require_capability(uow, rollback=True, atomic=atomic)
|
|
120
|
+
|
|
121
|
+
async def test_commit_makes_changes_visible(
|
|
122
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
123
|
+
) -> None:
|
|
124
|
+
async with contract_uow_factory() as uow:
|
|
125
|
+
item = await uow.repository(CONTRACT_RESOURCE).add(ContractItem("a", 1))
|
|
126
|
+
await uow.commit()
|
|
127
|
+
async with contract_uow_factory() as uow:
|
|
128
|
+
assert await uow.repository(CONTRACT_RESOURCE).get(item.id) is not None
|
|
129
|
+
|
|
130
|
+
async def test_leaving_without_commit_rolls_back(
|
|
131
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
132
|
+
) -> None:
|
|
133
|
+
await self._transactional(contract_uow_factory)
|
|
134
|
+
async with contract_uow_factory() as uow:
|
|
135
|
+
item = await uow.repository(CONTRACT_RESOURCE).add(ContractItem("a", 1))
|
|
136
|
+
item_id = item.id
|
|
137
|
+
async with contract_uow_factory() as uow:
|
|
138
|
+
assert await uow.repository(CONTRACT_RESOURCE).get(item_id) is None
|
|
139
|
+
|
|
140
|
+
async def test_exception_rolls_back(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
141
|
+
await self._transactional(contract_uow_factory)
|
|
142
|
+
item_id = None
|
|
143
|
+
with pytest.raises(RuntimeError):
|
|
144
|
+
async with contract_uow_factory() as uow:
|
|
145
|
+
item = await uow.repository(CONTRACT_RESOURCE).add(ContractItem("a", 1))
|
|
146
|
+
item_id = item.id
|
|
147
|
+
raise RuntimeError("boom")
|
|
148
|
+
async with contract_uow_factory() as uow:
|
|
149
|
+
assert await uow.repository(CONTRACT_RESOURCE).get(item_id) is None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class RepositoryContract(UnitOfWorkContract):
|
|
153
|
+
"""Contract of a repository: create, read, list, update and delete through a unit of work."""
|
|
154
|
+
|
|
155
|
+
async def _seed(self, factory: Callable[[], Any]) -> list[ContractItem]:
|
|
156
|
+
async with factory() as uow:
|
|
157
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
158
|
+
items = [
|
|
159
|
+
await repo.add(ContractItem(name, rank, group))
|
|
160
|
+
for name, rank, group in [("c", 3, "a"), ("a", 1, "b"), ("b", 2, "a")]
|
|
161
|
+
]
|
|
162
|
+
await uow.commit()
|
|
163
|
+
return items
|
|
164
|
+
|
|
165
|
+
async def test_add_assigns_distinct_ids(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
166
|
+
items = await self._seed(contract_uow_factory)
|
|
167
|
+
ids = [i.id for i in items]
|
|
168
|
+
assert None not in ids and len(set(ids)) == 3
|
|
169
|
+
|
|
170
|
+
async def test_get_missing_returns_none(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
171
|
+
async with contract_uow_factory() as uow:
|
|
172
|
+
assert await uow.repository(CONTRACT_RESOURCE).get(999_999) is None
|
|
173
|
+
|
|
174
|
+
async def test_update_and_delete(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
175
|
+
item = (await self._seed(contract_uow_factory))[0]
|
|
176
|
+
async with contract_uow_factory() as uow:
|
|
177
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
178
|
+
loaded = await repo.get(item.id)
|
|
179
|
+
loaded.name = "renamed"
|
|
180
|
+
await repo.update(loaded)
|
|
181
|
+
await uow.commit()
|
|
182
|
+
async with contract_uow_factory() as uow:
|
|
183
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
184
|
+
loaded = await repo.get(item.id)
|
|
185
|
+
assert loaded.name == "renamed"
|
|
186
|
+
await repo.delete(loaded)
|
|
187
|
+
await uow.commit()
|
|
188
|
+
async with contract_uow_factory() as uow:
|
|
189
|
+
assert await uow.repository(CONTRACT_RESOURCE).get(item.id) is None
|
|
190
|
+
|
|
191
|
+
async def test_list_filters_orders_and_pages(
|
|
192
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
193
|
+
) -> None:
|
|
194
|
+
await self._seed(contract_uow_factory)
|
|
195
|
+
async with contract_uow_factory() as uow:
|
|
196
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
197
|
+
page = await repo.list(ListQuery(order_by=["rank"]))
|
|
198
|
+
assert [i.name for i in page.items] == ["a", "b", "c"] and page.total == 3
|
|
199
|
+
page = await repo.list(ListQuery(order_by=["-rank"], limit=2, offset=1))
|
|
200
|
+
assert [i.name for i in page.items] == ["b", "a"] and page.total == 3
|
|
201
|
+
page = await repo.list(ListQuery(filters={"group": "a"}, order_by=["name"]))
|
|
202
|
+
assert [i.name for i in page.items] == ["b", "c"] and page.total == 2
|
|
203
|
+
|
|
204
|
+
async def _many(self, factory: Callable[[], Any]) -> list[ContractItem]:
|
|
205
|
+
rows = [("e", 2, "b"), ("a", 1, "a"), ("d", 2, "a"), ("b", 3, "b"), ("c", 2, "a")]
|
|
206
|
+
async with factory() as uow:
|
|
207
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
208
|
+
items = [await repo.add(ContractItem(n, r, g)) for n, r, g in rows]
|
|
209
|
+
await uow.commit()
|
|
210
|
+
return items
|
|
211
|
+
|
|
212
|
+
async def test_paging_walks_every_record_once(
|
|
213
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Pages cover every record exactly once, also when the sort has ties
|
|
216
|
+
(``rank``, ``group``) or there is no sort at all: the adapter must make
|
|
217
|
+
the order total (SQL: the primary key last). 120 records, half of them
|
|
218
|
+
rewritten so the stored order differs from the id order, in pages of 7.
|
|
219
|
+
Sorts the adapter declares it can't run are left out, by name."""
|
|
220
|
+
from resource_engine.capabilities import capabilities
|
|
221
|
+
|
|
222
|
+
async with contract_uow_factory() as uow: # commits no bigger than max_writes
|
|
223
|
+
batch = capabilities(uow.repository(CONTRACT_RESOURCE), uow).max_writes or 120
|
|
224
|
+
every: list[Any] = []
|
|
225
|
+
for start in range(0, 120, batch):
|
|
226
|
+
async with contract_uow_factory() as uow:
|
|
227
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
228
|
+
for i in range(start, min(start + batch, 120)):
|
|
229
|
+
item = await repo.add(ContractItem(f"n{i:03}", i % 3, "ab"[(i * 7) % 2]))
|
|
230
|
+
every.append(item.id)
|
|
231
|
+
await uow.commit()
|
|
232
|
+
every.sort()
|
|
233
|
+
rewrite = every[::2]
|
|
234
|
+
for start in range(0, len(rewrite), batch):
|
|
235
|
+
async with contract_uow_factory() as uow:
|
|
236
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
237
|
+
for item_id in rewrite[start : start + batch]:
|
|
238
|
+
loaded = await repo.get(item_id)
|
|
239
|
+
loaded.name += "x"
|
|
240
|
+
await repo.update(loaded)
|
|
241
|
+
await uow.commit()
|
|
242
|
+
walked, skipped = 0, []
|
|
243
|
+
for order in ([], ["rank"], ["group"], ["-rank"], ["group", "-rank"]):
|
|
244
|
+
async with contract_uow_factory() as uow:
|
|
245
|
+
missing = missing_capabilities(uow, order_by=order, offset=119)
|
|
246
|
+
if missing:
|
|
247
|
+
skipped += missing
|
|
248
|
+
continue
|
|
249
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
250
|
+
seen: list[Any] = []
|
|
251
|
+
for offset in range(0, 120, 7):
|
|
252
|
+
page = await repo.list(ListQuery(order_by=order, limit=7, offset=offset))
|
|
253
|
+
assert page.total == 120, order
|
|
254
|
+
seen += [i.id for i in page.items]
|
|
255
|
+
walked += 1
|
|
256
|
+
assert sorted(seen) == every, f"order {order}: {len(set(seen))} distinct of 120"
|
|
257
|
+
if not walked:
|
|
258
|
+
pytest.skip("the adapter declares " + ", ".join(dict.fromkeys(skipped)))
|
|
259
|
+
|
|
260
|
+
async def test_ordering_by_several_fields(
|
|
261
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
262
|
+
) -> None:
|
|
263
|
+
await self._many(contract_uow_factory)
|
|
264
|
+
async with contract_uow_factory() as uow:
|
|
265
|
+
require_capability(uow, order_by=["group", "-rank", "name"])
|
|
266
|
+
page = await uow.repository(CONTRACT_RESOURCE).list(
|
|
267
|
+
ListQuery(order_by=["group", "-rank", "name"])
|
|
268
|
+
)
|
|
269
|
+
assert [i.name for i in page.items] == ["c", "d", "a", "b", "e"]
|
|
270
|
+
|
|
271
|
+
async def test_filters_combine_and_pages_past_the_end_are_empty(
|
|
272
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
273
|
+
) -> None:
|
|
274
|
+
await self._many(contract_uow_factory)
|
|
275
|
+
async with contract_uow_factory() as uow:
|
|
276
|
+
require_capability(uow, filters=["group", "rank"], order_by=["name"], offset=10)
|
|
277
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
278
|
+
page = await repo.list(ListQuery(filters={"group": "a", "rank": 2}, order_by=["name"]))
|
|
279
|
+
assert [i.name for i in page.items] == ["c", "d"] and page.total == 2
|
|
280
|
+
none = await repo.list(ListQuery(filters={"group": "zz"}))
|
|
281
|
+
assert none.items == [] and none.total == 0
|
|
282
|
+
past = await repo.list(ListQuery(order_by=["name"], offset=10, limit=5))
|
|
283
|
+
assert past.items == [] and past.total == 5
|
|
284
|
+
|
|
285
|
+
async def test_values_round_trip(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
286
|
+
async with contract_uow_factory() as uow:
|
|
287
|
+
item = await uow.repository(CONTRACT_RESOURCE).add(ContractItem("àèï € 漢字", -7, "ç"))
|
|
288
|
+
await uow.commit()
|
|
289
|
+
async with contract_uow_factory() as uow:
|
|
290
|
+
loaded = await uow.repository(CONTRACT_RESOURCE).get(item.id)
|
|
291
|
+
assert (loaded.name, loaded.rank, loaded.group) == ("àèï € 漢字", -7, "ç")
|
|
292
|
+
|
|
293
|
+
async def test_a_rolled_back_update_leaves_the_record(
|
|
294
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
295
|
+
) -> None:
|
|
296
|
+
await self._transactional(contract_uow_factory)
|
|
297
|
+
item = (await self._seed(contract_uow_factory))[0]
|
|
298
|
+
name = item.name
|
|
299
|
+
async with contract_uow_factory() as uow:
|
|
300
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
301
|
+
loaded = await repo.get(item.id)
|
|
302
|
+
loaded.name = "not saved"
|
|
303
|
+
await repo.update(loaded)
|
|
304
|
+
async with contract_uow_factory() as uow:
|
|
305
|
+
stored = await uow.repository(CONTRACT_RESOURCE).get(item.id)
|
|
306
|
+
assert stored is not None and stored.name == name
|
|
307
|
+
|
|
308
|
+
async def test_a_rolled_back_delete_keeps_the_record_and_its_id(
|
|
309
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
310
|
+
) -> None:
|
|
311
|
+
await self._transactional(contract_uow_factory, atomic=True)
|
|
312
|
+
item = (await self._seed(contract_uow_factory))[0]
|
|
313
|
+
with pytest.raises(RuntimeError):
|
|
314
|
+
async with contract_uow_factory() as uow:
|
|
315
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
316
|
+
await repo.delete(await repo.get(item.id))
|
|
317
|
+
raise RuntimeError("boom")
|
|
318
|
+
async with contract_uow_factory() as uow:
|
|
319
|
+
assert await uow.repository(CONTRACT_RESOURCE).get(item.id) is not None
|
|
320
|
+
|
|
321
|
+
async def test_uncommitted_writes_stay_private(
|
|
322
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
323
|
+
) -> None:
|
|
324
|
+
await self._transactional(contract_uow_factory, atomic=True)
|
|
325
|
+
async with contract_uow_factory() as writer:
|
|
326
|
+
await writer.repository(CONTRACT_RESOURCE).add(ContractItem("draft", 1))
|
|
327
|
+
async with contract_uow_factory() as reader:
|
|
328
|
+
page = await reader.repository(CONTRACT_RESOURCE).list(ListQuery())
|
|
329
|
+
assert "draft" not in [i.name for i in page.items]
|
|
330
|
+
|
|
331
|
+
async def test_concurrent_units_of_work_get_distinct_ids(
|
|
332
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
333
|
+
) -> None:
|
|
334
|
+
async def add(n: int) -> Any:
|
|
335
|
+
async with contract_uow_factory() as uow:
|
|
336
|
+
item = await uow.repository(CONTRACT_RESOURCE).add(ContractItem(f"n{n}", n))
|
|
337
|
+
await uow.commit()
|
|
338
|
+
return item.id
|
|
339
|
+
|
|
340
|
+
ids = await asyncio.gather(*(add(n) for n in range(8)))
|
|
341
|
+
assert None not in ids and len(set(ids)) == 8
|
|
342
|
+
async with contract_uow_factory() as uow:
|
|
343
|
+
assert (await uow.repository(CONTRACT_RESOURCE).list(ListQuery(limit=50))).total == 8
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
#: The rows ``ReadOnlyRepositoryContract`` expects: ids 1-40, ties in ``rank``
|
|
347
|
+
#: (0-2) and ``group`` (a, b), one non-ASCII name. Load them into the store.
|
|
348
|
+
CONTRACT_ROWS: list[dict[str, Any]] = [
|
|
349
|
+
{
|
|
350
|
+
"id": i,
|
|
351
|
+
"name": "àèï € 漢字" if i == 40 else f"n{i:02}",
|
|
352
|
+
"rank": i % 3,
|
|
353
|
+
"group": "ab"[(i * 7) % 2],
|
|
354
|
+
}
|
|
355
|
+
for i in range(1, 41)
|
|
356
|
+
]
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class ReadOnlyRepositoryContract:
|
|
360
|
+
"""Reads of stores that only serve them (query engines, views): ``get``,
|
|
361
|
+
filters, sorting and paging over ``CONTRACT_ROWS``, which the adapter's
|
|
362
|
+
tests load first. Paging must see every record once also when the sort has
|
|
363
|
+
ties: the store makes the order total (the id last)."""
|
|
364
|
+
|
|
365
|
+
@pytest.fixture
|
|
366
|
+
def contract_uow_factory(self) -> Callable[[], Any]:
|
|
367
|
+
"""Override: a factory of units of work serving ``CONTRACT_RESOURCE`` over
|
|
368
|
+
``CONTRACT_ROWS``."""
|
|
369
|
+
raise NotImplementedError(
|
|
370
|
+
"Provide a unit of work factory serving CONTRACT_RESOURCE over CONTRACT_ROWS"
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
async def test_get_reads_a_record_and_misses_none(
|
|
374
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
375
|
+
) -> None:
|
|
376
|
+
async with contract_uow_factory() as uow:
|
|
377
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
378
|
+
row = await repo.get(40)
|
|
379
|
+
assert (row.id, row.name, row.rank, row.group) == (40, "àèï € 漢字", 1, "a")
|
|
380
|
+
assert await repo.get(999_999) is None
|
|
381
|
+
|
|
382
|
+
async def test_filters_and_counts(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
383
|
+
expected = sorted(r["id"] for r in CONTRACT_ROWS if r["group"] == "a" and r["rank"] == 2)
|
|
384
|
+
async with contract_uow_factory() as uow:
|
|
385
|
+
require_capability(uow, filters=["group", "rank"], order_by=["id"])
|
|
386
|
+
page = await uow.repository(CONTRACT_RESOURCE).list(
|
|
387
|
+
ListQuery(filters={"group": "a", "rank": 2}, order_by=["id"], limit=50)
|
|
388
|
+
)
|
|
389
|
+
assert [r.id for r in page.items] == expected and page.total == len(expected)
|
|
390
|
+
|
|
391
|
+
async def test_ordering_by_several_fields(
|
|
392
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
393
|
+
) -> None:
|
|
394
|
+
expected = [
|
|
395
|
+
r["id"] for r in sorted(CONTRACT_ROWS, key=lambda r: (r["group"], -r["rank"], r["id"]))
|
|
396
|
+
]
|
|
397
|
+
async with contract_uow_factory() as uow:
|
|
398
|
+
require_capability(uow, order_by=["group", "-rank", "id"])
|
|
399
|
+
page = await uow.repository(CONTRACT_RESOURCE).list(
|
|
400
|
+
ListQuery(order_by=["group", "-rank", "id"], limit=50)
|
|
401
|
+
)
|
|
402
|
+
assert [r.id for r in page.items] == expected
|
|
403
|
+
|
|
404
|
+
async def test_paging_walks_every_record_once(
|
|
405
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
406
|
+
) -> None:
|
|
407
|
+
walked, skipped = 0, []
|
|
408
|
+
for order in ([], ["rank"], ["group"], ["-rank"], ["group", "-rank"]):
|
|
409
|
+
async with contract_uow_factory() as uow:
|
|
410
|
+
missing = missing_capabilities(uow, order_by=order, offset=39)
|
|
411
|
+
if missing:
|
|
412
|
+
skipped += missing
|
|
413
|
+
continue
|
|
414
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
415
|
+
seen: list[Any] = []
|
|
416
|
+
for offset in range(0, 40, 7):
|
|
417
|
+
page = await repo.list(ListQuery(order_by=order, limit=7, offset=offset))
|
|
418
|
+
assert page.total == 40, order
|
|
419
|
+
seen += [r.id for r in page.items]
|
|
420
|
+
walked += 1
|
|
421
|
+
assert sorted(seen) == list(range(1, 41)), f"order {order}: {len(set(seen))} of 40"
|
|
422
|
+
if not walked:
|
|
423
|
+
pytest.skip("the adapter declares " + ", ".join(dict.fromkeys(skipped)))
|
|
424
|
+
|
|
425
|
+
async def test_icontains_ignores_case(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
426
|
+
from resource_engine.errors import ConditionNotSupported
|
|
427
|
+
|
|
428
|
+
expected = sorted(r["id"] for r in CONTRACT_ROWS if "n0" in r["name"].lower())
|
|
429
|
+
async with contract_uow_factory() as uow:
|
|
430
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
431
|
+
for word in ("N0", "n0"):
|
|
432
|
+
condition = {"icontains": [{"attr": "resource.name"}, word]}
|
|
433
|
+
try:
|
|
434
|
+
page = await repo.list(ListQuery(condition=condition, limit=50))
|
|
435
|
+
except ConditionNotSupported as exc:
|
|
436
|
+
pytest.skip(f"the adapter refuses icontains: {exc}")
|
|
437
|
+
assert sorted(r.id for r in page.items) == expected and page.total == 9
|
|
438
|
+
none = {"icontains": [{"attr": "resource.name"}, "%"]} # not a wildcard
|
|
439
|
+
assert (await repo.list(ListQuery(condition=none))).total == 0
|
|
440
|
+
|
|
441
|
+
async def test_pages_past_the_end_are_empty(
|
|
442
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
443
|
+
) -> None:
|
|
444
|
+
async with contract_uow_factory() as uow:
|
|
445
|
+
require_capability(uow, offset=100)
|
|
446
|
+
page = await uow.repository(CONTRACT_RESOURCE).list(ListQuery(offset=100, limit=5))
|
|
447
|
+
assert page.items == [] and page.total == 40
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
class OutboxContract:
|
|
451
|
+
"""Contract of a transactional outbox: events added in a unit of work are kept, read in order
|
|
452
|
+
and marked published."""
|
|
453
|
+
|
|
454
|
+
@pytest.fixture
|
|
455
|
+
def contract_uow_factory(self) -> Callable[[], Any]:
|
|
456
|
+
"""Override: a factory of units of work with ``outbox()``."""
|
|
457
|
+
raise NotImplementedError("Provide a unit of work factory whose units have outbox()")
|
|
458
|
+
|
|
459
|
+
async def _pending(self, factory: Callable[[], Any], limit: int = 100) -> list[Any]:
|
|
460
|
+
async with factory() as uow:
|
|
461
|
+
pending: list[Any] = await uow.outbox().pending(limit)
|
|
462
|
+
return pending
|
|
463
|
+
|
|
464
|
+
async def test_unit_of_work_supports_outbox(
|
|
465
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
466
|
+
) -> None:
|
|
467
|
+
async with contract_uow_factory() as uow:
|
|
468
|
+
assert isinstance(uow, SupportsOutbox)
|
|
469
|
+
|
|
470
|
+
async def test_committed_messages_are_pending_in_order(
|
|
471
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
472
|
+
) -> None:
|
|
473
|
+
envelopes = [contract_envelope(n) for n in range(5)]
|
|
474
|
+
async with contract_uow_factory() as uow:
|
|
475
|
+
await uow.outbox().add(envelopes[:3])
|
|
476
|
+
await uow.outbox().add(envelopes[3:])
|
|
477
|
+
await uow.commit()
|
|
478
|
+
pending = await self._pending(contract_uow_factory)
|
|
479
|
+
assert [r.envelope.id for r in pending] == [e.id for e in envelopes]
|
|
480
|
+
assert pending[0].envelope == envelopes[0]
|
|
481
|
+
assert [r.envelope.id for r in await self._pending(contract_uow_factory, 2)] == [
|
|
482
|
+
e.id for e in envelopes[:2]
|
|
483
|
+
]
|
|
484
|
+
|
|
485
|
+
async def test_rolled_back_messages_are_discarded(
|
|
486
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
487
|
+
) -> None:
|
|
488
|
+
async with contract_uow_factory() as uow:
|
|
489
|
+
await uow.outbox().add([contract_envelope(1)])
|
|
490
|
+
assert await self._pending(contract_uow_factory) == []
|
|
491
|
+
|
|
492
|
+
async def test_mark_published_and_failed(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
493
|
+
a, b = contract_envelope(1), contract_envelope(2)
|
|
494
|
+
async with contract_uow_factory() as uow:
|
|
495
|
+
await uow.outbox().add([a, b])
|
|
496
|
+
await uow.commit()
|
|
497
|
+
async with contract_uow_factory() as uow:
|
|
498
|
+
await uow.outbox().mark_published([a.id])
|
|
499
|
+
await uow.outbox().mark_failed([b.id], "broker down")
|
|
500
|
+
await uow.commit()
|
|
501
|
+
(record,) = await self._pending(contract_uow_factory)
|
|
502
|
+
assert record.envelope.id == b.id
|
|
503
|
+
assert record.attempts == 1 and record.last_error == "broker down"
|
|
504
|
+
|
|
505
|
+
async def test_purge_published_keeps_pending_and_recent(
|
|
506
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
507
|
+
) -> None:
|
|
508
|
+
envelopes = [contract_envelope(n) for n in range(4)]
|
|
509
|
+
async with contract_uow_factory() as uow:
|
|
510
|
+
await uow.outbox().add(envelopes)
|
|
511
|
+
await uow.commit()
|
|
512
|
+
async with contract_uow_factory() as uow:
|
|
513
|
+
await uow.outbox().mark_published([e.id for e in envelopes[:3]])
|
|
514
|
+
await uow.commit()
|
|
515
|
+
past = datetime.now(UTC) - timedelta(minutes=5)
|
|
516
|
+
future = datetime.now(UTC) + timedelta(minutes=5)
|
|
517
|
+
async with contract_uow_factory() as uow:
|
|
518
|
+
assert await uow.outbox().purge_published(past, 100) == 0
|
|
519
|
+
assert await uow.outbox().purge_published(future, 2) == 2
|
|
520
|
+
assert await uow.outbox().purge_published(future, 100) == 1
|
|
521
|
+
await uow.commit()
|
|
522
|
+
(record,) = await self._pending(contract_uow_factory)
|
|
523
|
+
assert record.envelope.id == envelopes[3].id
|
|
524
|
+
|
|
525
|
+
async def test_inspect_and_requeue(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
526
|
+
from resource_engine.ports.messaging import InspectableOutbox
|
|
527
|
+
|
|
528
|
+
a, b = contract_envelope(1), contract_envelope(2)
|
|
529
|
+
async with contract_uow_factory() as uow:
|
|
530
|
+
if not isinstance(uow.outbox(), InspectableOutbox):
|
|
531
|
+
pytest.skip("this outbox can't be inspected (optional)")
|
|
532
|
+
await uow.outbox().add([a, b])
|
|
533
|
+
await uow.commit()
|
|
534
|
+
async with contract_uow_factory() as uow:
|
|
535
|
+
await uow.outbox().mark_published([a.id])
|
|
536
|
+
await uow.outbox().mark_failed([b.id], "broker down")
|
|
537
|
+
await uow.commit()
|
|
538
|
+
async with contract_uow_factory() as uow:
|
|
539
|
+
outbox = uow.outbox()
|
|
540
|
+
[waiting] = await outbox.unpublished(10)
|
|
541
|
+
assert waiting.envelope.id == b.id and waiting.last_error == "broker down"
|
|
542
|
+
sent = await outbox.get(a.id)
|
|
543
|
+
assert sent is not None and sent.published and sent.published_at is not None
|
|
544
|
+
assert await outbox.get("missing") is None
|
|
545
|
+
assert await outbox.requeue([a.id, b.id, "missing"]) == 2
|
|
546
|
+
await uow.commit()
|
|
547
|
+
records = await self._pending(contract_uow_factory)
|
|
548
|
+
assert {r.envelope.id for r in records} == {a.id, b.id}
|
|
549
|
+
assert all(r.attempts == 0 and r.last_error is None for r in records)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
type Receive = Callable[[int], Awaitable[list[EventEnvelope]]]
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
class MessagePublisherContract:
|
|
556
|
+
"""Round-trip through a real or emulated broker.
|
|
557
|
+
|
|
558
|
+
Fixtures:
|
|
559
|
+
message_publisher: the ``MessagePublisher`` under test.
|
|
560
|
+
receive: ``async (expected_count) -> list[EventEnvelope]`` reading back from
|
|
561
|
+
the destination (e.g. the queue subscribed to a topic). It should wait
|
|
562
|
+
until ``expected_count`` messages arrive or a timeout elapses.
|
|
563
|
+
"""
|
|
564
|
+
|
|
565
|
+
@pytest.fixture
|
|
566
|
+
def message_publisher(self) -> Any:
|
|
567
|
+
"""Override: the publisher under test."""
|
|
568
|
+
raise NotImplementedError
|
|
569
|
+
|
|
570
|
+
@pytest.fixture
|
|
571
|
+
def receive(self) -> Receive:
|
|
572
|
+
"""Override: reads up to ``n`` envelopes back from the broker."""
|
|
573
|
+
raise NotImplementedError
|
|
574
|
+
|
|
575
|
+
async def test_round_trip_preserves_envelope(
|
|
576
|
+
self, message_publisher: Any, receive: Any
|
|
577
|
+
) -> None:
|
|
578
|
+
sent = contract_envelope(7)
|
|
579
|
+
await message_publisher.publish([sent])
|
|
580
|
+
(got,) = await receive(1)
|
|
581
|
+
assert got == sent
|
|
582
|
+
|
|
583
|
+
async def test_batches_larger_than_broker_limits(
|
|
584
|
+
self, message_publisher: Any, receive: Any
|
|
585
|
+
) -> None:
|
|
586
|
+
sent = [contract_envelope(n) for n in range(25)]
|
|
587
|
+
await message_publisher.publish(sent)
|
|
588
|
+
got = await receive(25)
|
|
589
|
+
assert sorted(e.id for e in got) == sorted(e.id for e in sent)
|
|
590
|
+
|
|
591
|
+
async def test_empty_publish_is_a_no_op(self, message_publisher: Any, receive: Any) -> None:
|
|
592
|
+
await message_publisher.publish([])
|
|
593
|
+
await asyncio.sleep(0)
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
class InboxContract:
|
|
597
|
+
"""Contract of an inbox: which message ids a consumer already processed, written in its unit
|
|
598
|
+
of work."""
|
|
599
|
+
|
|
600
|
+
@pytest.fixture
|
|
601
|
+
def contract_uow_factory(self) -> Callable[[], Any]:
|
|
602
|
+
"""Override: a factory of units of work with ``inbox()``."""
|
|
603
|
+
raise NotImplementedError("Provide a unit of work factory whose units have inbox()")
|
|
604
|
+
|
|
605
|
+
async def _processed(
|
|
606
|
+
self, factory: Callable[[], Any], consumer: str, ids: list[str]
|
|
607
|
+
) -> set[str]:
|
|
608
|
+
async with factory() as uow:
|
|
609
|
+
processed: set[str] = await uow.inbox().processed(consumer, ids)
|
|
610
|
+
return processed
|
|
611
|
+
|
|
612
|
+
async def test_unit_of_work_supports_inbox(
|
|
613
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
614
|
+
) -> None:
|
|
615
|
+
async with contract_uow_factory() as uow:
|
|
616
|
+
assert isinstance(uow, SupportsInbox)
|
|
617
|
+
|
|
618
|
+
async def test_marks_are_per_consumer_and_committed(
|
|
619
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
620
|
+
) -> None:
|
|
621
|
+
async with contract_uow_factory() as uow:
|
|
622
|
+
await uow.inbox().mark_processed("billing", ["m1", "m2"])
|
|
623
|
+
await uow.commit()
|
|
624
|
+
assert await self._processed(contract_uow_factory, "billing", ["m1", "m3"]) == {"m1"}
|
|
625
|
+
assert await self._processed(contract_uow_factory, "audit", ["m1"]) == set()
|
|
626
|
+
|
|
627
|
+
async def test_rolled_back_marks_are_discarded(
|
|
628
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
629
|
+
) -> None:
|
|
630
|
+
async with contract_uow_factory() as uow:
|
|
631
|
+
await uow.inbox().mark_processed("billing", ["m9"])
|
|
632
|
+
assert await self._processed(contract_uow_factory, "billing", ["m9"]) == set()
|
|
633
|
+
|
|
634
|
+
async def test_purge_deletes_old_marks_in_batches(
|
|
635
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
636
|
+
) -> None:
|
|
637
|
+
async with contract_uow_factory() as uow:
|
|
638
|
+
await uow.inbox().mark_processed("billing", ["p1", "p2"])
|
|
639
|
+
await uow.inbox().mark_processed("audit", ["p1"])
|
|
640
|
+
await uow.commit()
|
|
641
|
+
past = datetime.now(UTC) - timedelta(minutes=5)
|
|
642
|
+
future = datetime.now(UTC) + timedelta(minutes=5)
|
|
643
|
+
async with contract_uow_factory() as uow:
|
|
644
|
+
assert await uow.inbox().purge(past, 100) == 0
|
|
645
|
+
assert await uow.inbox().purge(future, 2) == 2
|
|
646
|
+
await uow.commit()
|
|
647
|
+
remaining = await self._processed(contract_uow_factory, "billing", ["p1", "p2"])
|
|
648
|
+
remaining |= {
|
|
649
|
+
f"audit:{i}" for i in await self._processed(contract_uow_factory, "audit", ["p1"])
|
|
650
|
+
}
|
|
651
|
+
assert len(remaining) == 1
|
|
652
|
+
async with contract_uow_factory() as uow:
|
|
653
|
+
assert await uow.inbox().purge(future, 100) == 1
|
|
654
|
+
await uow.commit()
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
type Send = Callable[[list[EventEnvelope]], Awaitable[None]]
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
async def drain(source: Any, expected: int, *, timeout: float = 10.0) -> list[Any]:
|
|
661
|
+
"""Receive until ``expected`` messages arrived (or ``timeout``); for broker tests."""
|
|
662
|
+
got: list[Any] = []
|
|
663
|
+
loop = asyncio.get_running_loop()
|
|
664
|
+
deadline = loop.time() + timeout
|
|
665
|
+
while len(got) < expected and loop.time() < deadline:
|
|
666
|
+
got += await source.receive(min(10, expected - len(got)), 1.0)
|
|
667
|
+
return got
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
class MessageSourceContract:
|
|
671
|
+
"""Behaviour of a ``MessageSource`` against a real or emulated broker.
|
|
672
|
+
|
|
673
|
+
Fixtures:
|
|
674
|
+
message_source: the source under test, reading from an empty destination.
|
|
675
|
+
send: ``async (envelopes) -> None`` putting envelopes on that destination
|
|
676
|
+
(usually the matching publisher).
|
|
677
|
+
"""
|
|
678
|
+
|
|
679
|
+
@pytest.fixture
|
|
680
|
+
def message_source(self) -> Any:
|
|
681
|
+
"""Override: the source under test."""
|
|
682
|
+
raise NotImplementedError
|
|
683
|
+
|
|
684
|
+
@pytest.fixture
|
|
685
|
+
def send(self) -> Send:
|
|
686
|
+
"""Override: puts envelopes on the queue the source reads."""
|
|
687
|
+
raise NotImplementedError
|
|
688
|
+
|
|
689
|
+
async def test_receive_decodes_envelopes(self, message_source: Any, send: Any) -> None:
|
|
690
|
+
sent = [contract_envelope(n) for n in range(3)]
|
|
691
|
+
await send(sent)
|
|
692
|
+
got = await drain(message_source, 3)
|
|
693
|
+
assert sorted((m.envelope for m in got), key=lambda e: e.id) == sorted(
|
|
694
|
+
sent, key=lambda e: e.id
|
|
695
|
+
)
|
|
696
|
+
assert all(m.delivery_count in (1, None) for m in got)
|
|
697
|
+
await message_source.ack(got)
|
|
698
|
+
|
|
699
|
+
async def test_acked_messages_are_not_redelivered(self, message_source: Any, send: Any) -> None:
|
|
700
|
+
await send([contract_envelope(1)])
|
|
701
|
+
got = await drain(message_source, 1)
|
|
702
|
+
await message_source.ack(got)
|
|
703
|
+
assert await message_source.receive(10, 1.0) == []
|
|
704
|
+
|
|
705
|
+
async def test_retried_messages_come_back(self, message_source: Any, send: Any) -> None:
|
|
706
|
+
sent = contract_envelope(2)
|
|
707
|
+
await send([sent])
|
|
708
|
+
(first,) = await drain(message_source, 1)
|
|
709
|
+
await message_source.retry([first], 0)
|
|
710
|
+
(again,) = await drain(message_source, 1)
|
|
711
|
+
assert again.envelope == sent
|
|
712
|
+
if first.delivery_count is not None and again.delivery_count is not None:
|
|
713
|
+
assert again.delivery_count == first.delivery_count + 1
|
|
714
|
+
await message_source.ack([again])
|
|
715
|
+
|
|
716
|
+
async def test_empty_receive_returns_within_wait(self, message_source: Any) -> None:
|
|
717
|
+
loop = asyncio.get_running_loop()
|
|
718
|
+
start = loop.time()
|
|
719
|
+
assert await message_source.receive(10, 1.0) == []
|
|
720
|
+
assert loop.time() - start < 5
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
class BlobStoreContract:
|
|
724
|
+
"""Behaviour of a ``BlobStore`` (and ``SupportsPresignedUrls`` when provided).
|
|
725
|
+
|
|
726
|
+
Fixtures:
|
|
727
|
+
blob_store: the store under test, on an empty bucket/prefix.
|
|
728
|
+
presigned_client: ``(upload, download)`` coroutines performing the client
|
|
729
|
+
side of presigned requests (``httpx`` for real stores). Return ``None``
|
|
730
|
+
to skip the presigned tests.
|
|
731
|
+
"""
|
|
732
|
+
|
|
733
|
+
@pytest.fixture
|
|
734
|
+
def blob_store(self) -> Any:
|
|
735
|
+
"""Override: the store under test."""
|
|
736
|
+
raise NotImplementedError
|
|
737
|
+
|
|
738
|
+
@pytest.fixture
|
|
739
|
+
def presigned_client(self) -> Any:
|
|
740
|
+
"""Override for stores with presigned URLs: an HTTP client that can reach them (``None``:
|
|
741
|
+
skip those tests)."""
|
|
742
|
+
return None
|
|
743
|
+
|
|
744
|
+
async def test_put_head_open_round_trip(self, blob_store: BlobStore) -> None:
|
|
745
|
+
import hashlib
|
|
746
|
+
|
|
747
|
+
data = b"%PDF-1.7 " + bytes(range(256)) * 100
|
|
748
|
+
info = await blob_store.put("a/b/1", data, content_type="application/pdf")
|
|
749
|
+
assert info.size == len(data) and info.sha256 == hashlib.sha256(data).hexdigest()
|
|
750
|
+
head = await blob_store.head("a/b/1")
|
|
751
|
+
assert head is not None and head.size == len(data)
|
|
752
|
+
assert b"".join([c async for c in blob_store.open("a/b/1")]) == data
|
|
753
|
+
|
|
754
|
+
async def test_streamed_put(self, blob_store: BlobStore) -> None:
|
|
755
|
+
async def chunks() -> AsyncIterator[bytes]:
|
|
756
|
+
for n in range(5):
|
|
757
|
+
yield bytes([n]) * 1000
|
|
758
|
+
|
|
759
|
+
info = await blob_store.put("streamed", chunks(), content_type="application/octet-stream")
|
|
760
|
+
assert info.size == 5000
|
|
761
|
+
|
|
762
|
+
async def test_max_bytes_aborts_without_leaving_an_object(self, blob_store: BlobStore) -> None:
|
|
763
|
+
from resource_engine.errors import DocumentTooLarge
|
|
764
|
+
|
|
765
|
+
with pytest.raises(DocumentTooLarge):
|
|
766
|
+
await blob_store.put("big", b"x" * 2000, content_type="text/plain", max_bytes=1000)
|
|
767
|
+
assert await blob_store.head("big") is None
|
|
768
|
+
|
|
769
|
+
async def test_missing_and_delete(self, blob_store: BlobStore) -> None:
|
|
770
|
+
from resource_engine.errors import BlobNotFound
|
|
771
|
+
|
|
772
|
+
assert await blob_store.head("missing") is None
|
|
773
|
+
with pytest.raises(BlobNotFound):
|
|
774
|
+
async for _ in blob_store.open("missing"):
|
|
775
|
+
pass
|
|
776
|
+
await blob_store.put("gone", b"1", content_type="text/plain")
|
|
777
|
+
await blob_store.delete(["gone", "never-existed"])
|
|
778
|
+
assert await blob_store.head("gone") is None
|
|
779
|
+
|
|
780
|
+
async def test_list_by_prefix(self, blob_store: BlobStore) -> None:
|
|
781
|
+
for key in ("p/1", "p/2", "q/1"):
|
|
782
|
+
await blob_store.put(key, b"x", content_type="text/plain")
|
|
783
|
+
assert sorted([i.key async for i in blob_store.list("p/")]) == ["p/1", "p/2"]
|
|
784
|
+
|
|
785
|
+
async def test_presigned_upload_and_download(
|
|
786
|
+
self, blob_store: BlobStore, presigned_client: Any
|
|
787
|
+
) -> None:
|
|
788
|
+
from datetime import timedelta
|
|
789
|
+
|
|
790
|
+
from resource_engine.ports.storage import SupportsPresignedUrls
|
|
791
|
+
|
|
792
|
+
if presigned_client is None or not isinstance(blob_store, SupportsPresignedUrls):
|
|
793
|
+
pytest.skip("store has no presigned URLs")
|
|
794
|
+
upload, download = presigned_client
|
|
795
|
+
put = await blob_store.presign_put(
|
|
796
|
+
"direct/1", content_type="text/plain", expires=timedelta(minutes=5)
|
|
797
|
+
)
|
|
798
|
+
await upload(put, b"uploaded directly")
|
|
799
|
+
head = await blob_store.head("direct/1")
|
|
800
|
+
assert head is not None and head.size == len(b"uploaded directly")
|
|
801
|
+
get = await blob_store.presign_get(
|
|
802
|
+
"direct/1", expires=timedelta(minutes=5), download_name="nota.txt"
|
|
803
|
+
)
|
|
804
|
+
assert await download(get) == b"uploaded directly"
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
class ConditionContract(RepositoryContract):
|
|
808
|
+
"""Row filters (``ListQuery.condition``) for repositories with
|
|
809
|
+
``supports_conditions = True``."""
|
|
810
|
+
|
|
811
|
+
async def test_supports_conditions(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
812
|
+
async with contract_uow_factory() as uow:
|
|
813
|
+
assert getattr(uow.repository(CONTRACT_RESOURCE), "supports_conditions", False)
|
|
814
|
+
|
|
815
|
+
async def test_condition_filters_and_counts(
|
|
816
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
817
|
+
) -> None:
|
|
818
|
+
await self._seed(contract_uow_factory)
|
|
819
|
+
cases = [
|
|
820
|
+
({"eq": [{"attr": "resource.group"}, "a"]}, ["b", "c"]),
|
|
821
|
+
({"lt": [{"attr": "resource.rank"}, 3]}, ["a", "b"]),
|
|
822
|
+
({"in": [{"attr": "resource.name"}, ["a", "c"]]}, ["a", "c"]),
|
|
823
|
+
({"nin": [{"attr": "resource.name"}, ["a"]]}, ["b", "c"]),
|
|
824
|
+
(
|
|
825
|
+
{
|
|
826
|
+
"or": [
|
|
827
|
+
{"eq": [{"attr": "resource.group"}, "b"]},
|
|
828
|
+
{
|
|
829
|
+
"and": [
|
|
830
|
+
{"ge": [{"attr": "resource.rank"}, 3]},
|
|
831
|
+
{"not": {"eq": [{"attr": "resource.name"}, "x"]}},
|
|
832
|
+
]
|
|
833
|
+
},
|
|
834
|
+
]
|
|
835
|
+
},
|
|
836
|
+
["a", "c"],
|
|
837
|
+
),
|
|
838
|
+
(False, []),
|
|
839
|
+
]
|
|
840
|
+
async with contract_uow_factory() as uow:
|
|
841
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
842
|
+
for condition, names in cases:
|
|
843
|
+
page = await repo.list(ListQuery(order_by=["name"], condition=condition))
|
|
844
|
+
assert [i.name for i in page.items] == names, condition
|
|
845
|
+
assert page.total == len(names)
|
|
846
|
+
page = await repo.list(
|
|
847
|
+
ListQuery(filters={"group": "a"}, condition={"gt": [{"attr": "resource.rank"}, 2]})
|
|
848
|
+
)
|
|
849
|
+
assert [i.name for i in page.items] == ["c"]
|
|
850
|
+
|
|
851
|
+
async def test_icontains_ignores_case_and_wildcards(
|
|
852
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
853
|
+
) -> None:
|
|
854
|
+
"""``icontains`` (searches): the text, case ignored; ``%``, ``_`` and
|
|
855
|
+
backslashes are themselves, never wildcards. A store that can't do it
|
|
856
|
+
refuses with ``ConditionNotSupported``, and the case is skipped."""
|
|
857
|
+
from resource_engine.errors import ConditionNotSupported
|
|
858
|
+
|
|
859
|
+
async with contract_uow_factory() as uow:
|
|
860
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
861
|
+
for name in ("Mariana", "ANA puig", "50% off", "a_b", "x\\y", "plain"):
|
|
862
|
+
await repo.add(ContractItem(name, 1))
|
|
863
|
+
await uow.commit()
|
|
864
|
+
|
|
865
|
+
def text(word: str) -> Any:
|
|
866
|
+
return {"icontains": [{"attr": "resource.name"}, word]}
|
|
867
|
+
|
|
868
|
+
cases = [
|
|
869
|
+
(text("ana"), ["ANA puig", "Mariana"]),
|
|
870
|
+
(text("%"), ["50% off"]),
|
|
871
|
+
(text("_"), ["a_b"]),
|
|
872
|
+
(text("\\"), ["x\\y"]),
|
|
873
|
+
(text("zz"), []),
|
|
874
|
+
({"and": [text("an"), text("PUIG")]}, ["ANA puig"]),
|
|
875
|
+
]
|
|
876
|
+
async with contract_uow_factory() as uow:
|
|
877
|
+
repo = uow.repository(CONTRACT_RESOURCE)
|
|
878
|
+
for condition, names in cases:
|
|
879
|
+
try:
|
|
880
|
+
page = await repo.list(ListQuery(order_by=["name"], condition=condition))
|
|
881
|
+
except ConditionNotSupported as exc:
|
|
882
|
+
pytest.skip(f"the adapter refuses icontains: {exc}")
|
|
883
|
+
assert sorted(i.name for i in page.items) == sorted(names), condition
|
|
884
|
+
assert page.total == len(names)
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
CONTRACT_VERSIONED = "contract_versioned"
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
@dataclass
|
|
891
|
+
class ContractVersioned:
|
|
892
|
+
"""Entity of ``VersionContract``: a resource with ``concurrency = Versioned("version")``."""
|
|
893
|
+
|
|
894
|
+
name: str
|
|
895
|
+
version: int = 1
|
|
896
|
+
id: int | None = None
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def contract_registry() -> Any:
|
|
900
|
+
"""A registry with the contract resources (``CONTRACT_RESOURCE`` and
|
|
901
|
+
``CONTRACT_VERSIONED``), for adapters that read models from it."""
|
|
902
|
+
from pydantic import BaseModel
|
|
903
|
+
|
|
904
|
+
from resource_engine.application.registry import ResourceRegistry
|
|
905
|
+
from resource_engine.application.resource import Resource
|
|
906
|
+
|
|
907
|
+
class _In(BaseModel):
|
|
908
|
+
name: str
|
|
909
|
+
|
|
910
|
+
class ItemResource(Resource):
|
|
911
|
+
name = CONTRACT_RESOURCE
|
|
912
|
+
model = ContractItem
|
|
913
|
+
schemas = {"create": _In}
|
|
914
|
+
|
|
915
|
+
class VersionedResource(Resource):
|
|
916
|
+
name = CONTRACT_VERSIONED
|
|
917
|
+
model = ContractVersioned
|
|
918
|
+
schemas = {"create": _In}
|
|
919
|
+
concurrency = Versioned("version")
|
|
920
|
+
|
|
921
|
+
registry = ResourceRegistry()
|
|
922
|
+
registry.register(ItemResource)
|
|
923
|
+
registry.register(VersionedResource)
|
|
924
|
+
return registry
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
class VersionContract:
|
|
928
|
+
"""Compare-and-set writes (``supports_versions = True``): of two units of
|
|
929
|
+
work updating the same version, one commits and the other fails with
|
|
930
|
+
``VersionConflict``, at the write or at commit. Serve ``CONTRACT_VERSIONED``."""
|
|
931
|
+
|
|
932
|
+
@pytest.fixture
|
|
933
|
+
def contract_uow_factory(self) -> Callable[[], Any]:
|
|
934
|
+
"""Override: a factory of units of work serving ``CONTRACT_VERSIONED``."""
|
|
935
|
+
raise NotImplementedError("Provide a unit of work factory serving CONTRACT_VERSIONED")
|
|
936
|
+
|
|
937
|
+
async def _seed(self, factory: Callable[[], Any]) -> ContractVersioned:
|
|
938
|
+
async with factory() as uow:
|
|
939
|
+
item: ContractVersioned = await uow.repository(CONTRACT_VERSIONED).add(
|
|
940
|
+
ContractVersioned("a")
|
|
941
|
+
)
|
|
942
|
+
await uow.commit()
|
|
943
|
+
return item
|
|
944
|
+
|
|
945
|
+
async def test_racing_updates_one_wins(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
946
|
+
from resource_engine.errors import VersionConflict
|
|
947
|
+
|
|
948
|
+
item = await self._seed(contract_uow_factory)
|
|
949
|
+
async with contract_uow_factory() as first, contract_uow_factory() as second:
|
|
950
|
+
mine = await first.repository(CONTRACT_VERSIONED).get(item.id)
|
|
951
|
+
theirs = await second.repository(CONTRACT_VERSIONED).get(item.id)
|
|
952
|
+
mine.name, theirs.name = "mine", "theirs"
|
|
953
|
+
await first.repository(CONTRACT_VERSIONED).update(mine, expected_version=1)
|
|
954
|
+
await first.commit()
|
|
955
|
+
with pytest.raises(VersionConflict):
|
|
956
|
+
await second.repository(CONTRACT_VERSIONED).update(theirs, expected_version=1)
|
|
957
|
+
await second.commit()
|
|
958
|
+
async with contract_uow_factory() as uow:
|
|
959
|
+
stored = await uow.repository(CONTRACT_VERSIONED).get(item.id)
|
|
960
|
+
assert stored.name == "mine" and stored.version == 2
|
|
961
|
+
|
|
962
|
+
async def test_stale_delete_fails(self, contract_uow_factory: Callable[[], Any]) -> None:
|
|
963
|
+
from resource_engine.errors import VersionConflict
|
|
964
|
+
|
|
965
|
+
item = await self._seed(contract_uow_factory)
|
|
966
|
+
async with contract_uow_factory() as uow:
|
|
967
|
+
loaded = await uow.repository(CONTRACT_VERSIONED).get(item.id)
|
|
968
|
+
await uow.repository(CONTRACT_VERSIONED).update(loaded, expected_version=1)
|
|
969
|
+
await uow.commit()
|
|
970
|
+
with pytest.raises(VersionConflict):
|
|
971
|
+
async with contract_uow_factory() as uow:
|
|
972
|
+
await uow.repository(CONTRACT_VERSIONED).delete(loaded, expected_version=1)
|
|
973
|
+
await uow.commit()
|
|
974
|
+
async with contract_uow_factory() as uow:
|
|
975
|
+
assert await uow.repository(CONTRACT_VERSIONED).get(item.id) is not None
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
# ------------------------------------------------------------- authorizers
|
|
979
|
+
|
|
980
|
+
CONTRACT_DOCS = "contract_docs"
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
@dataclass
|
|
984
|
+
class ContractDoc:
|
|
985
|
+
"""Entity of the authorizer contract (in memory: no mapping needed)."""
|
|
986
|
+
|
|
987
|
+
title: str
|
|
988
|
+
owner: str
|
|
989
|
+
secret: str | None = None
|
|
990
|
+
id: int | None = None
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def contract_principals() -> dict[str, Any]:
|
|
994
|
+
"""``ann`` (roles writer, auditor), ``bob`` (writer) and ``eve`` (none)."""
|
|
995
|
+
from resource_engine.ports.identity import Principal
|
|
996
|
+
|
|
997
|
+
return {
|
|
998
|
+
name: Principal(subject=name, issuer="idp", roles=frozenset(roles))
|
|
999
|
+
for name, roles in {
|
|
1000
|
+
"ann": {"writer", "auditor"},
|
|
1001
|
+
"bob": {"writer"},
|
|
1002
|
+
"eve": set(),
|
|
1003
|
+
}.items()
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
class AuthorizerContract:
|
|
1008
|
+
"""What a ``PolicyEngine`` must decide, through ``EngineAuthorizer``.
|
|
1009
|
+
|
|
1010
|
+
Provide ``contract_engine``: an engine configured with these rules for the
|
|
1011
|
+
``contract_docs`` resource (type ``ContractDoc``, id field ``id``)::
|
|
1012
|
+
|
|
1013
|
+
contract_docs:get, :list, :update when resource.owner == subject.id
|
|
1014
|
+
contract_docs:create for role "writer"
|
|
1015
|
+
contract_docs:read:secret for role "auditor" (secret is restricted in code)
|
|
1016
|
+
anything else denied; anonymous callers denied
|
|
1017
|
+
|
|
1018
|
+
Engines that need relationship data (OpenFGA) override
|
|
1019
|
+
``contract_record_created`` to write it.
|
|
1020
|
+
"""
|
|
1021
|
+
|
|
1022
|
+
@pytest.fixture
|
|
1023
|
+
def contract_engine(self) -> Any:
|
|
1024
|
+
"""Override: the ``PolicyEngine`` under test, implementing the contract rules."""
|
|
1025
|
+
raise NotImplementedError("Provide a PolicyEngine implementing the contract rules")
|
|
1026
|
+
|
|
1027
|
+
async def contract_record_created(self, engine: Any, doc: ContractDoc) -> None:
|
|
1028
|
+
"""Called after each seeded record (e.g. write relationship tuples)."""
|
|
1029
|
+
|
|
1030
|
+
@pytest.fixture
|
|
1031
|
+
async def contract_manager(self, contract_engine: Any) -> Any:
|
|
1032
|
+
"""A manager over the contract resources, authorized through ``contract_engine``."""
|
|
1033
|
+
from pydantic import BaseModel, ConfigDict
|
|
1034
|
+
|
|
1035
|
+
from resource_engine.application.manager import ResourceManager
|
|
1036
|
+
from resource_engine.application.registry import ResourceRegistry
|
|
1037
|
+
from resource_engine.application.resource import Resource
|
|
1038
|
+
from resource_engine.authz.external import EngineAuthorizer
|
|
1039
|
+
from resource_engine.testing.memory import InMemoryStore
|
|
1040
|
+
|
|
1041
|
+
class DocIn(BaseModel):
|
|
1042
|
+
title: str
|
|
1043
|
+
owner: str
|
|
1044
|
+
secret: str | None = None
|
|
1045
|
+
|
|
1046
|
+
class DocPatch(BaseModel):
|
|
1047
|
+
title: str | None = None
|
|
1048
|
+
|
|
1049
|
+
class DocOut(DocIn):
|
|
1050
|
+
model_config = ConfigDict(from_attributes=True)
|
|
1051
|
+
id: int
|
|
1052
|
+
|
|
1053
|
+
class ContractDocResource(Resource):
|
|
1054
|
+
name = CONTRACT_DOCS
|
|
1055
|
+
model = ContractDoc
|
|
1056
|
+
schemas = {"create": DocIn, "update": DocPatch, "read": DocOut}
|
|
1057
|
+
operations = ["list", "get", "create", "update"]
|
|
1058
|
+
access = Access(restricted_fields=["secret"])
|
|
1059
|
+
|
|
1060
|
+
registry = ResourceRegistry()
|
|
1061
|
+
registry.register(ContractDocResource)
|
|
1062
|
+
store = InMemoryStore.from_registry(registry)
|
|
1063
|
+
return ResourceManager(
|
|
1064
|
+
registry, store.unit_of_work, authorizer=EngineAuthorizer(contract_engine)
|
|
1065
|
+
)
|
|
1066
|
+
|
|
1067
|
+
async def _seed(self, manager: Any, engine: Any) -> dict[str, Any]:
|
|
1068
|
+
from resource_engine.authz.base import system_principal
|
|
1069
|
+
|
|
1070
|
+
people = contract_principals()
|
|
1071
|
+
docs = {}
|
|
1072
|
+
for name in ("ann", "bob"):
|
|
1073
|
+
doc = await manager.create(
|
|
1074
|
+
CONTRACT_DOCS,
|
|
1075
|
+
{"title": f"{name}'s", "owner": people[name].id, "secret": "s"},
|
|
1076
|
+
actor=system_principal(),
|
|
1077
|
+
)
|
|
1078
|
+
await self.contract_record_created(
|
|
1079
|
+
engine, ContractDoc(doc.title, doc.owner, doc.secret, doc.id)
|
|
1080
|
+
)
|
|
1081
|
+
docs[name] = doc
|
|
1082
|
+
return docs
|
|
1083
|
+
|
|
1084
|
+
async def test_owners_get_their_records_only(
|
|
1085
|
+
self, contract_manager: Any, contract_engine: Any
|
|
1086
|
+
) -> None:
|
|
1087
|
+
from resource_engine.errors import EntityNotFound
|
|
1088
|
+
|
|
1089
|
+
docs = await self._seed(contract_manager, contract_engine)
|
|
1090
|
+
people = contract_principals()
|
|
1091
|
+
got = await contract_manager.get(CONTRACT_DOCS, docs["bob"].id, actor=people["bob"])
|
|
1092
|
+
assert got.title == "bob's"
|
|
1093
|
+
with pytest.raises(EntityNotFound):
|
|
1094
|
+
await contract_manager.get(CONTRACT_DOCS, docs["ann"].id, actor=people["bob"])
|
|
1095
|
+
authz = contract_manager.authorizer
|
|
1096
|
+
record = ContractDoc("bob's", people["bob"].id, "s", docs["bob"].id)
|
|
1097
|
+
assert (
|
|
1098
|
+
await authz.check(people["bob"], f"{CONTRACT_DOCS}:update", resource=record)
|
|
1099
|
+
).allowed
|
|
1100
|
+
assert (
|
|
1101
|
+
await authz.check(people["ann"], f"{CONTRACT_DOCS}:update", resource=record)
|
|
1102
|
+
).allowed is False
|
|
1103
|
+
|
|
1104
|
+
async def test_list_is_filtered_like_single_checks(
|
|
1105
|
+
self, contract_manager: Any, contract_engine: Any
|
|
1106
|
+
) -> None:
|
|
1107
|
+
await self._seed(contract_manager, contract_engine)
|
|
1108
|
+
people = contract_principals()
|
|
1109
|
+
for name in ("ann", "bob"):
|
|
1110
|
+
page = await contract_manager.list(CONTRACT_DOCS, actor=people[name])
|
|
1111
|
+
assert [d.owner for d in page.items] == [people[name].id]
|
|
1112
|
+
assert page.total == 1
|
|
1113
|
+
assert (await contract_manager.list(CONTRACT_DOCS, actor=people["eve"])).total == 0
|
|
1114
|
+
|
|
1115
|
+
async def test_create_needs_the_role(self, contract_manager: Any) -> None:
|
|
1116
|
+
from resource_engine.errors import PermissionDenied
|
|
1117
|
+
|
|
1118
|
+
people = contract_principals()
|
|
1119
|
+
doc = await contract_manager.create(
|
|
1120
|
+
CONTRACT_DOCS, {"title": "t", "owner": people["bob"].id}, actor=people["bob"]
|
|
1121
|
+
)
|
|
1122
|
+
assert doc.id is not None
|
|
1123
|
+
with pytest.raises(PermissionDenied):
|
|
1124
|
+
await contract_manager.create(
|
|
1125
|
+
CONTRACT_DOCS, {"title": "t", "owner": people["eve"].id}, actor=people["eve"]
|
|
1126
|
+
)
|
|
1127
|
+
|
|
1128
|
+
async def test_restricted_field_needs_the_role(
|
|
1129
|
+
self, contract_manager: Any, contract_engine: Any
|
|
1130
|
+
) -> None:
|
|
1131
|
+
docs = await self._seed(contract_manager, contract_engine)
|
|
1132
|
+
people = contract_principals()
|
|
1133
|
+
ann = await contract_manager.get(CONTRACT_DOCS, docs["ann"].id, actor=people["ann"])
|
|
1134
|
+
assert ann.secret == "s" # noqa: S105 - a test value
|
|
1135
|
+
bob = await contract_manager.get(CONTRACT_DOCS, docs["bob"].id, actor=people["bob"])
|
|
1136
|
+
from resource_engine.authz.fields import hidden_fields
|
|
1137
|
+
|
|
1138
|
+
assert hidden_fields(bob) == {"secret"}
|
|
1139
|
+
|
|
1140
|
+
async def test_anonymous_and_system_callers(
|
|
1141
|
+
self, contract_manager: Any, contract_engine: Any
|
|
1142
|
+
) -> None:
|
|
1143
|
+
from resource_engine.authz.base import system_principal
|
|
1144
|
+
from resource_engine.errors import AuthenticationFailed
|
|
1145
|
+
|
|
1146
|
+
await self._seed(contract_manager, contract_engine)
|
|
1147
|
+
# nobody signed in: "sign in" (RE-E701), whatever the policies say
|
|
1148
|
+
with pytest.raises(AuthenticationFailed):
|
|
1149
|
+
await contract_manager.create(CONTRACT_DOCS, {"title": "t", "owner": "x"})
|
|
1150
|
+
with pytest.raises(AuthenticationFailed):
|
|
1151
|
+
await contract_manager.list(CONTRACT_DOCS)
|
|
1152
|
+
everything = await contract_manager.list(CONTRACT_DOCS, actor=system_principal())
|
|
1153
|
+
assert everything.total == 2
|
|
1154
|
+
|
|
1155
|
+
|
|
1156
|
+
class LockContract:
|
|
1157
|
+
"""Behaviour of a ``LockProvider``. Fixture: ``lock_provider``."""
|
|
1158
|
+
|
|
1159
|
+
@pytest.fixture
|
|
1160
|
+
def lock_provider(self) -> Any:
|
|
1161
|
+
"""Override: the ``LockProvider`` under test."""
|
|
1162
|
+
raise NotImplementedError("Provide the LockProvider under test")
|
|
1163
|
+
|
|
1164
|
+
async def test_one_owner_at_a_time(self, lock_provider: Any) -> None:
|
|
1165
|
+
ttl = timedelta(minutes=1)
|
|
1166
|
+
assert await lock_provider.acquire("job", "a", ttl)
|
|
1167
|
+
assert not await lock_provider.acquire("job", "b", ttl)
|
|
1168
|
+
assert await lock_provider.acquire("job", "a", ttl) # renew
|
|
1169
|
+
assert await lock_provider.acquire("other", "b", ttl)
|
|
1170
|
+
|
|
1171
|
+
async def test_release_frees_only_for_the_owner(self, lock_provider: Any) -> None:
|
|
1172
|
+
ttl = timedelta(minutes=1)
|
|
1173
|
+
assert await lock_provider.acquire("job", "a", ttl)
|
|
1174
|
+
await lock_provider.release("job", "b")
|
|
1175
|
+
assert not await lock_provider.acquire("job", "b", ttl)
|
|
1176
|
+
await lock_provider.release("job", "a")
|
|
1177
|
+
assert await lock_provider.acquire("job", "b", ttl)
|
|
1178
|
+
|
|
1179
|
+
async def test_expired_lease_can_be_taken(self, lock_provider: Any) -> None:
|
|
1180
|
+
assert await lock_provider.acquire("job", "a", timedelta(milliseconds=50))
|
|
1181
|
+
await asyncio.sleep(0.1)
|
|
1182
|
+
assert await lock_provider.acquire("job", "b", timedelta(minutes=1))
|
|
1183
|
+
|
|
1184
|
+
async def test_racing_owners_one_wins(self, lock_provider: Any) -> None:
|
|
1185
|
+
ttl = timedelta(minutes=1)
|
|
1186
|
+
results = await asyncio.gather(
|
|
1187
|
+
*(lock_provider.acquire("race", f"w{i}", ttl) for i in range(5))
|
|
1188
|
+
)
|
|
1189
|
+
assert results.count(True) == 1
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
class IdempotencyContract:
|
|
1193
|
+
"""Behaviour of an ``IdempotencyStore``. Fixture: ``contract_uow_factory``
|
|
1194
|
+
(units of work with ``idempotency()``)."""
|
|
1195
|
+
|
|
1196
|
+
@pytest.fixture
|
|
1197
|
+
def contract_uow_factory(self) -> Callable[[], Any]:
|
|
1198
|
+
"""Override: a factory of units of work with ``idempotency()``."""
|
|
1199
|
+
raise NotImplementedError("Provide a unit of work factory whose units have idempotency()")
|
|
1200
|
+
|
|
1201
|
+
@staticmethod
|
|
1202
|
+
def record(key: str = "k", *, ttl: timedelta = timedelta(hours=1), fp: str = "f" * 64) -> Any:
|
|
1203
|
+
"""An idempotency record for the tests."""
|
|
1204
|
+
from resource_engine.ports.idempotency import IdempotencyRecord
|
|
1205
|
+
|
|
1206
|
+
now = datetime.now(UTC)
|
|
1207
|
+
return IdempotencyRecord(
|
|
1208
|
+
scope="user:ana", key=key, fingerprint=fp, resource="invoices", operation="create",
|
|
1209
|
+
result={"kind": "model", "data": {"id": 1, "amount": "1.50"}},
|
|
1210
|
+
created_at=now, expires_at=now + ttl,
|
|
1211
|
+
) # fmt: skip
|
|
1212
|
+
|
|
1213
|
+
async def _get(self, factory: Callable[[], Any], key: str = "k") -> Any:
|
|
1214
|
+
async with factory() as uow:
|
|
1215
|
+
return await uow.idempotency().get("user:ana", key)
|
|
1216
|
+
|
|
1217
|
+
async def test_committed_records_come_back(
|
|
1218
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
1219
|
+
) -> None:
|
|
1220
|
+
async with contract_uow_factory() as uow:
|
|
1221
|
+
await uow.idempotency().put(self.record())
|
|
1222
|
+
await uow.commit()
|
|
1223
|
+
found = await self._get(contract_uow_factory)
|
|
1224
|
+
assert found.fingerprint == "f" * 64 and found.operation == "create"
|
|
1225
|
+
assert found.result == {"kind": "model", "data": {"id": 1, "amount": "1.50"}}
|
|
1226
|
+
assert await self._get(contract_uow_factory, "other") is None
|
|
1227
|
+
|
|
1228
|
+
async def test_rolled_back_records_are_discarded(
|
|
1229
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
1230
|
+
) -> None:
|
|
1231
|
+
async with contract_uow_factory() as uow:
|
|
1232
|
+
await uow.idempotency().put(self.record())
|
|
1233
|
+
assert await self._get(contract_uow_factory) is None
|
|
1234
|
+
|
|
1235
|
+
async def test_a_second_commit_of_the_same_key_fails(
|
|
1236
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
1237
|
+
) -> None:
|
|
1238
|
+
async with contract_uow_factory() as first, contract_uow_factory() as second:
|
|
1239
|
+
await first.idempotency().put(self.record())
|
|
1240
|
+
await first.commit()
|
|
1241
|
+
with pytest.raises(Exception): # noqa: B017, PT011 - a primary key violation, per store
|
|
1242
|
+
await second.idempotency().put(self.record(fp="e" * 64))
|
|
1243
|
+
await second.commit()
|
|
1244
|
+
assert (await self._get(contract_uow_factory)).fingerprint == "f" * 64
|
|
1245
|
+
|
|
1246
|
+
async def test_an_expired_record_is_replaced(
|
|
1247
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
1248
|
+
) -> None:
|
|
1249
|
+
async with contract_uow_factory() as uow:
|
|
1250
|
+
await uow.idempotency().put(self.record(ttl=timedelta(seconds=-1)))
|
|
1251
|
+
await uow.commit()
|
|
1252
|
+
async with contract_uow_factory() as uow:
|
|
1253
|
+
await uow.idempotency().put(self.record(fp="e" * 64))
|
|
1254
|
+
await uow.commit()
|
|
1255
|
+
assert (await self._get(contract_uow_factory)).fingerprint == "e" * 64
|
|
1256
|
+
|
|
1257
|
+
async def test_purge_deletes_expired_records(
|
|
1258
|
+
self, contract_uow_factory: Callable[[], Any]
|
|
1259
|
+
) -> None:
|
|
1260
|
+
async with contract_uow_factory() as uow:
|
|
1261
|
+
for n in range(3):
|
|
1262
|
+
await uow.idempotency().put(self.record(f"old{n}", ttl=timedelta(seconds=-1)))
|
|
1263
|
+
await uow.idempotency().put(self.record("fresh"))
|
|
1264
|
+
await uow.commit()
|
|
1265
|
+
async with contract_uow_factory() as uow:
|
|
1266
|
+
assert await uow.idempotency().purge(datetime.now(UTC), 2) == 2
|
|
1267
|
+
assert await uow.idempotency().purge(datetime.now(UTC), 10) == 1
|
|
1268
|
+
await uow.commit()
|
|
1269
|
+
assert await self._get(contract_uow_factory, "fresh") is not None
|
|
1270
|
+
|
|
1271
|
+
|
|
1272
|
+
class ActivityLogContract:
|
|
1273
|
+
"""Behaviour of an ``ActivityLog``. Fixture: ``activity_log``."""
|
|
1274
|
+
|
|
1275
|
+
@pytest.fixture
|
|
1276
|
+
def activity_log(self) -> Any:
|
|
1277
|
+
"""Override: the ``ActivityLog`` under test."""
|
|
1278
|
+
raise NotImplementedError("Provide an ActivityLog")
|
|
1279
|
+
|
|
1280
|
+
async def test_deliveries_by_message_oldest_first(self, activity_log: Any) -> None:
|
|
1281
|
+
from resource_engine.ports.activity import DeliveryRecord
|
|
1282
|
+
|
|
1283
|
+
now = datetime.now(UTC)
|
|
1284
|
+
later = DeliveryRecord("mailer", "m1", "InvoiceApproved", "retry", 0.25,
|
|
1285
|
+
error="RE-E501: down", at=now) # fmt: skip
|
|
1286
|
+
first = DeliveryRecord("billing", "m1", "InvoiceApproved", "ack", 0.01,
|
|
1287
|
+
at=now - timedelta(seconds=1)) # fmt: skip
|
|
1288
|
+
other = DeliveryRecord("billing", "m2", "InvoiceApproved", "ack", 0.01, at=now)
|
|
1289
|
+
for record in (later, first, other):
|
|
1290
|
+
await activity_log.record_delivery(record)
|
|
1291
|
+
found = await activity_log.deliveries("m1")
|
|
1292
|
+
assert [(d.consumer, d.outcome, d.error) for d in found] == [
|
|
1293
|
+
("billing", "ack", None),
|
|
1294
|
+
("mailer", "retry", "RE-E501: down"),
|
|
1295
|
+
]
|
|
1296
|
+
assert found[1].at == now and found[1].seconds == 0.25
|
|
1297
|
+
assert await activity_log.deliveries("missing") == []
|
|
1298
|
+
|
|
1299
|
+
async def test_purge_deletes_old_records_in_batches(self, activity_log: Any) -> None:
|
|
1300
|
+
from resource_engine.ports.activity import DeliveryRecord
|
|
1301
|
+
|
|
1302
|
+
now = datetime.now(UTC)
|
|
1303
|
+
for i in range(3):
|
|
1304
|
+
await activity_log.record_delivery(
|
|
1305
|
+
DeliveryRecord("c", f"old{i}", "T", "ack", 0.0, at=now - timedelta(days=10))
|
|
1306
|
+
)
|
|
1307
|
+
await activity_log.record_delivery(DeliveryRecord("c", "new", "T", "ack", 0.0, at=now))
|
|
1308
|
+
before = now - timedelta(days=1)
|
|
1309
|
+
assert await activity_log.purge(before, 2) == 2
|
|
1310
|
+
assert await activity_log.purge(before, 10) == 1
|
|
1311
|
+
assert len(await activity_log.deliveries("new")) == 1
|
|
1312
|
+
|
|
1313
|
+
async def test_workers_register_their_jobs(self, activity_log: Any) -> None:
|
|
1314
|
+
from resource_engine.ports.activity import JobInfo
|
|
1315
|
+
|
|
1316
|
+
await activity_log.register_jobs("w1", [JobInfo("outbox", 1.0), JobInfo("timers", 60.0)])
|
|
1317
|
+
await activity_log.register_jobs("w2", [JobInfo("timers", 60.0, single=True, ttl=120.0)])
|
|
1318
|
+
await activity_log.register_jobs("w1", [JobInfo("outbox", 2.0)]) # replaces w1's
|
|
1319
|
+
workers = {w.owner: w for w in await activity_log.workers()}
|
|
1320
|
+
assert set(workers) == {"w1", "w2"}
|
|
1321
|
+
assert workers["w1"].jobs == (JobInfo("outbox", 2.0),)
|
|
1322
|
+
assert workers["w2"].jobs[0].single and workers["w2"].jobs[0].ttl == 120.0
|
|
1323
|
+
|
|
1324
|
+
async def test_job_runs_newest_first(self, activity_log: Any) -> None:
|
|
1325
|
+
from resource_engine.ports.activity import JobRunRecord
|
|
1326
|
+
|
|
1327
|
+
now = datetime.now(UTC)
|
|
1328
|
+
await activity_log.record_job_run(
|
|
1329
|
+
JobRunRecord("outbox", "ok", 0.1, "w1", at=now - timedelta(minutes=2))
|
|
1330
|
+
)
|
|
1331
|
+
await activity_log.record_job_run(
|
|
1332
|
+
JobRunRecord("outbox", "failed", 0.2, "w1", error="RE-E501: down", at=now)
|
|
1333
|
+
)
|
|
1334
|
+
await activity_log.record_job_run(JobRunRecord("timers", "skipped", 0.0, "w2", at=now))
|
|
1335
|
+
runs = await activity_log.job_runs("outbox")
|
|
1336
|
+
assert [(r.outcome, r.error) for r in runs] == [("failed", "RE-E501: down"), ("ok", None)]
|
|
1337
|
+
assert len(await activity_log.job_runs()) == 3
|
|
1338
|
+
assert len(await activity_log.job_runs(limit=1)) == 1
|
|
1339
|
+
|
|
1340
|
+
async def test_run_requests_are_claimed_once(self, activity_log: Any) -> None:
|
|
1341
|
+
request = await activity_log.request_run("timers", "oidc:ana")
|
|
1342
|
+
other = await activity_log.request_run("reports", "oidc:ana")
|
|
1343
|
+
assert (await activity_log.run_request(request.id)).status == "pending"
|
|
1344
|
+
assert await activity_log.claim_requests("w1", ["outbox"]) == [] # not its job
|
|
1345
|
+
[claimed] = await activity_log.claim_requests("w1", ["timers"])
|
|
1346
|
+
assert claimed.id == request.id and claimed.status == "running"
|
|
1347
|
+
assert claimed.claimed_by == "w1" and claimed.requested_by == "oidc:ana"
|
|
1348
|
+
assert await activity_log.claim_requests("w2", ["timers"]) == [] # already claimed
|
|
1349
|
+
await activity_log.finish_request(request.id, "failed", "RuntimeError: boom")
|
|
1350
|
+
done = await activity_log.run_request(request.id)
|
|
1351
|
+
assert done.status == "failed" and done.error == "RuntimeError: boom" and done.finished_at
|
|
1352
|
+
assert (await activity_log.run_request(other.id)).status == "pending"
|
|
1353
|
+
assert await activity_log.run_request("missing") is None
|
|
1354
|
+
|
|
1355
|
+
async def test_purge_covers_runs_requests_and_workers(self, activity_log: Any) -> None:
|
|
1356
|
+
from resource_engine.ports.activity import JobInfo, JobRunRecord
|
|
1357
|
+
|
|
1358
|
+
old = datetime.now(UTC) - timedelta(days=10)
|
|
1359
|
+
await activity_log.record_job_run(JobRunRecord("outbox", "ok", 0.1, "w1", at=old))
|
|
1360
|
+
await activity_log.register_jobs("w1", [JobInfo("outbox", 1.0)])
|
|
1361
|
+
request = await activity_log.request_run("outbox", None)
|
|
1362
|
+
await activity_log.finish_request(request.id, "ok")
|
|
1363
|
+
pending = await activity_log.request_run("outbox", None)
|
|
1364
|
+
assert await activity_log.purge(datetime.now(UTC) + timedelta(seconds=1), 100) >= 3
|
|
1365
|
+
assert await activity_log.job_runs() == []
|
|
1366
|
+
assert await activity_log.run_request(request.id) is None
|
|
1367
|
+
assert await activity_log.run_request(pending.id) is not None # never purged unfinished
|
|
1368
|
+
assert await activity_log.workers() == []
|
|
1369
|
+
|
|
1370
|
+
async def test_dead_letters_newest_first(self, activity_log: Any) -> None:
|
|
1371
|
+
from resource_engine.ports.activity import DeliveryRecord
|
|
1372
|
+
|
|
1373
|
+
now = datetime.now(UTC)
|
|
1374
|
+
await activity_log.record_delivery(
|
|
1375
|
+
DeliveryRecord("billing", "m1", "T", "dead_letter", 0.1, error="RE-E406: no", at=now)
|
|
1376
|
+
)
|
|
1377
|
+
await activity_log.record_delivery(DeliveryRecord("billing", "m2", "T", "ack", 0.1, at=now))
|
|
1378
|
+
await activity_log.record_delivery(
|
|
1379
|
+
DeliveryRecord("mailer", "m3", "T", "dead_letter", 0.1, at=now - timedelta(minutes=1))
|
|
1380
|
+
)
|
|
1381
|
+
found = await activity_log.dead_letters()
|
|
1382
|
+
assert [(d.message_id, d.error) for d in found] == [("m1", "RE-E406: no"), ("m3", None)]
|
|
1383
|
+
assert len(await activity_log.dead_letters(limit=1)) == 1
|
|
1384
|
+
|
|
1385
|
+
|
|
1386
|
+
__all__ = [
|
|
1387
|
+
"CONTRACT_DOCS",
|
|
1388
|
+
"CONTRACT_RESOURCE",
|
|
1389
|
+
"CONTRACT_ROWS",
|
|
1390
|
+
"CONTRACT_VERSIONED",
|
|
1391
|
+
"ActivityLogContract",
|
|
1392
|
+
"AuthorizerContract",
|
|
1393
|
+
"BlobStoreContract",
|
|
1394
|
+
"ConditionContract",
|
|
1395
|
+
"ContractDoc",
|
|
1396
|
+
"ContractItem",
|
|
1397
|
+
"ContractVersioned",
|
|
1398
|
+
"IdempotencyContract",
|
|
1399
|
+
"InboxContract",
|
|
1400
|
+
"LockContract",
|
|
1401
|
+
"MessagePublisherContract",
|
|
1402
|
+
"MessageSourceContract",
|
|
1403
|
+
"OutboxContract",
|
|
1404
|
+
"ReadOnlyRepositoryContract",
|
|
1405
|
+
"Receive",
|
|
1406
|
+
"RepositoryContract",
|
|
1407
|
+
"Send",
|
|
1408
|
+
"UnitOfWorkContract",
|
|
1409
|
+
"VersionContract",
|
|
1410
|
+
"contract_envelope",
|
|
1411
|
+
"contract_principals",
|
|
1412
|
+
"contract_registry",
|
|
1413
|
+
"drain",
|
|
1414
|
+
"missing_capabilities",
|
|
1415
|
+
"require_capability",
|
|
1416
|
+
]
|