netherframe.testing 0.2.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.
- netherframe/testing/__init__.py +1 -0
- netherframe/testing/fakecloud.py +628 -0
- netherframe/testing/graph_memory.py +1484 -0
- netherframe/testing/graph_scenarios.py +377 -0
- netherframe/testing/log_capture.py +33 -0
- netherframe/testing/options.py +124 -0
- netherframe/testing/patching.py +17 -0
- netherframe/testing/provider_sources.py +53 -0
- netherframe/testing/provider_test_helpers.py +33 -0
- netherframe/testing/py.typed +0 -0
- netherframe/testing/pytest_fakecloud.py +75 -0
- netherframe/testing/pytest_workspace.py +122 -0
- netherframe/testing/schema_cache.py +54 -0
- netherframe/testing/state_backend_contract.py +775 -0
- netherframe/testing/terraform_cache.py +39 -0
- netherframe_testing-0.2.0.dist-info/METADATA +26 -0
- netherframe_testing-0.2.0.dist-info/RECORD +35 -0
- netherframe_testing-0.2.0.dist-info/WHEEL +4 -0
- netherframe_testing-0.2.0.dist-info/entry_points.txt +3 -0
- netherframe_testing-0.2.0.dist-info/licenses/LICENSE +21 -0
- nf/testing/__init__.py +21 -0
- nf/testing/fakecloud.py +21 -0
- nf/testing/graph_memory.py +21 -0
- nf/testing/graph_scenarios.py +21 -0
- nf/testing/log_capture.py +21 -0
- nf/testing/options.py +21 -0
- nf/testing/patching.py +21 -0
- nf/testing/provider_sources.py +21 -0
- nf/testing/provider_test_helpers.py +21 -0
- nf/testing/py.typed +0 -0
- nf/testing/pytest_fakecloud.py +21 -0
- nf/testing/pytest_workspace.py +21 -0
- nf/testing/schema_cache.py +21 -0
- nf/testing/state_backend_contract.py +21 -0
- nf/testing/terraform_cache.py +21 -0
|
@@ -0,0 +1,775 @@
|
|
|
1
|
+
# ruff: noqa: S101 - contract checks are pytest assertions shipped for reuse by backend test suites
|
|
2
|
+
"""Contract tests that every ``StateBackend`` implementation must pass.
|
|
3
|
+
|
|
4
|
+
The contract pins down the behavior the state engine relies on: missing state loads
|
|
5
|
+
as an empty ``State``, saved state round-trips (its serial and lineage too), the
|
|
6
|
+
state lock excludes other processes until it is released, releasing a lock you do
|
|
7
|
+
not hold is harmless, the lock holder can keep writing, expiring locks are renewed
|
|
8
|
+
while held, and a conditional write (``save_if_unchanged``) replaces only the
|
|
9
|
+
version of state the writer expects: a writer that read state before another run
|
|
10
|
+
stored a newer one is refused, whether or not it held the lock. Backends that cannot
|
|
11
|
+
write conditionally (``conditional_writes = False``) write anyway, as documented. A
|
|
12
|
+
held lock is reported with its ID (``current_lock()``), and ``force_unlock(id)``
|
|
13
|
+
releases that lock and no other; backends that cannot release another run's lock
|
|
14
|
+
(``can_force_unlock = False``) refuse to. A checkpoint (``save_checkpoint``) keeps the
|
|
15
|
+
stored state as it was, readable back from where it says it is, and only the newest
|
|
16
|
+
are kept; backends that keep none return None. A move (``nf state mv``, through
|
|
17
|
+
``StateEngine.move_entries``) renames an entry and rewrites the entries that depend on
|
|
18
|
+
it in one conditional write: stored whole, or, when it cannot be made or another run
|
|
19
|
+
stored state since it was read, not at all. A removal (``nf state rm``, through
|
|
20
|
+
``StateEngine.forget_entries``) takes resources and outputs out the same way, and never
|
|
21
|
+
leaves an entry depending on one removed.
|
|
22
|
+
|
|
23
|
+
To run it against a backend, subclass :class:`StateBackendContract` in a test module
|
|
24
|
+
and provide a ``backend_factory`` fixture. Every call to the factory must return a
|
|
25
|
+
*new* backend instance pointing at the *same* storage, standing in for a separate
|
|
26
|
+
process sharing that state::
|
|
27
|
+
|
|
28
|
+
import pytest
|
|
29
|
+
from netherframe.testing.state_backend_contract import BackendFactory, StateBackendContract
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TestMyBackendContract(StateBackendContract):
|
|
33
|
+
@pytest.fixture
|
|
34
|
+
def backend_factory(self, tmp_path) -> BackendFactory:
|
|
35
|
+
store = InMemoryStore()
|
|
36
|
+
return lambda: MyStateBackend(client=store.client())
|
|
37
|
+
|
|
38
|
+
Backends whose locks lapse unless renewed (leases, sessions, heartbeats) should set
|
|
39
|
+
``lock_expiry_seconds`` to how long an unrenewed lock survives in the fixture's
|
|
40
|
+
storage, and make the factory shorten the backend's renewal interval accordingly.
|
|
41
|
+
Every lock test runs with that expiry, so keep it well above a renewal thread's delay on a
|
|
42
|
+
loaded machine: the bundled backends use 2 seconds, renewing every third of a second. Below
|
|
43
|
+
a second, a held lock can lapse whenever the suite runs on every core.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import getpass
|
|
49
|
+
import os
|
|
50
|
+
import socket
|
|
51
|
+
import time
|
|
52
|
+
import uuid
|
|
53
|
+
from collections.abc import Callable, Iterator
|
|
54
|
+
from dataclasses import replace
|
|
55
|
+
from typing import Any, ClassVar
|
|
56
|
+
|
|
57
|
+
import pytest
|
|
58
|
+
|
|
59
|
+
from netherframe.core.backends.state_backend import StateBackend
|
|
60
|
+
from netherframe.core.backends.state_engine_runtime import StateEngine
|
|
61
|
+
from netherframe.core.backends.state_lock import LockInfo
|
|
62
|
+
from netherframe.core.backends.state_models import ResourceState, State, StateVersion
|
|
63
|
+
from netherframe.core.exceptions import StateConflictError, StateError, StateLockError
|
|
64
|
+
from netherframe.core.logging import get_logger
|
|
65
|
+
|
|
66
|
+
logger = get_logger(__name__)
|
|
67
|
+
|
|
68
|
+
type BackendFactory = Callable[[], StateBackend]
|
|
69
|
+
|
|
70
|
+
__all__ = [
|
|
71
|
+
"BackendFactory",
|
|
72
|
+
"StateBackendContract",
|
|
73
|
+
"engine_lock_info",
|
|
74
|
+
"sample_state",
|
|
75
|
+
"terraform_lock_info",
|
|
76
|
+
"versioned_state",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
LINEAGE = "3f0c2a5e-contract-lineage"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def engine_lock_info(operation: str = "apply") -> dict[str, Any]:
|
|
83
|
+
"""Return lock info shaped like the one ``StateEngine.lock()`` passes to backends."""
|
|
84
|
+
return {
|
|
85
|
+
"ID": str(uuid.uuid4()),
|
|
86
|
+
"operation": operation,
|
|
87
|
+
"user": getpass.getuser(),
|
|
88
|
+
"host": socket.gethostname(),
|
|
89
|
+
"pid": os.getpid(),
|
|
90
|
+
"timestamp": time.time(),
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def terraform_lock_info(operation: str = "apply") -> dict[str, Any]:
|
|
95
|
+
"""Return lock info in Terraform's ``LockInfo`` shape."""
|
|
96
|
+
return LockInfo(
|
|
97
|
+
id=str(uuid.uuid4()),
|
|
98
|
+
operation=operation,
|
|
99
|
+
who=f"{getpass.getuser()}@{socket.gethostname()}",
|
|
100
|
+
version="1.0.0",
|
|
101
|
+
created=time.time(),
|
|
102
|
+
path="terraform.tfstate",
|
|
103
|
+
).to_dict()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def sample_state(serial: int = 1) -> State:
|
|
107
|
+
"""Return a state that exercises resources, dependencies, outputs and metadata."""
|
|
108
|
+
state = State()
|
|
109
|
+
bucket = ResourceState(
|
|
110
|
+
type="aws_s3_bucket",
|
|
111
|
+
id="assets",
|
|
112
|
+
provider="registry.terraform.io/hashicorp/aws",
|
|
113
|
+
attributes={
|
|
114
|
+
"bucket": f"assets-{serial}",
|
|
115
|
+
"tags": {"env": "test", "owner": "platform"},
|
|
116
|
+
"versioning": [{"enabled": True, "mfa_delete": False}],
|
|
117
|
+
"force_destroy": False,
|
|
118
|
+
"object_lock_enabled": None,
|
|
119
|
+
},
|
|
120
|
+
stack_id="main",
|
|
121
|
+
metadata={"created_by": "contract", "serial": serial},
|
|
122
|
+
)
|
|
123
|
+
policy = ResourceState(
|
|
124
|
+
type="aws_s3_bucket_policy",
|
|
125
|
+
id="assets_policy",
|
|
126
|
+
provider="registry.terraform.io/hashicorp/aws",
|
|
127
|
+
attributes={"bucket": f"assets-{serial}", "policy": '{"Version": "2012-10-17"}'},
|
|
128
|
+
stack_id="main",
|
|
129
|
+
dependencies=[bucket.resource_id],
|
|
130
|
+
)
|
|
131
|
+
state.resources[bucket.resource_id] = bucket
|
|
132
|
+
state.resources[policy.resource_id] = policy
|
|
133
|
+
state.outputs = {
|
|
134
|
+
"bucket_name": f"assets-{serial}",
|
|
135
|
+
"replicas": 3,
|
|
136
|
+
"ratio": 0.5,
|
|
137
|
+
"zones": ["a", "b"],
|
|
138
|
+
"endpoint": {"host": "example.com", "port": 443},
|
|
139
|
+
"unicode": "café ☃",
|
|
140
|
+
}
|
|
141
|
+
state.metadata = {"serial": serial, "lineage": "contract-lineage", "nested": {"k": [1, 2]}}
|
|
142
|
+
return state
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def versioned_state(serial: int, lineage: str = LINEAGE) -> State:
|
|
146
|
+
"""A sample state as the ``serial``-th write of ``lineage`` stores it."""
|
|
147
|
+
state = sample_state(serial)
|
|
148
|
+
state.serial = serial
|
|
149
|
+
state.lineage = lineage
|
|
150
|
+
return state
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class StateBackendContract:
|
|
154
|
+
"""Base class for contract tests; subclasses provide ``backend_factory``."""
|
|
155
|
+
|
|
156
|
+
#: Seconds an unrenewed lock survives in the fixture's storage; None if locks never expire.
|
|
157
|
+
lock_expiry_seconds: ClassVar[float | None] = None
|
|
158
|
+
|
|
159
|
+
#: Whether a lock is its run's, so a run whose lock was released cannot release the next run's;
|
|
160
|
+
#: False where locks belong to a user, whose runs share them (HCP Terraform's workspace locks)
|
|
161
|
+
locks_belong_to_runs: ClassVar[bool] = True
|
|
162
|
+
|
|
163
|
+
#: Whether only the newest checkpoints are kept; False where the storage keeps every version of
|
|
164
|
+
#: state and a checkpoint is one of them (HCP Terraform's state versions)
|
|
165
|
+
checkpoints_are_pruned: ClassVar[bool] = True
|
|
166
|
+
|
|
167
|
+
@pytest.fixture
|
|
168
|
+
def backend_factory(self) -> BackendFactory:
|
|
169
|
+
"""Return a factory creating new backend instances over one shared storage."""
|
|
170
|
+
raise NotImplementedError("Subclasses of StateBackendContract must provide a backend_factory fixture")
|
|
171
|
+
|
|
172
|
+
@pytest.fixture
|
|
173
|
+
def new_backend(self, backend_factory: BackendFactory) -> Iterator[BackendFactory]:
|
|
174
|
+
"""Create backend instances and release any lock they still hold afterwards."""
|
|
175
|
+
created: list[StateBackend] = []
|
|
176
|
+
|
|
177
|
+
def make() -> StateBackend:
|
|
178
|
+
backend = backend_factory()
|
|
179
|
+
created.append(backend)
|
|
180
|
+
return backend
|
|
181
|
+
|
|
182
|
+
yield make
|
|
183
|
+
|
|
184
|
+
for backend in created:
|
|
185
|
+
try:
|
|
186
|
+
backend.unlock()
|
|
187
|
+
except Exception as exc:
|
|
188
|
+
# Best-effort teardown: lock failures under test surface in the tests themselves.
|
|
189
|
+
logger.debug("Ignoring unlock failure during backend fixture teardown: %s", exc)
|
|
190
|
+
|
|
191
|
+
@pytest.fixture(params=["engine", "terraform"])
|
|
192
|
+
def lock_info(self, request: pytest.FixtureRequest) -> Callable[[], dict[str, Any]]:
|
|
193
|
+
"""Build lock info in each shape callers pass to ``lock()``."""
|
|
194
|
+
return engine_lock_info if request.param == "engine" else terraform_lock_info
|
|
195
|
+
|
|
196
|
+
# -- load / save ---------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def test_load_on_fresh_backend_returns_empty_state(self, new_backend: BackendFactory) -> None:
|
|
199
|
+
state = new_backend().load()
|
|
200
|
+
|
|
201
|
+
assert isinstance(state, State)
|
|
202
|
+
assert state.resources == {}
|
|
203
|
+
assert state.outputs == {}
|
|
204
|
+
assert state.metadata == {}
|
|
205
|
+
|
|
206
|
+
def test_save_then_load_round_trips(self, new_backend: BackendFactory) -> None:
|
|
207
|
+
writer = new_backend()
|
|
208
|
+
expected = sample_state()
|
|
209
|
+
|
|
210
|
+
writer.save(expected)
|
|
211
|
+
|
|
212
|
+
assert writer.load().to_dict() == expected.to_dict()
|
|
213
|
+
# A separate instance sees the same state, so it was persisted, not cached.
|
|
214
|
+
assert new_backend().load().to_dict() == expected.to_dict()
|
|
215
|
+
|
|
216
|
+
def test_save_replaces_previous_state(self, new_backend: BackendFactory) -> None:
|
|
217
|
+
backend = new_backend()
|
|
218
|
+
backend.save(sample_state(serial=1))
|
|
219
|
+
|
|
220
|
+
replacement = sample_state(serial=2)
|
|
221
|
+
del replacement.resources["main.aws_s3_bucket_policy.assets_policy"]
|
|
222
|
+
replacement.outputs.pop("zones")
|
|
223
|
+
backend.save(replacement)
|
|
224
|
+
|
|
225
|
+
assert new_backend().load().to_dict() == replacement.to_dict()
|
|
226
|
+
|
|
227
|
+
def test_save_empty_state_round_trips(self, new_backend: BackendFactory) -> None:
|
|
228
|
+
backend = new_backend()
|
|
229
|
+
backend.save(sample_state())
|
|
230
|
+
backend.save(State())
|
|
231
|
+
|
|
232
|
+
loaded = new_backend().load()
|
|
233
|
+
assert loaded.to_dict() == State().to_dict()
|
|
234
|
+
|
|
235
|
+
def test_read_state_write_state_round_trip(self, new_backend: BackendFactory) -> None:
|
|
236
|
+
backend = new_backend()
|
|
237
|
+
read_state = getattr(backend, "read_state", None)
|
|
238
|
+
write_state = getattr(backend, "write_state", None)
|
|
239
|
+
if read_state is None or write_state is None:
|
|
240
|
+
pytest.skip(f"{type(backend).__name__} has no read_state/write_state")
|
|
241
|
+
|
|
242
|
+
assert read_state() is None
|
|
243
|
+
|
|
244
|
+
expected = sample_state()
|
|
245
|
+
write_state(expected)
|
|
246
|
+
|
|
247
|
+
loaded = read_state()
|
|
248
|
+
assert loaded is not None
|
|
249
|
+
assert loaded.to_dict() == expected.to_dict()
|
|
250
|
+
assert new_backend().load().to_dict() == expected.to_dict()
|
|
251
|
+
|
|
252
|
+
# -- locking -------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
def test_lock_succeeds_on_free_backend(
|
|
255
|
+
self,
|
|
256
|
+
new_backend: BackendFactory,
|
|
257
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
258
|
+
) -> None:
|
|
259
|
+
backend = new_backend()
|
|
260
|
+
|
|
261
|
+
assert backend.lock(lock_info()) is True
|
|
262
|
+
# Locking must not invent state on a fresh backend.
|
|
263
|
+
assert new_backend().load().resources == {}
|
|
264
|
+
|
|
265
|
+
def test_second_instance_cannot_lock_while_held(
|
|
266
|
+
self,
|
|
267
|
+
new_backend: BackendFactory,
|
|
268
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
269
|
+
) -> None:
|
|
270
|
+
holder = new_backend()
|
|
271
|
+
contender = new_backend()
|
|
272
|
+
|
|
273
|
+
assert holder.lock(lock_info()) is True
|
|
274
|
+
assert contender.lock(lock_info()) is False
|
|
275
|
+
assert new_backend().lock(lock_info()) is False
|
|
276
|
+
|
|
277
|
+
def test_second_instance_can_lock_after_unlock(
|
|
278
|
+
self,
|
|
279
|
+
new_backend: BackendFactory,
|
|
280
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
281
|
+
) -> None:
|
|
282
|
+
holder = new_backend()
|
|
283
|
+
contender = new_backend()
|
|
284
|
+
|
|
285
|
+
assert holder.lock(lock_info()) is True
|
|
286
|
+
assert contender.lock(lock_info()) is False
|
|
287
|
+
holder.unlock()
|
|
288
|
+
|
|
289
|
+
assert contender.lock(lock_info()) is True
|
|
290
|
+
assert holder.lock(lock_info()) is False
|
|
291
|
+
contender.unlock()
|
|
292
|
+
|
|
293
|
+
assert holder.lock(lock_info()) is True
|
|
294
|
+
|
|
295
|
+
def test_unlock_without_holding_lock_keeps_other_holders_lock(
|
|
296
|
+
self,
|
|
297
|
+
new_backend: BackendFactory,
|
|
298
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
299
|
+
) -> None:
|
|
300
|
+
holder = new_backend()
|
|
301
|
+
bystander = new_backend()
|
|
302
|
+
loser = new_backend()
|
|
303
|
+
|
|
304
|
+
assert holder.lock(lock_info()) is True
|
|
305
|
+
|
|
306
|
+
bystander.unlock()
|
|
307
|
+
# A caller whose lock() failed commonly still calls unlock() in a finally block.
|
|
308
|
+
assert loser.lock(lock_info()) is False
|
|
309
|
+
loser.unlock()
|
|
310
|
+
|
|
311
|
+
assert new_backend().lock(lock_info()) is False
|
|
312
|
+
holder.unlock()
|
|
313
|
+
assert new_backend().lock(lock_info()) is True
|
|
314
|
+
|
|
315
|
+
def test_unlock_is_idempotent(
|
|
316
|
+
self,
|
|
317
|
+
new_backend: BackendFactory,
|
|
318
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
319
|
+
) -> None:
|
|
320
|
+
new_backend().unlock()
|
|
321
|
+
|
|
322
|
+
backend = new_backend()
|
|
323
|
+
assert backend.lock(lock_info()) is True
|
|
324
|
+
backend.unlock()
|
|
325
|
+
backend.unlock()
|
|
326
|
+
|
|
327
|
+
assert new_backend().lock(lock_info()) is True
|
|
328
|
+
|
|
329
|
+
def test_writes_while_holding_lock_succeed(
|
|
330
|
+
self,
|
|
331
|
+
new_backend: BackendFactory,
|
|
332
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
333
|
+
) -> None:
|
|
334
|
+
holder = new_backend()
|
|
335
|
+
first = sample_state(serial=1)
|
|
336
|
+
second = sample_state(serial=2)
|
|
337
|
+
|
|
338
|
+
assert holder.lock(lock_info()) is True
|
|
339
|
+
holder.save(first)
|
|
340
|
+
assert holder.load().to_dict() == first.to_dict()
|
|
341
|
+
write_state = getattr(holder, "write_state", None)
|
|
342
|
+
if write_state is not None:
|
|
343
|
+
write_state(second)
|
|
344
|
+
else:
|
|
345
|
+
holder.save(second)
|
|
346
|
+
assert new_backend().load().to_dict() == second.to_dict()
|
|
347
|
+
|
|
348
|
+
holder.unlock()
|
|
349
|
+
|
|
350
|
+
def test_writes_to_existing_state_while_holding_lock_succeed(
|
|
351
|
+
self,
|
|
352
|
+
new_backend: BackendFactory,
|
|
353
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
354
|
+
) -> None:
|
|
355
|
+
existing = sample_state(serial=1)
|
|
356
|
+
new_backend().save(existing)
|
|
357
|
+
|
|
358
|
+
holder = new_backend()
|
|
359
|
+
assert holder.lock(lock_info()) is True
|
|
360
|
+
assert holder.load().to_dict() == existing.to_dict()
|
|
361
|
+
|
|
362
|
+
updated = sample_state(serial=2)
|
|
363
|
+
holder.save(updated)
|
|
364
|
+
holder.unlock()
|
|
365
|
+
|
|
366
|
+
assert new_backend().load().to_dict() == updated.to_dict()
|
|
367
|
+
|
|
368
|
+
def test_lock_is_kept_alive_while_held(self, new_backend: BackendFactory) -> None:
|
|
369
|
+
expiry = self.lock_expiry_seconds
|
|
370
|
+
if expiry is None:
|
|
371
|
+
pytest.skip("locks of this backend do not expire")
|
|
372
|
+
|
|
373
|
+
holder = new_backend()
|
|
374
|
+
assert holder.lock(engine_lock_info()) is True
|
|
375
|
+
|
|
376
|
+
time.sleep(expiry * 3)
|
|
377
|
+
|
|
378
|
+
assert new_backend().lock(engine_lock_info()) is False
|
|
379
|
+
latest = sample_state(serial=3)
|
|
380
|
+
holder.save(latest)
|
|
381
|
+
assert new_backend().load().to_dict() == latest.to_dict()
|
|
382
|
+
|
|
383
|
+
holder.unlock()
|
|
384
|
+
assert new_backend().lock(engine_lock_info()) is True
|
|
385
|
+
|
|
386
|
+
# -- conditional writes --------------------------------------------------------------
|
|
387
|
+
|
|
388
|
+
def test_load_returns_the_serial_and_lineage_written(self, new_backend: BackendFactory) -> None:
|
|
389
|
+
new_backend().save(versioned_state(7))
|
|
390
|
+
|
|
391
|
+
loaded = new_backend().load()
|
|
392
|
+
|
|
393
|
+
assert (loaded.serial, loaded.lineage) == (7, LINEAGE)
|
|
394
|
+
assert loaded.to_dict() == versioned_state(7).to_dict()
|
|
395
|
+
|
|
396
|
+
def test_conditional_writes_replace_the_version_they_expect(self, new_backend: BackendFactory) -> None:
|
|
397
|
+
writer = new_backend()
|
|
398
|
+
assert StateVersion.of(writer.load()) == StateVersion()
|
|
399
|
+
|
|
400
|
+
writer.save_if_unchanged(versioned_state(1), StateVersion())
|
|
401
|
+
writer.save_if_unchanged(versioned_state(2), StateVersion(1, LINEAGE))
|
|
402
|
+
|
|
403
|
+
assert new_backend().load().to_dict() == versioned_state(2).to_dict()
|
|
404
|
+
# A new instance, which read nothing yet, writes over what it reads
|
|
405
|
+
other = new_backend()
|
|
406
|
+
assert StateVersion.of(other.load()) == StateVersion(2, LINEAGE)
|
|
407
|
+
other.save_if_unchanged(versioned_state(3), StateVersion(2, LINEAGE))
|
|
408
|
+
assert new_backend().load().to_dict() == versioned_state(3).to_dict()
|
|
409
|
+
|
|
410
|
+
def test_a_writer_that_read_before_another_run_wrote_is_refused(self, new_backend: BackendFactory) -> None:
|
|
411
|
+
new_backend().save(versioned_state(1))
|
|
412
|
+
stale = new_backend()
|
|
413
|
+
current = new_backend()
|
|
414
|
+
assert stale.load().serial == 1
|
|
415
|
+
assert current.load().serial == 1
|
|
416
|
+
|
|
417
|
+
current.save_if_unchanged(versioned_state(2), StateVersion(1, LINEAGE))
|
|
418
|
+
|
|
419
|
+
if not stale.conditional_writes:
|
|
420
|
+
stale.save_if_unchanged(versioned_state(2, "stale"), StateVersion(1, LINEAGE))
|
|
421
|
+
assert new_backend().load().lineage == "stale" # documented: written anyway
|
|
422
|
+
return
|
|
423
|
+
with pytest.raises(StateConflictError, match="written by another run"):
|
|
424
|
+
stale.save_if_unchanged(versioned_state(2, "stale"), StateVersion(1, LINEAGE))
|
|
425
|
+
assert new_backend().load().to_dict() == versioned_state(2).to_dict()
|
|
426
|
+
|
|
427
|
+
def test_a_first_write_is_refused_once_another_run_created_state(self, new_backend: BackendFactory) -> None:
|
|
428
|
+
stale = new_backend()
|
|
429
|
+
assert stale.load().resources == {}
|
|
430
|
+
new_backend().save_if_unchanged(versioned_state(1, "first"), StateVersion())
|
|
431
|
+
|
|
432
|
+
if not stale.conditional_writes:
|
|
433
|
+
pytest.skip(f"{type(stale).__name__} cannot write conditionally")
|
|
434
|
+
with pytest.raises(StateConflictError):
|
|
435
|
+
stale.save_if_unchanged(versioned_state(1, "second"), StateVersion())
|
|
436
|
+
assert new_backend().load().lineage == "first"
|
|
437
|
+
|
|
438
|
+
def test_a_holder_whose_lock_was_taken_over_cannot_overwrite_the_new_holder(
|
|
439
|
+
self,
|
|
440
|
+
new_backend: BackendFactory,
|
|
441
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
442
|
+
) -> None:
|
|
443
|
+
"""A run whose lock lapsed (or was forced open) is refused when it writes after the next run did."""
|
|
444
|
+
old_holder = new_backend()
|
|
445
|
+
assert old_holder.lock(lock_info()) is True
|
|
446
|
+
assert StateVersion.of(old_holder.load()) == StateVersion()
|
|
447
|
+
old_holder.unlock() # stands in for a lock that lapsed while its holder kept running
|
|
448
|
+
|
|
449
|
+
new_holder = new_backend()
|
|
450
|
+
assert new_holder.lock(lock_info()) is True
|
|
451
|
+
new_holder.load()
|
|
452
|
+
new_holder.save_if_unchanged(versioned_state(1), StateVersion())
|
|
453
|
+
|
|
454
|
+
if not old_holder.conditional_writes:
|
|
455
|
+
pytest.skip(f"{type(old_holder).__name__} cannot write conditionally")
|
|
456
|
+
# Refused as a conflict, or because the new holder's lock excludes the write
|
|
457
|
+
with pytest.raises(StateError):
|
|
458
|
+
old_holder.save_if_unchanged(versioned_state(1, "old-holder"), StateVersion())
|
|
459
|
+
new_holder.unlock()
|
|
460
|
+
with pytest.raises(StateConflictError):
|
|
461
|
+
old_holder.save_if_unchanged(versioned_state(1, "old-holder"), StateVersion())
|
|
462
|
+
assert new_backend().load().to_dict() == versioned_state(1).to_dict()
|
|
463
|
+
|
|
464
|
+
# -- moves (nf state mv) ---------------------------------------------------------------
|
|
465
|
+
|
|
466
|
+
BUCKET = "main.aws_s3_bucket.assets"
|
|
467
|
+
MOVED_BUCKET = "main.aws_s3_bucket.static"
|
|
468
|
+
POLICY = "main.aws_s3_bucket_policy.assets_policy"
|
|
469
|
+
|
|
470
|
+
def _moved_bucket(self, engine: StateEngine) -> tuple[str, ResourceState]:
|
|
471
|
+
return self.BUCKET, replace(engine.load_state().resources[self.BUCKET], id="static")
|
|
472
|
+
|
|
473
|
+
def test_a_move_renames_an_entry_and_its_dependents_in_one_write(self, new_backend: BackendFactory) -> None:
|
|
474
|
+
new_backend().save(versioned_state(1))
|
|
475
|
+
engine = StateEngine(new_backend())
|
|
476
|
+
assert engine.lock("move") is True
|
|
477
|
+
try:
|
|
478
|
+
engine.move_entries([self._moved_bucket(engine)])
|
|
479
|
+
finally:
|
|
480
|
+
engine.unlock()
|
|
481
|
+
|
|
482
|
+
stored = new_backend().load()
|
|
483
|
+
expected = versioned_state(1)
|
|
484
|
+
assert set(stored.resources) == {self.MOVED_BUCKET, self.POLICY}
|
|
485
|
+
assert stored.resources[self.MOVED_BUCKET].attributes == expected.resources[self.BUCKET].attributes
|
|
486
|
+
assert stored.resources[self.POLICY].dependencies == [self.MOVED_BUCKET]
|
|
487
|
+
assert (stored.outputs, stored.metadata) == (expected.outputs, expected.metadata)
|
|
488
|
+
assert StateVersion.of(stored) == StateVersion(2, LINEAGE)
|
|
489
|
+
|
|
490
|
+
def test_moves_are_made_in_order_and_dependents_follow_each(self, new_backend: BackendFactory) -> None:
|
|
491
|
+
new_backend().save(versioned_state(1))
|
|
492
|
+
engine = StateEngine(new_backend())
|
|
493
|
+
assert engine.lock("move") is True
|
|
494
|
+
try:
|
|
495
|
+
source, renamed = self._moved_bucket(engine)
|
|
496
|
+
engine.move_entries([(source, renamed), (self.MOVED_BUCKET, replace(renamed, id="final"))])
|
|
497
|
+
finally:
|
|
498
|
+
engine.unlock()
|
|
499
|
+
|
|
500
|
+
stored = new_backend().load()
|
|
501
|
+
assert set(stored.resources) == {"main.aws_s3_bucket.final", self.POLICY}
|
|
502
|
+
assert stored.resources[self.POLICY].dependencies == ["main.aws_s3_bucket.final"]
|
|
503
|
+
|
|
504
|
+
@pytest.mark.parametrize(
|
|
505
|
+
("source", "target", "problem"),
|
|
506
|
+
[
|
|
507
|
+
("main.aws_s3_bucket.missing", "main.aws_s3_bucket.static", "is not in state"),
|
|
508
|
+
(BUCKET, POLICY, "is already in state"),
|
|
509
|
+
],
|
|
510
|
+
)
|
|
511
|
+
def test_a_move_state_cannot_make_writes_nothing(self, new_backend: BackendFactory, source: str, target: str, problem: str) -> None:
|
|
512
|
+
new_backend().save(versioned_state(1))
|
|
513
|
+
engine = StateEngine(new_backend())
|
|
514
|
+
assert engine.lock("move") is True
|
|
515
|
+
try:
|
|
516
|
+
entry = engine.load_state().resources[self.BUCKET]
|
|
517
|
+
target_type, target_name = target.split(".")[1:]
|
|
518
|
+
with pytest.raises(StateError, match=problem):
|
|
519
|
+
engine.move_entries([(source, replace(entry, type=target_type, id=target_name))])
|
|
520
|
+
finally:
|
|
521
|
+
engine.unlock()
|
|
522
|
+
|
|
523
|
+
assert new_backend().load().to_dict() == versioned_state(1).to_dict()
|
|
524
|
+
|
|
525
|
+
def test_a_move_is_refused_once_another_run_stored_state(self, new_backend: BackendFactory) -> None:
|
|
526
|
+
"""A move read before another run wrote (its lock lapsed meanwhile) stores nothing over that run's state."""
|
|
527
|
+
new_backend().save(versioned_state(1))
|
|
528
|
+
engine = StateEngine(new_backend())
|
|
529
|
+
assert engine.lock("move") is True
|
|
530
|
+
move = self._moved_bucket(engine)
|
|
531
|
+
engine.backend.unlock() # stands in for a lock that lapsed while the move was prepared
|
|
532
|
+
|
|
533
|
+
other = new_backend()
|
|
534
|
+
assert other.lock(engine_lock_info()) is True
|
|
535
|
+
other.load()
|
|
536
|
+
other.save_if_unchanged(versioned_state(2), StateVersion(1, LINEAGE))
|
|
537
|
+
other.unlock()
|
|
538
|
+
|
|
539
|
+
if not engine.backend.conditional_writes:
|
|
540
|
+
pytest.skip(f"{type(engine.backend).__name__} cannot write conditionally")
|
|
541
|
+
try:
|
|
542
|
+
with pytest.raises(StateConflictError):
|
|
543
|
+
engine.move_entries([move])
|
|
544
|
+
finally:
|
|
545
|
+
engine.unlock()
|
|
546
|
+
assert new_backend().load().to_dict() == versioned_state(2).to_dict()
|
|
547
|
+
|
|
548
|
+
# -- removals (nf state rm) -------------------------------------------------------------
|
|
549
|
+
|
|
550
|
+
OUTPUT = "main.output.bucket"
|
|
551
|
+
|
|
552
|
+
def _with_output(self) -> State:
|
|
553
|
+
state = versioned_state(1)
|
|
554
|
+
state.outputs[self.OUTPUT] = {"value": "assets-1", "sensitive": False}
|
|
555
|
+
return state
|
|
556
|
+
|
|
557
|
+
def test_a_removal_takes_resources_and_outputs_out_in_one_write(self, new_backend: BackendFactory) -> None:
|
|
558
|
+
new_backend().save(self._with_output())
|
|
559
|
+
engine = StateEngine(new_backend())
|
|
560
|
+
assert engine.lock("forget") is True
|
|
561
|
+
try:
|
|
562
|
+
removed = engine.forget_entries([self.POLICY, self.BUCKET, self.OUTPUT])
|
|
563
|
+
finally:
|
|
564
|
+
engine.unlock()
|
|
565
|
+
|
|
566
|
+
stored = new_backend().load()
|
|
567
|
+
assert removed == (self.POLICY, self.BUCKET, self.OUTPUT)
|
|
568
|
+
assert stored.resources == {}
|
|
569
|
+
assert stored.outputs == versioned_state(1).outputs
|
|
570
|
+
assert StateVersion.of(stored) == StateVersion(2, LINEAGE)
|
|
571
|
+
|
|
572
|
+
@pytest.mark.parametrize(
|
|
573
|
+
("addresses", "problem"),
|
|
574
|
+
[
|
|
575
|
+
# The policy depends on the bucket: removing the bucket alone would leave it dangling
|
|
576
|
+
([BUCKET], "depend on what would be removed"),
|
|
577
|
+
(["main.aws_s3_bucket.missing"], "is not in state"),
|
|
578
|
+
(["main.data.aws_s3_bucket.assets"], "not a managed resource or output"),
|
|
579
|
+
(["main.aws_s3_bucket.assets[0]"], "not a managed resource or output"),
|
|
580
|
+
([POLICY, POLICY], "distinct target addresses"),
|
|
581
|
+
],
|
|
582
|
+
)
|
|
583
|
+
def test_a_removal_state_cannot_make_writes_nothing(self, new_backend: BackendFactory, addresses: list[str], problem: str) -> None:
|
|
584
|
+
new_backend().save(self._with_output())
|
|
585
|
+
engine = StateEngine(new_backend())
|
|
586
|
+
assert engine.lock("forget") is True
|
|
587
|
+
try:
|
|
588
|
+
with pytest.raises(StateError, match=problem):
|
|
589
|
+
engine.forget_entries(addresses)
|
|
590
|
+
finally:
|
|
591
|
+
engine.unlock()
|
|
592
|
+
|
|
593
|
+
assert new_backend().load().to_dict() == self._with_output().to_dict()
|
|
594
|
+
|
|
595
|
+
def test_a_removal_is_refused_once_another_run_stored_state(self, new_backend: BackendFactory) -> None:
|
|
596
|
+
new_backend().save(versioned_state(1))
|
|
597
|
+
engine = StateEngine(new_backend())
|
|
598
|
+
assert engine.lock("forget") is True
|
|
599
|
+
engine.load_state()
|
|
600
|
+
engine.backend.unlock() # stands in for a lock that lapsed while the removal was prepared
|
|
601
|
+
|
|
602
|
+
other = new_backend()
|
|
603
|
+
assert other.lock(engine_lock_info()) is True
|
|
604
|
+
other.load()
|
|
605
|
+
other.save_if_unchanged(versioned_state(2), StateVersion(1, LINEAGE))
|
|
606
|
+
other.unlock()
|
|
607
|
+
|
|
608
|
+
if not engine.backend.conditional_writes:
|
|
609
|
+
pytest.skip(f"{type(engine.backend).__name__} cannot write conditionally")
|
|
610
|
+
try:
|
|
611
|
+
with pytest.raises(StateConflictError):
|
|
612
|
+
engine.forget_entries([self.POLICY])
|
|
613
|
+
finally:
|
|
614
|
+
engine.unlock()
|
|
615
|
+
assert new_backend().load().to_dict() == versioned_state(2).to_dict()
|
|
616
|
+
|
|
617
|
+
# -- force-unlock ----------------------------------------------------------------------
|
|
618
|
+
|
|
619
|
+
def test_the_lock_held_is_reported_with_its_id(
|
|
620
|
+
self,
|
|
621
|
+
new_backend: BackendFactory,
|
|
622
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
623
|
+
) -> None:
|
|
624
|
+
assert new_backend().current_lock() is None
|
|
625
|
+
holder = new_backend()
|
|
626
|
+
info = lock_info()
|
|
627
|
+
assert holder.lock(info) is True
|
|
628
|
+
|
|
629
|
+
current = new_backend().current_lock()
|
|
630
|
+
|
|
631
|
+
if current is None:
|
|
632
|
+
pytest.skip(f"{type(holder).__name__} cannot tell who holds its lock")
|
|
633
|
+
assert current["ID"]
|
|
634
|
+
holder.unlock()
|
|
635
|
+
assert new_backend().current_lock() is None
|
|
636
|
+
|
|
637
|
+
def test_force_unlock_releases_the_lock_it_names_and_no_other(
|
|
638
|
+
self,
|
|
639
|
+
new_backend: BackendFactory,
|
|
640
|
+
lock_info: Callable[[], dict[str, Any]],
|
|
641
|
+
) -> None:
|
|
642
|
+
holder = new_backend()
|
|
643
|
+
assert holder.lock(lock_info()) is True
|
|
644
|
+
current = new_backend().current_lock()
|
|
645
|
+
if current is None:
|
|
646
|
+
pytest.skip(f"{type(holder).__name__} cannot tell who holds its lock")
|
|
647
|
+
lock_id = str(current["ID"])
|
|
648
|
+
rescuer = new_backend()
|
|
649
|
+
|
|
650
|
+
with pytest.raises(StateLockError):
|
|
651
|
+
rescuer.force_unlock(f"not-{lock_id}")
|
|
652
|
+
assert new_backend().lock(lock_info()) is False
|
|
653
|
+
|
|
654
|
+
if not rescuer.can_force_unlock:
|
|
655
|
+
with pytest.raises(StateLockError):
|
|
656
|
+
rescuer.force_unlock(lock_id)
|
|
657
|
+
assert new_backend().lock(lock_info()) is False
|
|
658
|
+
return
|
|
659
|
+
rescuer.force_unlock(lock_id)
|
|
660
|
+
|
|
661
|
+
assert new_backend().current_lock() is None
|
|
662
|
+
successor = new_backend()
|
|
663
|
+
assert successor.lock(lock_info()) is True
|
|
664
|
+
if self.locks_belong_to_runs:
|
|
665
|
+
# The released holder's unlock, when it comes, leaves the successor's lock alone
|
|
666
|
+
holder.unlock()
|
|
667
|
+
assert new_backend().lock(lock_info()) is False
|
|
668
|
+
successor.unlock()
|
|
669
|
+
|
|
670
|
+
def test_force_unlock_of_an_unlocked_state_is_refused(self, new_backend: BackendFactory) -> None:
|
|
671
|
+
with pytest.raises(StateLockError):
|
|
672
|
+
new_backend().force_unlock("no-such-lock")
|
|
673
|
+
|
|
674
|
+
# -- checkpoints -----------------------------------------------------------------------
|
|
675
|
+
|
|
676
|
+
def test_a_checkpoint_keeps_the_stored_state_as_it_was(self, new_backend: BackendFactory) -> None:
|
|
677
|
+
backend = new_backend()
|
|
678
|
+
backend.save(versioned_state(1))
|
|
679
|
+
|
|
680
|
+
location = backend.save_checkpoint("pre-apply-20260101T000000Z-0000aaaa.json", keep=5)
|
|
681
|
+
|
|
682
|
+
if location is None:
|
|
683
|
+
pytest.skip(f"{type(backend).__name__} keeps no checkpoints")
|
|
684
|
+
new_backend().save(versioned_state(2))
|
|
685
|
+
restored = new_backend().load_checkpoint(location)
|
|
686
|
+
assert restored is not None
|
|
687
|
+
assert restored.to_dict() == versioned_state(1).to_dict()
|
|
688
|
+
# Keeping a checkpoint leaves the state alone
|
|
689
|
+
assert new_backend().load().to_dict() == versioned_state(2).to_dict()
|
|
690
|
+
assert new_backend().load_checkpoint("/somewhere/else.json") is None
|
|
691
|
+
|
|
692
|
+
def test_only_the_newest_checkpoints_are_kept(self, new_backend: BackendFactory) -> None:
|
|
693
|
+
backend = new_backend()
|
|
694
|
+
backend.save(versioned_state(1))
|
|
695
|
+
|
|
696
|
+
locations = [backend.save_checkpoint(f"pre-apply-2026010{day}T000000Z-0000aaaa.json", keep=2) for day in range(1, 5)]
|
|
697
|
+
|
|
698
|
+
if locations[0] is None:
|
|
699
|
+
pytest.skip(f"{type(backend).__name__} keeps no checkpoints")
|
|
700
|
+
if not self.checkpoints_are_pruned:
|
|
701
|
+
assert all(new_backend().load_checkpoint(str(location)) is not None for location in locations)
|
|
702
|
+
return
|
|
703
|
+
with pytest.raises(FileNotFoundError):
|
|
704
|
+
new_backend().load_checkpoint(str(locations[0]))
|
|
705
|
+
assert new_backend().load_checkpoint(str(locations[-1])) is not None
|
|
706
|
+
|
|
707
|
+
def test_checkpoints_named_before_names_were_utc_are_pruned_first(self, new_backend: BackendFactory) -> None:
|
|
708
|
+
"""A local-time name of a later hour (a run east of UTC) is still older than any UTC name."""
|
|
709
|
+
backend = new_backend()
|
|
710
|
+
backend.save(versioned_state(1))
|
|
711
|
+
|
|
712
|
+
legacy = backend.save_checkpoint("pre-apply-20260109T230000-0000aaaa.json", keep=2)
|
|
713
|
+
if legacy is None or not self.checkpoints_are_pruned:
|
|
714
|
+
pytest.skip(f"{type(backend).__name__} prunes no checkpoints")
|
|
715
|
+
utc = [backend.save_checkpoint(f"pre-apply-2026010{day}T000000Z-0000aaaa.json", keep=2) for day in (1, 2)]
|
|
716
|
+
|
|
717
|
+
with pytest.raises(FileNotFoundError):
|
|
718
|
+
new_backend().load_checkpoint(str(legacy))
|
|
719
|
+
assert all(new_backend().load_checkpoint(str(location)) is not None for location in utc)
|
|
720
|
+
|
|
721
|
+
def test_a_run_status_is_kept_beside_the_state_apart_from_it(self, new_backend: BackendFactory) -> None:
|
|
722
|
+
"""A running apply's status (``write_run_status``) round-trips, is replaced, and touches neither state nor checkpoints."""
|
|
723
|
+
backend = new_backend()
|
|
724
|
+
if not backend.supports_run_status():
|
|
725
|
+
assert backend.run_status_location() is None
|
|
726
|
+
assert backend.read_run_status() is None
|
|
727
|
+
pytest.skip(f"{type(backend).__name__} keeps no run status")
|
|
728
|
+
backend.save(versioned_state(1))
|
|
729
|
+
assert new_backend().read_run_status() is None
|
|
730
|
+
|
|
731
|
+
backend.write_run_status(b'{"phase":"applying"}')
|
|
732
|
+
backend.write_run_status(b'{"phase":"finished"}')
|
|
733
|
+
|
|
734
|
+
reader = new_backend()
|
|
735
|
+
assert reader.read_run_status() == b'{"phase":"finished"}'
|
|
736
|
+
assert reader.run_status_location()
|
|
737
|
+
assert reader.load().to_dict() == versioned_state(1).to_dict()
|
|
738
|
+
location = backend.save_checkpoint("pre-apply-20260101T000000Z-0000aaaa.json", keep=1)
|
|
739
|
+
if location is not None:
|
|
740
|
+
# The status is no checkpoint: keeping one prunes nothing of it, and it is not listed as one
|
|
741
|
+
assert new_backend().read_run_status() == b'{"phase":"finished"}'
|
|
742
|
+
assert new_backend().load_checkpoint(location) is not None
|
|
743
|
+
|
|
744
|
+
def test_run_records_are_kept_beside_the_state_by_run_apart_from_it(self, new_backend: BackendFactory) -> None:
|
|
745
|
+
"""Run records (``write_run_record``) round-trip by run id, are listed, replaced and deleted, and touch neither state, checkpoints nor the run status."""
|
|
746
|
+
backend = new_backend()
|
|
747
|
+
if not backend.supports_run_records():
|
|
748
|
+
assert backend.run_record_location("20260101T000000.000000001Z-0000aaaa") is None
|
|
749
|
+
assert backend.read_run_record("20260101T000000.000000001Z-0000aaaa") is None
|
|
750
|
+
assert backend.run_record_ids() == []
|
|
751
|
+
pytest.skip(f"{type(backend).__name__} keeps no run records")
|
|
752
|
+
backend.save(versioned_state(1))
|
|
753
|
+
first, second = "20260101T000000.000000001Z-0000aaaa", "20260101T000000.000000002Z-0000bbbb"
|
|
754
|
+
assert new_backend().run_record_ids() == []
|
|
755
|
+
assert new_backend().read_run_record(first) is None
|
|
756
|
+
|
|
757
|
+
backend.write_run_record(first, b'{"status":"running"}')
|
|
758
|
+
backend.write_run_record(second, b'{"status":"finalized"}')
|
|
759
|
+
backend.write_run_record(first, b'{"status":"failed"}')
|
|
760
|
+
|
|
761
|
+
reader = new_backend()
|
|
762
|
+
assert reader.run_record_ids() == [first, second]
|
|
763
|
+
assert (reader.read_run_record(first), reader.read_run_record(second)) == (b'{"status":"failed"}', b'{"status":"finalized"}')
|
|
764
|
+
assert reader.run_record_location(first)
|
|
765
|
+
assert reader.run_record_location(first) != reader.run_record_location(second)
|
|
766
|
+
assert reader.load().to_dict() == versioned_state(1).to_dict()
|
|
767
|
+
if backend.supports_run_status():
|
|
768
|
+
backend.write_run_status(b'{"phase":"finished"}')
|
|
769
|
+
backend.save_checkpoint("pre-apply-20260101T000000Z-0000aaaa.json", keep=1)
|
|
770
|
+
# Neither a checkpoint nor the run status is a run record
|
|
771
|
+
assert new_backend().run_record_ids() == [first, second]
|
|
772
|
+
|
|
773
|
+
backend.delete_run_record(second)
|
|
774
|
+
assert new_backend().run_record_ids() == [first]
|
|
775
|
+
assert new_backend().read_run_record(second) is None
|