Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
225 changes: 225 additions & 0 deletions tests/test_delete_resource.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
"""Offline tests for _delete_resource, _delete_artifact and delete() in api/delete.py.

No network: requests.delete and fetch_databus_jsonld are replaced with fakes.
"""

import json

import pytest

from databusclient.api import delete as delmod

HOST = "https://databus.dbpedia.org"
GROUP = f"{HOST}/acc/group"
ARTIFACT = f"{GROUP}/artifact"
VERSION = f"{ARTIFACT}/2024.01.01"
FILE = f"{VERSION}/artifact.ttl"
COLLECTION = f"{HOST}/acc/collections/my-collection"


class FakeResponse:
def __init__(self, status_code, text=""):
self.status_code = status_code
self.text = text


class FakeManifest:
def __init__(self):
self.records = []

def record_file(self, url, status, **kwargs):
self.records.append((url, status))


@pytest.fixture
def http_calls(monkeypatch):
"""Record every requests.delete call and answer with 204 by default."""
calls = []
state = {"response": FakeResponse(204)}

def fake_delete(url, headers=None, timeout=None):
calls.append({"url": url, "headers": headers, "timeout": timeout})
return state["response"]

monkeypatch.setattr(delmod.requests, "delete", fake_delete)
return calls, state


# _delete_resource


def test_delete_resource_sends_delete_with_api_key(http_calls):
calls, _ = http_calls
delmod._delete_resource(VERSION, "secret", force=True)

assert len(calls) == 1
assert calls[0]["url"] == VERSION
assert calls[0]["headers"] == {"accept": "*/*", "X-API-KEY": "secret"}
assert calls[0]["timeout"] == 30


@pytest.mark.parametrize("status", [200, 204])
def test_delete_resource_success_records_manifest(http_calls, status):
calls, state = http_calls
state["response"] = FakeResponse(status)
manifest = FakeManifest()

delmod._delete_resource(VERSION, "secret", force=True, manifest_context=manifest)

assert manifest.records == [(VERSION, "success")]


def test_delete_resource_error_status_raises(http_calls):
_, state = http_calls
state["response"] = FakeResponse(403, "Forbidden")

with pytest.raises(Exception, match="403 - Forbidden"):
delmod._delete_resource(VERSION, "secret", force=True)


def test_delete_resource_dry_run_sends_nothing(http_calls):
calls, _ = http_calls
manifest = FakeManifest()

delmod._delete_resource(VERSION, "secret", dry_run=True, manifest_context=manifest)

assert calls == []
assert manifest.records == [(VERSION, "dry_run")]


def test_delete_resource_with_queue_only_queues(http_calls):
calls, _ = http_calls
queue = delmod.DeleteQueue("secret")

delmod._delete_resource(VERSION, "secret", force=True, queue=queue)

assert calls == []
assert queue.queue == {VERSION}


def test_delete_resource_without_key_raises(http_calls):
calls, _ = http_calls
with pytest.raises(ValueError, match="API key"):
delmod._delete_resource(VERSION, None, force=True)
assert calls == []


def test_delete_resource_skip_answer_sends_nothing(http_calls, monkeypatch):
calls, _ = http_calls
monkeypatch.setattr(delmod, "_confirm_delete", lambda uri: "skip")

delmod._delete_resource(VERSION, "secret")

assert calls == []


def test_delete_resource_cancel_answer_raises(http_calls, monkeypatch):
calls, _ = http_calls
monkeypatch.setattr(delmod, "_confirm_delete", lambda uri: "cancel")

with pytest.raises(KeyboardInterrupt):
delmod._delete_resource(VERSION, "secret")
assert calls == []


def test_delete_resource_confirm_answer_deletes(http_calls, monkeypatch):
calls, _ = http_calls
monkeypatch.setattr(delmod, "_confirm_delete", lambda uri: "confirm")

delmod._delete_resource(VERSION, "secret")

assert [c["url"] for c in calls] == [VERSION]


def test_delete_resource_force_does_not_ask(http_calls, monkeypatch):
def fail(uri):
raise AssertionError("must not ask when force=True")

monkeypatch.setattr(delmod, "_confirm_delete", fail)
delmod._delete_resource(VERSION, "secret", force=True)


# _delete_artifact


def _run_delete_artifact(monkeypatch, versions_payload):
body = {} if versions_payload is ... else {"databus:hasVersion": versions_payload}
monkeypatch.setattr(
delmod, "fetch_databus_jsonld", lambda *a, **k: json.dumps(body)
)
deleted = []
monkeypatch.setattr(
delmod, "_delete_resource", lambda uri, *a, **k: deleted.append(uri)
)
delmod._delete_artifact(ARTIFACT, "secret", force=True)
return deleted


def test_delete_artifact_single_version_dict(monkeypatch):
deleted = _run_delete_artifact(monkeypatch, {"@id": VERSION})
assert deleted == [VERSION, ARTIFACT]


def test_delete_artifact_multiple_versions_then_artifact(monkeypatch):
v2 = f"{ARTIFACT}/2024.02.01"
deleted = _run_delete_artifact(monkeypatch, [{"@id": VERSION}, {"@id": v2}])
assert deleted == [VERSION, v2, ARTIFACT]


def test_delete_artifact_without_versions_deletes_artifact_only(monkeypatch):
deleted = _run_delete_artifact(monkeypatch, ...)
assert deleted == [ARTIFACT]


def test_delete_artifact_versions_without_id_are_skipped(monkeypatch):
deleted = _run_delete_artifact(monkeypatch, [{"name": "no id here"}])
assert deleted == [ARTIFACT]


# delete() dispatch


@pytest.fixture
def dispatch(monkeypatch):
"""Replace the per-level helpers and record which one delete() picks."""
picked = []
for name in ("_delete_resource", "_delete_artifact", "_delete_group"):
monkeypatch.setattr(
delmod,
name,
lambda uri, *a, _name=name, **k: picked.append((_name, uri)),
)
return picked


@pytest.mark.parametrize(
"uri, helper",
[
(COLLECTION, "_delete_resource"),
(VERSION, "_delete_resource"),
(ARTIFACT, "_delete_artifact"),
(GROUP, "_delete_group"),
],
)
def test_delete_dispatches_by_uri_level(dispatch, uri, helper):
delmod.delete([uri], "secret", dry_run=False, force=True)
assert dispatch == [(helper, uri)]


@pytest.mark.parametrize("uri", [FILE, f"{HOST}/acc"])
def test_delete_unsupported_uri_does_nothing(dispatch, uri):
delmod.delete([uri], "secret", dry_run=False, force=True)
assert dispatch == []


def test_delete_runs_queue_deepest_first(monkeypatch, http_calls):
calls, _ = http_calls
monkeypatch.setattr(
delmod,
"fetch_databus_jsonld",
lambda *a, **k: json.dumps({"databus:hasVersion": {"@id": VERSION}}),
)

delmod.delete([ARTIFACT], "secret", dry_run=False, force=True)

assert [c["url"] for c in calls] == [VERSION, ARTIFACT]
Loading