280 lines
14 KiB
Python
280 lines
14 KiB
Python
"""Current DB/publication owners with simulated Git transport; no external publication."""
|
|
# #region Test.Tooling.PublishCatalog [C:3] [TYPE Module] [SEMANTICS test,gitea,catalog,publish]
|
|
# @BRIEF Preserve eight publisher test identities at exact DB revision, destination, transport and durable worker boundaries.
|
|
# @RELATION VERIFIES -> [Tooling.PublishCatalog]
|
|
# @RELATION VERIFIES -> [BaselineEngine.CatalogStore.Read]
|
|
# @RELATION VERIFIES -> [ScenarioExecution.PublicationWorker.Publish]
|
|
# @TEST_INVARIANT Invalid current revisions/configuration cannot reach HTTP; create/update bytes and verified receipts remain exact.
|
|
# @RATIONALE D15 removed CLI/file-envelope/alias mechanics; live publication properties use current owners, never compatibility exports.
|
|
import base64
|
|
from copy import deepcopy
|
|
import json
|
|
|
|
import httpx
|
|
import pytest
|
|
import yaml
|
|
|
|
from src.models.baseline_catalog import BaselineCatalogMembership, BaselineCatalogRevision
|
|
from src.models.publication_operation import PublicationOperation
|
|
from src.scripts.publish_catalog import PublishError, fetch_existing_sha, publish_catalog_bytes
|
|
from src.services.dashboard_testing.catalog_store import load_catalog_revision, render_catalog_revision
|
|
from src.services.dashboard_testing.execution.publication_config import PublicationDestination
|
|
from src.services.dashboard_testing.execution.publication_errors import PublicationError
|
|
from src.services.dashboard_testing.execution.publication_worker import publish_baseline_catalog
|
|
from tests.services.dashboard_testing.execution.test_publication_failure_state import (
|
|
_stored_state,
|
|
publication_configuration as publication_configuration,
|
|
)
|
|
from tests.services.dashboard_testing.execution.test_publication_transaction_recovery import (
|
|
pending_publication as pending_publication,
|
|
publication_trace as publication_trace,
|
|
)
|
|
from tests.services.dashboard_testing.execution.test_publication_worker import (
|
|
attempt_case, Server, HEAD, WRITTEN, publication_source_identity as publication_source_identity,
|
|
)
|
|
from tests.services.dashboard_testing.test_baseline_catalog import exact_selector
|
|
|
|
|
|
# #region Test.Tooling.PublishCatalog.Fakes [C:2] [TYPE Class]
|
|
# @BRIEF Minimal httpx-client doubles capturing GET/POST/PUT calls for offline assertions.
|
|
class _FakeResponse:
|
|
def __init__(self, status_code: int, payload=None, text: str = "") -> None:
|
|
self.status_code = status_code
|
|
self._payload = payload if payload is not None else {}
|
|
self.text = text
|
|
|
|
def json(self):
|
|
return self._payload
|
|
|
|
|
|
class _FakeClient:
|
|
def __init__(self, get_response, put_response, post_response=None) -> None:
|
|
self.get_response = get_response
|
|
self.put_response = put_response
|
|
self.post_response = post_response or put_response
|
|
self.gets: list[tuple[str, dict]] = []
|
|
self.puts: list[tuple[str, dict]] = []
|
|
self.posts: list[tuple[str, dict]] = []
|
|
|
|
def get(self, url, params=None):
|
|
self.gets.append((url, params or {}))
|
|
return self.get_response
|
|
|
|
def put(self, url, json=None):
|
|
self.puts.append((url, json or {}))
|
|
return self.put_response
|
|
|
|
def post(self, url, json=None):
|
|
self.posts.append((url, json or {}))
|
|
return self.post_response
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *args):
|
|
return False
|
|
# #endregion Test.Tooling.PublishCatalog.Fakes
|
|
|
|
# #region Test.Tooling.PublishCatalog.Validate [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Exact immutable DB payload/membership must validate before rendering or HTTP; invalid revisions do not mutate.
|
|
def test_validate_catalog_accepts_envelope_and_rejects_nested_only_and_malformed(monkeypatch):
|
|
db, _, snapshot, _, _, rendered = attempt_case()
|
|
assert yaml.safe_load(rendered.content) == {
|
|
"integrity_sha256": snapshot.integrity_sha256,
|
|
"catalog_revision": snapshot.revision.model_dump(mode="json"),
|
|
}
|
|
assert load_catalog_revision(db, exact_selector()) == snapshot
|
|
|
|
def forbidden(*args, **kwargs):
|
|
pytest.fail("Invalid DB revision reached HTTP")
|
|
|
|
monkeypatch.setattr(httpx, "Client", forbidden)
|
|
for change, code in (
|
|
("payload", "CATALOG_REVISION_PAYLOAD_INVALID"),
|
|
("identity", "CATALOG_REVISION_IDENTITY_CONFLICT"),
|
|
("membership", "CATALOG_MEMBERSHIP_INTEGRITY_CONFLICT"),
|
|
("missing", "CATALOG_REVISION_MISSING"),
|
|
):
|
|
invalid = attempt_case()[0]
|
|
if change == "payload":
|
|
del invalid.row.payload["operation"]
|
|
elif change == "identity":
|
|
invalid.row.parent_revision_id = invalid.head.id
|
|
elif change == "membership":
|
|
invalid.rows[BaselineCatalogMembership] = []
|
|
else:
|
|
invalid.rows[BaselineCatalogRevision] = []
|
|
before = deepcopy(invalid.rows)
|
|
with pytest.raises(ValueError, match=f"^{code}$"):
|
|
render_catalog_revision(invalid, exact_selector())
|
|
with pytest.raises(ValueError, match=f"^{code}$"):
|
|
publish_baseline_catalog(invalid, selector=exact_selector(), expected_branch_head=HEAD,
|
|
idempotency_key="explicit-malformed-source", actor="fixture")
|
|
assert invalid.rows == before and invalid.commits == 0
|
|
|
|
|
|
def test_catalog_path_renders_aliases_and_rejects_bad_template():
|
|
from tests.services.dashboard_testing.test_baseline_catalog import CATALOG, REVISION
|
|
rendered = attempt_case()[-1]
|
|
assert rendered.path == f"catalogs/{CATALOG}/{REVISION}.yaml"
|
|
destination = PublicationDestination(base_url="https://git.test", repository="fixture/catalog",
|
|
branch="main", path=rendered.path)
|
|
assert destination.path == rendered.path
|
|
for invalid in ("../../foreign.yaml", "/catalogs/foreign.yaml", "catalogs/../foreign.yaml",
|
|
"catalogs/{unknown}/v1.json", "catalogs/ss-prod-visual/v1.json"):
|
|
with pytest.raises(ValueError, match="PUBLISH_DESTINATION_INVALID"):
|
|
PublicationDestination(base_url="https://git.test", repository="fixture/catalog",
|
|
branch="main", path=invalid)
|
|
# #endregion Test.Tooling.PublishCatalog.Validate
|
|
|
|
|
|
# #region Test.Tooling.PublishCatalog.Publish [C:3] [TYPE Function]
|
|
def test_publish_creates_when_absent_and_updates_with_sha():
|
|
_, _, _, _, target, rendered = attempt_case()
|
|
raw = rendered.content
|
|
create_client = _FakeClient(_FakeResponse(404), _FakeResponse(422, {"message": "[SHA]: Required"}),
|
|
_FakeResponse(201, {"content": {"path": target.path}}))
|
|
assert fetch_existing_sha(create_client, target) is None
|
|
result = publish_catalog_bytes(create_client, target, raw, "create")
|
|
assert result["content"]["path"] == target.path
|
|
assert not create_client.puts
|
|
assert len(create_client.posts) == 1
|
|
url, body = create_client.posts[0]
|
|
assert url == target.contents_url(target.path)
|
|
assert "sha" not in body
|
|
assert base64.b64decode(body["content"]) == raw
|
|
assert body["branch"] == "main" and body["message"] == "create"
|
|
assert all(params == {"ref": "main"} for _, params in create_client.gets)
|
|
|
|
for observed_sha in ("9" * 40, "a" * 64):
|
|
update_client = _FakeClient(_FakeResponse(200, {"sha": observed_sha}), _FakeResponse(200, {}))
|
|
assert fetch_existing_sha(update_client, target) == observed_sha
|
|
publish_catalog_bytes(update_client, target, raw, "update")
|
|
assert not update_client.posts
|
|
assert len(update_client.puts) == 1
|
|
assert update_client.puts[0][0] == target.contents_url(target.path)
|
|
assert update_client.puts[0][1]["sha"] == observed_sha
|
|
assert base64.b64decode(update_client.puts[0][1]["content"]) == raw
|
|
assert update_client.puts[0][1]["branch"] == "main"
|
|
assert update_client.puts[0][1]["message"] == "update"
|
|
|
|
|
|
def test_publish_failures_are_typed():
|
|
_, _, _, _, target, rendered = attempt_case()
|
|
for status, code in ((401, "PUBLISH_AUTH_FAILED"), (500, "PUBLISH_UNAVAILABLE")):
|
|
client = _FakeClient(_FakeResponse(status, text="private response"), _FakeResponse(200, {}))
|
|
with pytest.raises(PublishError) as raised:
|
|
publish_catalog_bytes(client, target, rendered.content, "unavailable")
|
|
assert raised.value.code == code
|
|
assert not client.puts and not client.posts
|
|
cases = (
|
|
(_FakeClient(_FakeResponse(200, {"sha": "b" * 40}), _FakeResponse(409)), "PUBLISH_CONFLICT", "PUT"),
|
|
(_FakeClient(_FakeResponse(404), _FakeResponse(200, {}),
|
|
_FakeResponse(422, {"message": "file already exists"}, text="file already exists")), "PUBLISH_CONFLICT", "POST"),
|
|
(_FakeClient(_FakeResponse(404), _FakeResponse(200, {}), _FakeResponse(401)), "PUBLISH_AUTH_FAILED", "POST"),
|
|
)
|
|
for client, code, method in cases:
|
|
with pytest.raises(PublishError) as raised:
|
|
publish_catalog_bytes(client, target, rendered.content, "typed failure")
|
|
assert raised.value.code == code
|
|
assert len(client.puts if method == "PUT" else client.posts) == 1
|
|
assert not (client.posts if method == "PUT" else client.puts)
|
|
# #endregion Test.Tooling.PublishCatalog.Publish
|
|
|
|
|
|
# #region Test.Tooling.PublishCatalog.Main [C:3] [TYPE Function]
|
|
# @TEST_INVARIANT Missing current configuration performs no HTTP or publication attempt; DB reads may validate the exact selector first.
|
|
@pytest.mark.parametrize("missing", ["PUBLISHED_CATALOG_BASE_URL", "PUBLISHED_CATALOG_REPO",
|
|
"PUBLISHED_CATALOG_REF", "PUBLISHED_CATALOG_TOKEN"])
|
|
def test_main_missing_config_exits_2_without_network(pending_publication, monkeypatch, missing):
|
|
db, selector, operation = pending_publication
|
|
operation_id, key = operation.id, operation.idempotency_key
|
|
count = db.query(PublicationOperation).count()
|
|
monkeypatch.delenv(missing)
|
|
|
|
def forbidden(*args, **kwargs):
|
|
pytest.fail("Missing publication configuration reached HTTP")
|
|
|
|
monkeypatch.setattr(httpx, "Client", forbidden)
|
|
with pytest.raises(PublicationError) as raised:
|
|
publish_baseline_catalog(db, selector=selector, expected_branch_head=HEAD,
|
|
idempotency_key=key, actor="fixture")
|
|
assert raised.value.code == "PUBLISH_SOURCE_UNCONFIGURED"
|
|
assert db.query(PublicationOperation).count() == count
|
|
assert _stored_state(db, operation_id) == ("publish_pending", None, None, None, 0)
|
|
|
|
|
|
# @TEST_INVARIANT Real PG-selected immutable revision supplies exact render; configured baseURL/Authorization and verified six-field receipt are mandatory.
|
|
def test_main_publishes_end_to_end_with_fake_client(pending_publication, monkeypatch):
|
|
db, selector, operation = pending_publication
|
|
before = load_catalog_revision(db, selector).revision.model_dump(mode="json")
|
|
rendered = render_catalog_revision(db, selector)
|
|
server = Server(rendered.content)
|
|
seen = {}
|
|
real_client = httpx.Client
|
|
|
|
def configured_client(**kwargs):
|
|
seen.update(kwargs)
|
|
return real_client(**kwargs)
|
|
|
|
monkeypatch.setattr(httpx, "Client", configured_client)
|
|
result = publish_baseline_catalog(db, selector=selector, expected_branch_head=HEAD,
|
|
idempotency_key=operation.idempotency_key, actor="fixture", transport=httpx.MockTransport(server.handler))
|
|
assert result["state"] == "published" and result["commit_sha"] == WRITTEN
|
|
assert seen["base_url"] == "https://git.test"
|
|
assert seen["headers"] == {"Authorization": "token offline-token"}
|
|
receipt = result["published_receipt"]
|
|
assert set(receipt) == {"catalog_revision_id", "render_sha256", "integrity_sha256", "commit_sha", "head_after", "verified_at"}
|
|
assert receipt["catalog_revision_id"] == selector.catalog_revision_id
|
|
assert receipt["render_sha256"] == rendered.render_sha256
|
|
assert receipt["integrity_sha256"] == load_catalog_revision(db, selector).integrity_sha256
|
|
assert receipt["commit_sha"] == receipt["head_after"] == WRITTEN and receipt["verified_at"]
|
|
assert len(server.writes) == 1 and server.content == rendered.content
|
|
assert load_catalog_revision(db, selector).revision.model_dump(mode="json") == before
|
|
assert _stored_state(db, operation.id)[0:3] == ("published", None, WRITTEN)
|
|
|
|
|
|
def test_main_creates_via_post_when_absent(pending_publication):
|
|
db, selector, operation = pending_publication
|
|
rendered = render_catalog_revision(db, selector)
|
|
server = Server(rendered.content)
|
|
writes = []
|
|
|
|
def observe(request):
|
|
assert str(request.url) == "https://git.test/api/v1/repos/fixture/catalog" or str(request.url).startswith("https://git.test/api/v1/repos/fixture/catalog/")
|
|
assert request.headers["Authorization"] == "token offline-token"
|
|
if request.method in {"POST", "PUT"}:
|
|
writes.append((request.method, request.url.path, json.loads(request.content)))
|
|
return server.handler(request)
|
|
|
|
result = publish_baseline_catalog(db, selector=selector, expected_branch_head=HEAD,
|
|
idempotency_key=operation.idempotency_key, actor="fixture", transport=httpx.MockTransport(observe))
|
|
assert result["state"] == "published" and result["commit_sha"] == WRITTEN
|
|
assert len(writes) == 1 and writes[0][0] == "POST" and "sha" not in writes[0][2]
|
|
assert writes[0][1].endswith("/contents/" + rendered.path)
|
|
assert base64.b64decode(writes[0][2]["content"]) == rendered.content
|
|
assert writes[0][2]["branch"] == "main"
|
|
assert writes[0][2]["message"].endswith(f"(publication {operation.id})")
|
|
assert result["published_receipt"]["catalog_revision_id"] == selector.catalog_revision_id
|
|
assert result["published_receipt"]["render_sha256"] == rendered.render_sha256
|
|
assert result["published_receipt"]["head_after"] == WRITTEN
|
|
assert _stored_state(db, operation.id)[3] == result["published_receipt"]
|
|
|
|
|
|
def test_main_types_transport_errors(pending_publication):
|
|
db, selector, operation = pending_publication
|
|
operation_id, key = operation.id, operation.idempotency_key
|
|
|
|
def unavailable(request):
|
|
if request.url.path == "/api/v1/repos/fixture/catalog":
|
|
return Server(b"").handler(request)
|
|
raise httpx.ConnectError("private transport error", request=request)
|
|
|
|
with pytest.raises(PublicationError) as raised:
|
|
publish_baseline_catalog(db, selector=selector, expected_branch_head=HEAD,
|
|
idempotency_key=key, actor="fixture", transport=httpx.MockTransport(unavailable))
|
|
assert raised.value.code == "PUBLISH_UNAVAILABLE"
|
|
assert _stored_state(db, operation_id) == ("publish_failed", "PUBLISH_UNAVAILABLE", None, None, 1)
|
|
# #endregion Test.Tooling.PublishCatalog.Main
|
|
# #endregion Test.Tooling.PublishCatalog
|