Skip to content
Open
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions databusclient/api/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
36 changes: 30 additions & 6 deletions databusclient/extensions/webdav.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
89 changes: 89 additions & 0 deletions tests/test_cand1_propagation.py
Original file line number Diff line number Diff line change
@@ -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)
116 changes: 43 additions & 73 deletions tests/test_deploy.py
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -104,26 +69,31 @@ 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",
"description": "Test description blabla",
"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,
}
],
}
},
],
}

Expand Down
30 changes: 30 additions & 0 deletions tests/test_deploy_metadata_guard.py
Original file line number Diff line number Diff line change
@@ -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([]) == []
Loading
Loading