Files
2026-11-11 14:56:29 +01:00

579 lines
22 KiB
Python

from decimal import Decimal
from typing import (
Any,
cast,
)
import pytest
from pydantic import ValidationError
from galaxy.datatypes.registry import example_datatype_registry_for_sample
from galaxy.model import (
Dataset,
DatasetCollection,
DatasetCollectionElement,
DatasetSource,
HistoryDatasetAssociation,
ImplicitlyConvertedDatasetAssociation,
set_datatypes_registry,
)
from galaxy.tool_util.parameters.convert import runtimeify
from galaxy.tool_util.parameters.state import JobInternalToolState
from galaxy.tool_util_models.parameters import (
build_collection_model_for_type,
DataCollectionListRuntime,
DataCollectionPairedOrUnpairedRuntime,
DataCollectionPairedRuntime,
DataCollectionRecordRuntime,
DataCollectionSampleSheetRuntime,
DataInternalJson,
DataParameterModel,
DataRequestInternalHda,
ToolParameterBundleModel,
)
from galaxy.tools.evaluation import UserToolEvaluator
from galaxy.tools.runtime import (
_validate_collection_runtime_dict,
collection_to_runtime,
setup_for_runtimeify,
)
from galaxy.util.bunch import Bunch
from galaxy.workflow.modules import to_cwl
@pytest.fixture
def mock_adapt_dataset():
def adapt(request):
return DataInternalJson(
**{
"class": "File",
"location": f"step_input://{request.id}",
"format": "txt",
"path": f"/path/to/{request.id}",
"size": 100,
"listing": [],
"basename": f"file_{request.id}.txt",
"nameroot": f"file_{request.id}",
"nameext": "txt",
}
)
return adapt
def create_model_collection(collection_type, elements_data):
# Create collection using real model
collection = DatasetCollection(collection_type=collection_type)
# Manually initialize list for in-memory relationship if needed
if not hasattr(collection, "elements"):
collection.elements = []
for i, (name, content) in enumerate(elements_data):
if isinstance(content, list): # Nested collection [type, elements]
child_collection = create_model_collection(content[0], content[1])
dce = DatasetCollectionElement(
collection=collection, element_identifier=name, element_index=i, element=child_collection
)
else: # HDA
hda = HistoryDatasetAssociation(create_dataset=True, flush=False, name=content)
hda.id = i + 100 # Fake ID for testing
# Also satisfy accessing hda.dataset.created_from_basename or hda.name in generic adapt if needed
assert hda.dataset is not None
hda.dataset.id = i + 1000
dce = DatasetCollectionElement(collection=collection, element_identifier=name, element_index=i, element=hda)
# SA relationship may handle append if active, but let's check.
# If we double-append, we get duplicates.
# If we don't append and SA mocks aren't active, we get empty.
# Safe approach: check if in list
if dce not in collection.elements:
collection.elements.append(dce)
return collection
def test_collection_to_runtime_paired(mock_adapt_dataset):
# Paired collection
collection = create_model_collection("paired", [("forward", "hda1"), ("reverse", "hda2")])
runtime = collection_to_runtime(
collection, name="test_paired", tags=["t1"], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
assert isinstance(runtime, DataCollectionPairedRuntime)
assert runtime.collection_type == "paired"
# DataCollectionPairedRuntime.elements is an object with forward/reverse fields
assert runtime.elements.forward.class_ == "File"
assert runtime.elements.reverse.class_ == "File"
def test_collection_to_runtime_list(mock_adapt_dataset):
# List collection
collection = create_model_collection("list", [("e1", "hda1"), ("e2", "hda2")])
runtime = collection_to_runtime(
collection, name="test_list", tags=[], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
assert isinstance(runtime, DataCollectionListRuntime)
assert runtime.collection_type == "list"
assert len(runtime.elements) == 2
assert runtime.elements[0].element_identifier == "e1"
def test_collection_to_runtime_nested(mock_adapt_dataset):
# Nested list:paired
paired_data = ["paired", [("forward", "hda1"), ("reverse", "hda2")]]
collection = create_model_collection("list:paired", [("p1", paired_data)])
runtime = collection_to_runtime(
collection, name="test_nested", tags=[], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
expected_model = build_collection_model_for_type("list:paired")
assert expected_model is not None
assert isinstance(runtime, expected_model)
assert type(runtime).__name__ == "DynamicCollection_list_paired"
assert runtime.collection_type == "list:paired"
assert hasattr(runtime, "elements")
assert len(runtime.elements) == 1
inner = runtime.elements[0]
assert isinstance(inner, DataCollectionPairedRuntime)
assert inner.elements.forward.class_ == "File"
def test_collection_to_runtime_invalid_paired(mock_adapt_dataset):
# Paired collection missing reverse
collection = create_model_collection("paired", [("forward", "hda1")])
# Should raise ValidationError because DataCollectionPairedRuntime requires forward and reverse
with pytest.raises(ValidationError):
collection_to_runtime(
collection, name="bad_paired", tags=[], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
def test_collection_to_runtime_record(mock_adapt_dataset):
# Record collection
collection = create_model_collection("record", [("f1", "hda1"), ("f2", "hda2")])
collection.fields = [{"name": "f1", "type": "File"}, {"name": "f2", "type": "File"}]
runtime = collection_to_runtime(
collection, name="test_record", tags=[], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
assert isinstance(runtime, DataCollectionRecordRuntime)
assert runtime.collection_type == "record"
assert runtime.elements["f1"].class_ == "File"
assert runtime.elements["f2"].class_ == "File"
def test_collection_to_runtime_sample_sheet(mock_adapt_dataset):
# Sample sheet -> List runtime
collection = create_model_collection("sample_sheet", [("s1", "hda1"), ("s2", "hda2")])
collection.column_definitions = [{"name": "cond", "type": "str"}]
# Mock elements should have columns
for ele in collection.elements:
ele.columns = ["treatment"]
runtime = collection_to_runtime(
collection, name="test_sheet", tags=[], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
# Should use DataCollectionSampleSheetRuntime to preserve metadata
assert isinstance(runtime, DataCollectionSampleSheetRuntime)
assert runtime.collection_type == "sample_sheet"
assert runtime.column_definitions is not None
assert runtime.elements[0].columns == ["treatment"]
def test_collection_to_runtime_paired_or_unpaired(mock_adapt_dataset):
# Paired mode
collection = create_model_collection("paired_or_unpaired", [("forward", "hda1"), ("reverse", "hda2")])
collection.has_single_item = False
runtime = collection_to_runtime(
collection, name="test_pou_paired", tags=[], adapt_dataset=mock_adapt_dataset, compute_environment=None
)
assert isinstance(runtime, DataCollectionPairedOrUnpairedRuntime)
assert runtime.elements["forward"].class_ == "File"
# Unpaired mode
collection_unpaired = create_model_collection("paired_or_unpaired", [("unpaired", "hda3")])
collection_unpaired.has_single_item = True
runtime_unpaired = collection_to_runtime(
collection_unpaired,
name="test_pou_unpaired",
tags=[],
adapt_dataset=mock_adapt_dataset,
compute_environment=None,
)
assert isinstance(runtime_unpaired, DataCollectionPairedOrUnpairedRuntime)
assert runtime_unpaired.elements["unpaired"].class_ == "File"
def test_collection_to_runtime_deeply_nested(mock_adapt_dataset):
"""End-to-end: list:list:paired through collection_to_runtime pipeline."""
paired_data = ["paired", [("forward", "hda1"), ("reverse", "hda2")]]
list_paired_data = ["list:paired", [("p1", paired_data)]]
collection = create_model_collection("list:list:paired", [("batch1", list_paired_data)])
runtime = collection_to_runtime(
collection,
name="test_deeply_nested",
tags=[],
adapt_dataset=mock_adapt_dataset,
compute_environment=None,
)
expected_model = build_collection_model_for_type("list:list:paired")
assert expected_model is not None
assert isinstance(runtime, expected_model)
assert runtime.collection_type == "list:list:paired"
assert hasattr(runtime, "elements")
assert len(runtime.elements) == 1
middle = runtime.elements[0]
expected_middle = build_collection_model_for_type("list:paired")
assert expected_middle is not None
assert isinstance(middle, expected_middle)
assert hasattr(middle, "elements")
assert middle.collection_type == "list:paired"
assert len(middle.elements) == 1
inner = middle.elements[0]
assert isinstance(inner, DataCollectionPairedRuntime)
assert inner.elements.forward.class_ == "File"
def test_validate_collection_runtime_dict_rejects_unknown_leaf():
"""Unknown leaf collection_type raises ValueError."""
raw = {"class": "Collection", "name": "x", "collection_type": "banana", "tags": [], "elements": []}
with pytest.raises(ValueError, match="Cannot build runtime model"):
_validate_collection_runtime_dict(raw)
def test_validate_collection_runtime_dict_rejects_unknown_nested():
"""Unknown nested collection_type raises ValueError."""
raw = {"class": "Collection", "name": "x", "collection_type": "list:banana", "tags": [], "elements": []}
with pytest.raises(ValueError, match="Cannot build runtime model"):
_validate_collection_runtime_dict(raw)
class RewritingComputeEnvironment:
def input_path_rewrite(self, dataset):
return f"/job/inputs/dataset_{dataset.id}.dat"
def input_extra_files_rewrite(self, dataset):
return f"/job/inputs/dataset_{dataset.id}_files"
class DatatypesApp:
def __init__(self, datatypes_registry):
self.datatypes_registry = datatypes_registry
def _adapt_input(
extension, deferred_uri=None, metadata=None, deferred=False, shell_quotable=False, extra_files_path=None
):
registry = example_datatype_registry_for_sample()
set_datatypes_registry(registry)
hda = HistoryDatasetAssociation(create_dataset=True, flush=False, name="input", extension=extension)
hda.id = 1
assert hda.dataset is not None
hda.dataset.file_size = Decimal(4)
hda.dataset.external_extra_files_path = extra_files_path or "/nonexistent/dataset_1_files"
for name, value in (metadata or {}).items():
setattr(hda.metadata, name, value)
if deferred or deferred_uri:
hda.dataset.state = Dataset.states.DEFERRED
if deferred_uri:
hda.dataset.sources = [DatasetSource(source_uri=deferred_uri)]
_, adapt_dataset, _ = setup_for_runtimeify(
cast(Any, DatatypesApp(registry)),
cast(Any, RewritingComputeEnvironment()),
{"input": hda},
shell_quotable=shell_quotable,
)
return adapt_dataset(DataRequestInternalHda(src="hda", id=1), [extension])
def test_adapt_dataset_file():
result = _adapt_input("txt")
assert result.class_ == "File"
assert result.path == "/job/inputs/dataset_1.dat"
assert result.extra_files_path is None
@pytest.mark.parametrize("extension", ["pbed", "blastdbn"])
def test_adapt_dataset_with_extra_files(extension, tmp_path):
result = _adapt_input(extension, extra_files_path=str(tmp_path))
assert result.class_ == "File"
assert result.path == "/job/inputs/dataset_1.dat"
assert result.extra_files_path == "/job/inputs/dataset_1_files"
@pytest.mark.parametrize("extension", ["directory", "zarr", "ome_zarr"])
def test_adapt_dataset_directory_datatypes(extension):
result = _adapt_input(extension)
assert result.class_ == "Directory"
assert result.path == "/job/inputs/dataset_1_files"
assert result.format == extension
@pytest.mark.parametrize("extension", ["zarr", "ome_zarr"])
def test_adapt_dataset_zarr_store_in_a_recorded_wrapper_folder(extension, tmp_path):
# Datasets created before stores were moved to the root are left as they are.
result = _adapt_input(extension, metadata={"store_root": "wrapped.zarr"}, extra_files_path=str(tmp_path))
assert result.path == "/job/inputs/dataset_1_files/wrapped.zarr"
assert result.extra_files_path == "/job/inputs/dataset_1_files"
@pytest.mark.parametrize(
"store_root",
[
"my store.zarr",
"sample (1).zarr",
"data+v2.zarr",
".hidden.zarr",
"..sample.zarr",
"...zarr",
"données.zarr",
"-x.zarr",
"tab\tbed.zarr",
],
)
def test_adapt_dataset_store_root_named_after_an_upload(store_root):
# store_root is the name of the folder an older dataset was uploaded in, whatever that was.
result = _adapt_input("zarr", metadata={"store_root": store_root}, shell_quotable=True)
assert result.path == f"/job/inputs/dataset_1_files/{store_root}"
@pytest.mark.parametrize(
"store_root",
[
"a';touch pwned;'.zarr",
"$(id).zarr",
'a"b.zarr',
"a`id`.zarr",
"a\\b",
"a\nb",
"a;id;.zarr",
"a&&id.zarr",
"a|id.zarr",
"a>out.zarr",
"a<in.zarr",
],
)
def test_adapt_dataset_rejects_a_store_root_that_cannot_be_quoted(store_root):
# A shell_command pastes the path in unescaped, so it must not end or escape a quoted value,
# nor start another command where the tool leaves it unquoted.
with pytest.raises(ValueError, match="cannot be passed to a tool"):
_adapt_input("zarr", metadata={"store_root": store_root}, shell_quotable=True)
def test_adapt_dataset_store_root_with_a_quote_for_escaped_arguments():
# base_command arguments are shell-escaped, so any folder name inside the dataset works there.
result = _adapt_input("zarr", metadata={"store_root": "Bob's store.zarr"})
assert result.path == "/job/inputs/dataset_1_files/Bob's store.zarr"
@pytest.mark.parametrize("store_root", ["../elsewhere", "/etc"])
def test_adapt_dataset_rejects_a_store_root_outside_the_dataset(store_root):
with pytest.raises(ValueError, match="outside"):
_adapt_input("zarr", metadata={"store_root": store_root})
def test_adapt_dataset_deferred_input_has_location_and_no_path():
result = _adapt_input("directory", deferred_uri="https://example.org/data/folder")
assert result.class_ == "Directory"
assert result.location == "https://example.org/data/folder"
assert result.path is None
assert result.extra_files_path is None
def test_adapt_dataset_deferred_input_without_a_source_is_rejected():
with pytest.raises(ValueError, match="has no source"):
_adapt_input("directory", deferred=True)
@pytest.mark.parametrize("extension", ["directory", "zarr"])
def test_to_cwl_directory_datatypes(extension):
# Tools run through /api/tools have no validated state and fall back to to_cwl.
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, extension)
properties = to_cwl(hda, [], compute_environment=cast(Any, RewritingComputeEnvironment()))
assert properties["class"] == "Directory"
assert properties["path"] == "/job/inputs/dataset_1_files"
assert properties["format"] == extension
def test_to_cwl_zarr_store_in_a_recorded_wrapper_folder():
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "zarr")
hda.metadata.store_root = "wrapped.zarr"
properties = to_cwl(hda, [], compute_environment=cast(Any, RewritingComputeEnvironment()))
assert properties["path"] == "/job/inputs/dataset_1_files/wrapped.zarr"
def test_to_cwl_deferred_dataset_has_location_and_no_path():
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "zarr")
assert hda.dataset is not None
hda.dataset.state = Dataset.states.DEFERRED
hda.dataset.sources = [DatasetSource(source_uri="https://example.org/data/store.zarr")]
properties = to_cwl(hda, [], compute_environment=cast(Any, RewritingComputeEnvironment()))
assert properties["location"] == "https://example.org/data/store.zarr"
assert "path" not in properties
assert "extra_files_path" not in properties
def test_to_cwl_store_root_with_a_quote():
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "zarr")
hda.metadata.store_root = "Bob's store.zarr"
compute_environment = cast(Any, RewritingComputeEnvironment())
# Workflow expressions and escaped arguments never paste the path into a shell.
properties = to_cwl(hda, [], compute_environment=compute_environment)
assert properties["path"] == "/job/inputs/dataset_1_files/Bob's store.zarr"
with pytest.raises(ValueError, match="cannot be passed to a tool"):
to_cwl({"input": [hda]}, [], compute_environment=compute_environment, shell_quotable=True)
class WorkingDirectoryComputeEnvironment(RewritingComputeEnvironment):
def working_directory(self):
return "/job/working"
@pytest.mark.parametrize(
"command",
[
{"shell_command": "ls '$(inputs.input.path)'"},
{"base_command": ["ls"]},
# base_command is the one that runs when a tool has both.
{"base_command": ["ls"], "shell_command": "ls '$(inputs.input.path)'"},
],
)
def test_user_tool_requires_a_quotable_path_only_for_shell_command(command):
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "zarr")
hda.metadata.store_root = "Bob's store.zarr"
tool = Bunch(
shell_command=command.get("shell_command"),
base_command=command.get("base_command"),
tool_source=Bunch(trusted=False),
has_data_table=False,
)
evaluator = UserToolEvaluator(cast(Any, Bunch()), cast(Any, tool), cast(Any, None), "/job")
evaluator.compute_environment = cast(Any, WorkingDirectoryComputeEnvironment())
def build_param_dict():
return evaluator.build_param_dict({"input": hda}, {}, {}, {})
if not tool.base_command:
with pytest.raises(ValueError, match="cannot be passed to a tool"):
build_param_dict()
else:
assert build_param_dict()["inputs"]["input"]["path"] == "/job/inputs/dataset_1_files/Bob's store.zarr"
def test_to_cwl_deferred_dataset_without_a_source_is_rejected():
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "zarr")
assert hda.dataset is not None
hda.dataset.state = Dataset.states.DEFERRED
with pytest.raises(ValueError, match="has no source"):
to_cwl(hda, [], compute_environment=cast(Any, RewritingComputeEnvironment()))
def test_to_cwl_file():
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "txt")
properties = to_cwl(hda, [], compute_environment=cast(Any, RewritingComputeEnvironment()))
assert properties["class"] == "File"
assert properties["path"] == "/job/inputs/dataset_1.dat"
assert properties["extra_files_path"] is None
def test_to_cwl_with_extra_files(tmp_path):
set_datatypes_registry(example_datatype_registry_for_sample())
hda = _hda(1, "pbed")
assert hda.dataset is not None
hda.dataset.external_extra_files_path = str(tmp_path)
properties = to_cwl(hda, [], compute_environment=cast(Any, RewritingComputeEnvironment()))
assert properties["path"] == "/job/inputs/dataset_1.dat"
assert properties["extra_files_path"] == "/job/inputs/dataset_1_files"
def _hda(id: int, extension: str) -> HistoryDatasetAssociation:
hda = HistoryDatasetAssociation(create_dataset=True, flush=False, name="input", extension=extension)
hda.id = id
assert hda.dataset is not None
hda.dataset.file_size = Decimal(4)
hda.dataset.external_extra_files_path = f"/nonexistent/dataset_{id}_files"
return hda
def _csv_with_tabular_conversion() -> tuple[Any, HistoryDatasetAssociation, HistoryDatasetAssociation]:
registry = example_datatype_registry_for_sample()
set_datatypes_registry(registry)
original = _hda(1, "csv")
converted = _hda(2, "tabular")
ImplicitlyConvertedDatasetAssociation(parent=original, dataset=converted, file_type="tabular")
return DatatypesApp(registry), original, converted
def test_adapt_dataset_resolves_an_implicitly_converted_input():
app, _, converted = _csv_with_tabular_conversion()
_, adapt_dataset, _ = setup_for_runtimeify(
cast(Any, app), cast(Any, RewritingComputeEnvironment()), {"input": converted}
)
result = adapt_dataset(DataRequestInternalHda(src="hda", id=1), ["tabular"])
assert result.format == "tabular"
assert result.path == "/job/inputs/dataset_2.dat"
def test_runtimeify_resolves_a_dataset_used_directly_and_converted():
app, original, converted = _csv_with_tabular_conversion()
parameters = ToolParameterBundleModel(
parameters=[
DataParameterModel(type="data", name="as_csv", extensions=["csv"]),
DataParameterModel(type="data", name="as_tabular", extensions=["tabular"]),
]
)
state = JobInternalToolState(
{"as_csv": {"src": "hda", "id": 1}, "as_tabular": {"src": "hda", "id": 1}},
)
_, adapt_dataset, adapt_collection = setup_for_runtimeify(
cast(Any, app),
cast(Any, RewritingComputeEnvironment()),
{"as_csv": original, "as_tabular": converted},
)
runtime_state = runtimeify(state, parameters, adapt_dataset, adapt_collection).input_state
assert runtime_state["as_csv"]["format"] == "csv"
assert runtime_state["as_csv"]["path"] == "/job/inputs/dataset_1.dat"
assert runtime_state["as_tabular"]["format"] == "tabular"
assert runtime_state["as_tabular"]["path"] == "/job/inputs/dataset_2.dat"