diff --git a/databusclient/api/deploy.py b/databusclient/api/deploy.py index 2c8cd081..2309279c 100644 --- a/databusclient/api/deploy.py +++ b/databusclient/api/deploy.py @@ -538,6 +538,9 @@ def deploy_from_metadata( apikey : str API key for authentication """ + if not metadata: + raise DeployError("Cannot deploy a dataset with no distribution metadata.") + distributions = create_distributions_from_metadata(metadata) dataset = create_dataset( diff --git a/databusclient/extensions/webdav.py b/databusclient/extensions/webdav.py index 7981a49c..ac01124b 100644 --- a/databusclient/extensions/webdav.py +++ b/databusclient/extensions/webdav.py @@ -9,10 +9,20 @@ import hashlib import os import posixpath +import shutil import subprocess from urllib.parse import quote, urljoin +class WebDAVUploadError(Exception): + """Raised when a requested WebDAV upload cannot be completed.""" + + def __init__(self, path: str, cause: Exception): + self.path = path + self.cause = cause + super().__init__(f"WebDAV upload failed for {path!r}: {cause}") + + def compute_sha256_and_length(filepath): """Compute the SHA-256 hex digest and total byte length of a file. @@ -63,20 +73,32 @@ def upload_to_webdav( Returns: A list of dicts with keys: ``filename``, ``checksum``, ``size``, ``url``. """ + if not shutil.which("rclone") and source_paths: + path = source_paths[0] + cause = FileNotFoundError("rclone not found on PATH") + raise WebDAVUploadError(path, cause) from cause + + remote_name = remote_name.rstrip(":") result = [] for path in source_paths: if not os.path.exists(path): - print(f"Path not found: {path}") - continue + cause = FileNotFoundError(f"Source path does not exist: {path}") + raise WebDAVUploadError(path, cause) from cause abs_path = os.path.abspath(path) basename = os.path.basename(abs_path) files = get_all_files(abs_path) + if not files: + cause = ValueError(f"Source path contains no files: {path}") + raise WebDAVUploadError(path, cause) from cause tmp_results = [] for file in files: - checksum, size = compute_sha256_and_length(file) + try: + checksum, size = compute_sha256_and_length(file) + except OSError as exc: + raise WebDAVUploadError(path, exc) from exc if os.path.isdir(path): rel_file = os.path.relpath(file, abs_path) @@ -116,8 +138,10 @@ def upload_to_webdav( result.extend(tmp_results) print("✅ Uploaded successfully.\n") except subprocess.CalledProcessError as e: - print(f"❌ Error uploading {path}: {e}\n") - except FileNotFoundError: - print("❌ rclone not found on PATH. Install rclone and retry.") + raise WebDAVUploadError(path, e) from e + except FileNotFoundError as exc: + raise WebDAVUploadError(path, exc) from exc + except OSError as exc: + raise WebDAVUploadError(path, exc) from exc return result diff --git a/tests/test_cand1_propagation.py b/tests/test_cand1_propagation.py new file mode 100644 index 00000000..93d1aa21 --- /dev/null +++ b/tests/test_cand1_propagation.py @@ -0,0 +1,89 @@ +"""CLI and workflow regression coverage for CAND-1 failure propagation.""" + +import json + +import pytest +from click.testing import CliRunner + +from databusclient.cli import app +from databusclient.extensions.webdav import WebDAVUploadError +from databusclient.manifest.context import ManifestContext +from databusclient.workflow.context import StepContext +from databusclient.workflow.engine import WorkflowEngine, WorkflowExecutionError + + +def test_cli_webdav_upload_failure_records_manifest_and_never_deploys( + monkeypatch, tmp_path +): + source = tmp_path / "source.ttl" + source.write_text("data") + manifest_path = tmp_path / "manifest.json" + error = WebDAVUploadError(str(source), OSError("rclone failed")) + deploy_calls = [] + + def fail_upload(*args, **kwargs): + raise error + + monkeypatch.setattr("databusclient.cli.webdav.upload_to_webdav", fail_upload) + monkeypatch.setattr( + "databusclient.cli.api_deploy.deploy_from_metadata", + lambda *args, **kwargs: deploy_calls.append(args), + ) + + result = CliRunner().invoke( + app, + [ + "deploy", "--version-id", "https://databus.example/a/g/x/1", + "--title", "T", "--abstract", "A", "--description", "D", + "--license", "https://license.example/", "--apikey", "secret", + "--webdav-url", "https://files.example/", "--remote", "remote", + "--path", "dataset", "--manifest", str(manifest_path), str(source), + ], + ) + + assert result.exit_code != 0 + assert "Successfully deployed" not in result.output + assert deploy_calls == [] + manifest = json.loads(manifest_path.read_text()) + assert "dbus:operationError" in manifest + assert manifest["dbus:executionResult"]["dbus:failed"] == 0 + assert manifest["dataid:distribution"]["dataid:file"] == [] + + +def test_workflow_webdav_upload_failure_fails_step_without_deploy_or_success_record( + monkeypatch, +): + error = WebDAVUploadError("/tmp/source.ttl", OSError("rclone failed")) + deploy_calls = [] + monkeypatch.setattr( + "databusclient.workflow.steps.webdav.upload_to_webdav", + lambda *args, **kwargs: (_ for _ in ()).throw(error), + ) + monkeypatch.setattr( + "databusclient.workflow.steps.deploy_from_metadata", + lambda *args, **kwargs: deploy_calls.append(args), + ) + manifest = ManifestContext(command="workflow") + engine = WorkflowEngine(context=StepContext(), manifest_context=manifest) + step = { + "name": "publish", + "command": "deploy", + "version_id": "https://databus.example/a/g/x/1", + "title": "T", + "abstract": "A", + "description": "D", + "license": "https://license.example/", + "api_key": "key", + "webdav_url": "https://files.example/", + "remote": "remote", + "path": "dataset", + "files": ["/tmp/source.ttl"], + } + + with pytest.raises(WorkflowExecutionError, match="Step 'publish' failed"): + engine.run([step]) + + assert engine.results[0].status == "failed" + assert deploy_calls == [] + assert [entry["status"] for entry in manifest.files] == ["failed"] + assert all(entry["status"] != "success" for entry in manifest.files) diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 679f11fe..4bfef37b 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -1,96 +1,61 @@ -"""Client tests""" - -from collections import OrderedDict +"""Client tests for deploy helpers.""" import pytest from databusclient.api.deploy import ( + BadArgumentException, + _get_content_variants, create_dataset, create_distribution, get_file_info, - _get_content_variants, - BadArgumentException, ) EXAMPLE_URL = "https://raw.githubusercontent.com/dbpedia/databus/608482875276ef5df00f2360a2f81005e62b58bd/server/app/api/swagger.yml" def test_get_content_variants(): - # With content variants cvs = _get_content_variants( "https://example.com/file.ttl|lang=en_type=parsed|ttl|none|sha256hash|12345" ) - assert cvs == { - "lang": "en", - "type": "parsed", - } - - # Without content variants - cvs = _get_content_variants( - "https://example.com/file.ttl||ttl|none|sha256hash|12345" - ) - assert cvs == {} + assert cvs == {"lang": "en", "type": "parsed"} + assert _get_content_variants("https://example.com/file.ttl||ttl|none|sha256hash|12345") == {} + assert _get_content_variants("https://example.com/file.ttl") == {} - csv = _get_content_variants("https://example.com/file.ttl") - assert csv == {} - - # Wrong format with pytest.raises(BadArgumentException): - _ = _get_content_variants("https://example.com/file.ttl|invalidformat") + _get_content_variants("https://example.com/file.ttl|invalidformat") -@pytest.mark.skip(reason="temporarily disabled since code needs fixing") def test_distribution_cases(): - metadata_args_with_filler = OrderedDict() - - metadata_args_with_filler["type=config_source=databus"] = "" - metadata_args_with_filler["yml"] = None - metadata_args_with_filler["none"] = None - metadata_args_with_filler[ - "79582a2a7712c0ce78a74bb55b253dc2064931364cf9c17c827370edf9b7e4f1:56737" - ] = None - - # test by leaving out an argument each - artifact_name = "databusclient-pytest" - uri = "https://raw.githubusercontent.com/dbpedia/databus/master/server/app/api/swagger.yml" - parameters = list(metadata_args_with_filler.keys()) - - for i in range(0, len(metadata_args_with_filler.keys())): - if i == 1: - continue - - dst_string = f"{uri}" - for j in range(0, len(metadata_args_with_filler.keys())): - if j == i: - replacement = metadata_args_with_filler[parameters[j]] - if replacement is None: - pass - else: - dst_string += f"|{replacement}" - else: - dst_string += f"|{parameters[j]}" - - print(f"{dst_string=}") - ( - name, + cases = [ + "https://example.org/file.yml|lang=en_type=parsed|json|none|abc123:45678", + "https://example.org/file.json||json|none|def456:123", + "https://example.org/file.ttl|lang=de|ttl|bz2|789abc:9876", + ] + + for distribution in cases: + cvs, file_format, compression, checksum, size = get_file_info(distribution) + recreated = create_distribution( + distribution.split("|")[0], cvs, - formatExtension, + file_format, compression, - sha256sum, - content_length, - ) = get_file_info(artifact_name, dst_string) - - created_dst_str = create_distribution( - uri, cvs, formatExtension, compression, (sha256sum, content_length) + (checksum, size), ) - - assert dst_string == created_dst_str + assert recreated == distribution -@pytest.mark.skip(reason="temporarily disabled since code needs fixing") def test_empty_cvs(): - dst = [create_distribution(url=EXAMPLE_URL, cvs={})] - + checksum = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + size = 59986 + dst = [ + create_distribution( + url=EXAMPLE_URL, + cvs={}, + file_format="yml", + compression="none", + sha256_length_tuple=(checksum, size), + ) + ] dataset = create_dataset( version_id="https://dev.databus.dbpedia.org/user/group/artifact/1970.01.01/", artifact_version_title="Test Title", @@ -104,8 +69,15 @@ def test_empty_cvs(): "@context": "https://downloads.dbpedia.org/databus/context.jsonld", "@graph": [ { - "@type": "Dataset", - "@id": "https://dev.databus.dbpedia.org/user/group/artifact/1970.01.01#Dataset", + "@id": "https://dev.databus.dbpedia.org/user/group/artifact", + "@type": "Artifact", + "title": "Test Title", + "abstract": "Test abstract blabla", + "description": "Test description blabla", + }, + { + "@type": ["Version", "Dataset"], + "@id": "https://dev.databus.dbpedia.org/user/group/artifact/1970.01.01", "hasVersion": "1970.01.01", "title": "Test Title", "abstract": "Test abstract blabla", @@ -113,17 +85,15 @@ def test_empty_cvs(): "license": "https://license.url/test/", "distribution": [ { - "@id": "https://dev.databus.dbpedia.org/user/group/artifact/1970.01.01#artifact.yml", "@type": "Part", - "file": "https://dev.databus.dbpedia.org/user/group/artifact/1970.01.01/artifact.yml", "formatExtension": "yml", "compression": "none", "downloadURL": EXAMPLE_URL, - "byteSize": 59986, - "sha256sum": "088e6161bf8b4861bdd4e9f517be4441b35a15346cb9d2d3c6d2e3d6cd412030", + "byteSize": size, + "sha256sum": checksum, } ], - } + }, ], } diff --git a/tests/test_deploy_metadata_guard.py b/tests/test_deploy_metadata_guard.py new file mode 100644 index 00000000..4149d686 --- /dev/null +++ b/tests/test_deploy_metadata_guard.py @@ -0,0 +1,30 @@ +"""Regression tests for refusing deployments without file metadata.""" + +import pytest + +from databusclient.api import deploy as deploy_api + + +@pytest.mark.parametrize("metadata", [None, []]) +def test_deploy_from_metadata_rejects_empty_metadata_before_publish( + monkeypatch, metadata +): + calls = [] + monkeypatch.setattr(deploy_api, "deploy", lambda *args: calls.append(args)) + + with pytest.raises(deploy_api.DeployError, match="no distribution metadata"): + deploy_api.deploy_from_metadata( + metadata, + "https://databus.example/account/group/artifact/1", + "title", + "abstract", + "description", + "https://license.example/", + "api-key", + ) + + assert calls == [] + + +def test_empty_metadata_converter_remains_empty(): + assert deploy_api.create_distributions_from_metadata([]) == [] diff --git a/tests/test_download.py b/tests/test_download.py index b1746d38..7f00da2a 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -2,7 +2,6 @@ import bz2 -import pytest import requests from click.testing import CliRunner @@ -59,14 +58,33 @@ def test_with_query(): api_download("tmp", DEFAULT_ENDPOINT, [TEST_QUERY]) -@pytest.mark.skip( - reason="Live collection download is long-running and flakes on network timeouts" -) -@pytest.mark.skip( - reason="Integration test: requires live databus.dbpedia.org connection" -) -def test_with_collection(): - api_download("tmp", DEFAULT_ENDPOINT, [TEST_COLLECTION]) +def test_with_collection(monkeypatch, tmp_path): + """Collection routing is exercised with mocked SPARQL and file downloads.""" + import databusclient.api.download as dl + + query = "SELECT ?file WHERE { ?file ?p ?o }" + urls = {"https://files.example/a.ttl", "https://files.example/b.ttl"} + captured = {} + + monkeypatch.setattr( + dl, "_get_sparql_query_of_collection", lambda uri, **kwargs: query + ) + monkeypatch.setattr( + dl, + "_get_file_download_urls_from_sparql_query", + lambda endpoint, actual_query, **kwargs: urls, + ) + + def fake_download_files(file_urls, local_dir, **kwargs): + captured["file_urls"] = file_urls + captured["local_dir"] = local_dir + + monkeypatch.setattr(dl, "_download_files", fake_download_files) + + api_download(str(tmp_path), DEFAULT_ENDPOINT, [TEST_COLLECTION]) + + assert set(captured["file_urls"]) == urls + assert captured["local_dir"] == str(tmp_path) def test_404_records_failed_manifest_entry(monkeypatch): diff --git a/tests/test_webdav.py b/tests/test_webdav.py new file mode 100644 index 00000000..299a6708 --- /dev/null +++ b/tests/test_webdav.py @@ -0,0 +1,190 @@ +"""Regression tests for fail-fast WebDAV uploads.""" + +import subprocess + +import pytest + +from databusclient.extensions import webdav + + +@pytest.fixture(autouse=True) +def rclone_is_available(monkeypatch): + monkeypatch.setattr(webdav.shutil, "which", lambda _name: "/usr/bin/rclone") + + +def test_upload_success_returns_metadata_after_rclone_succeeds(tmp_path, monkeypatch): + source = tmp_path / "data.ttl" + source.write_bytes(b"payload") + calls = [] + monkeypatch.setattr(webdav.subprocess, "run", lambda command, check: calls.append(command)) + + metadata = webdav.upload_to_webdav( + [str(source)], "remote:", "dataset", "https://files.example/" + ) + + assert len(calls) == 1 + assert calls[0][3] == "remote:dataset/data.ttl" + assert metadata == [ + { + "filename": "data.ttl", + "checksum": "239f59ed55e737c77147cf55ad0c1b030b6d7ee748a7426952f9b852d5a935e5", + "size": 7, + "url": "https://files.example/dataset/data.ttl", + } + ] + + +def test_missing_rclone_fails_before_hashing_any_source_or_subprocess( + tmp_path, monkeypatch +): + sources = [tmp_path / "first.ttl", tmp_path / "second.ttl"] + for source in sources: + source.write_bytes(b"payload") + monkeypatch.setattr(webdav.shutil, "which", lambda _name: None) + checksum_calls = [] + subprocess_calls = [] + monkeypatch.setattr( + webdav, + "compute_sha256_and_length", + lambda path: checksum_calls.append(path), + ) + monkeypatch.setattr( + webdav.subprocess, "run", lambda *args, **kwargs: subprocess_calls.append(args) + ) + + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [str(source) for source in sources], + "remote", + "dataset", + "https://files.example/", + ) + + assert caught.value.path == str(sources[0]) + assert isinstance(caught.value.cause, FileNotFoundError) + assert caught.value.__cause__ is caught.value.cause + assert checksum_calls == [] + assert subprocess_calls == [] + + +@pytest.mark.parametrize( + "failure", + [ + FileNotFoundError("rclone missing"), + subprocess.CalledProcessError(1, ["rclone", "copyto"]), + ], +) +def test_upload_rclone_failures_raise_with_path_and_cause( + tmp_path, monkeypatch, failure +): + source = tmp_path / "data.ttl" + source.write_bytes(b"payload") + + def fail(*args, **kwargs): + raise failure + + monkeypatch.setattr(webdav.subprocess, "run", fail) + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [str(source)], "remote", "dataset", "https://files.example/" + ) + + assert caught.value.path == str(source) + assert caught.value.cause is failure + assert caught.value.__cause__ is failure + + +def test_upload_subprocess_oserror_is_wrapped_with_path_and_cause( + tmp_path, monkeypatch +): + source = tmp_path / "data.ttl" + source.write_bytes(b"payload") + cause = PermissionError("operation not permitted") + + def fail(*args, **kwargs): + raise cause + + monkeypatch.setattr(webdav.subprocess, "run", fail) + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [str(source)], "remote", "dataset", "https://files.example/" + ) + + assert caught.value.path == str(source) + assert caught.value.cause is cause + assert caught.value.__cause__ is cause + + +def test_missing_source_raises_before_rclone(tmp_path, monkeypatch): + calls = [] + monkeypatch.setattr(webdav.subprocess, "run", lambda *a, **k: calls.append(a)) + missing = str(tmp_path / "missing.ttl") + + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [missing], "remote", "dataset", "https://files.example/" + ) + + assert caught.value.path == missing + assert isinstance(caught.value.cause, FileNotFoundError) + assert calls == [] + + +def test_empty_directory_raises_before_rclone(tmp_path, monkeypatch): + empty_dir = tmp_path / "empty" + empty_dir.mkdir() + calls = [] + monkeypatch.setattr(webdav.subprocess, "run", lambda *a, **k: calls.append(a)) + + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [str(empty_dir)], "remote", "dataset", "https://files.example/" + ) + + assert caught.value.path == str(empty_dir) + assert isinstance(caught.value.cause, ValueError) + assert calls == [] + + +def test_partial_upload_failure_raises_and_does_not_return_metadata( + tmp_path, monkeypatch +): + first = tmp_path / "first.ttl" + second = tmp_path / "second.ttl" + first.write_bytes(b"first") + second.write_bytes(b"second") + calls = 0 + + def fail_second(*args, **kwargs): + nonlocal calls + calls += 1 + if calls == 2: + raise subprocess.CalledProcessError(1, args[0]) + + monkeypatch.setattr(webdav.subprocess, "run", fail_second) + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [str(first), str(second)], "remote", "dataset", "https://files.example/" + ) + + assert caught.value.path == str(second) + assert calls == 2 + + +def test_checksum_oserror_is_wrapped_with_source_path(tmp_path, monkeypatch): + source = tmp_path / "data.ttl" + source.write_bytes(b"payload") + cause = PermissionError("permission denied") + + def fail_checksum(_path): + raise cause + + monkeypatch.setattr(webdav, "compute_sha256_and_length", fail_checksum) + with pytest.raises(webdav.WebDAVUploadError) as caught: + webdav.upload_to_webdav( + [str(source)], "remote", "dataset", "https://files.example/" + ) + + assert caught.value.path == str(source) + assert caught.value.cause is cause + assert caught.value.__cause__ is cause