Files
galaxy/test/unit/tool_util/test_user_tool_source_validation.py
mvdbeek f997319747 Merge branch 'release_26.1' into dev
# Conflicts:
#	client/src/components/BaseComponents/GTip.vue
#	client/src/components/Common/EmailReportForm.vue
#	client/src/components/Common/ItemListEditor.vue
#	client/src/components/ConfigTemplates/VaultSecret.vue
#	client/src/components/GalaxyAI.test.ts
#	client/src/components/GalaxyWizard.test.ts
#	client/src/components/GalaxyWizard.vue
#	client/src/components/Libraries/LibraryFolder/LibraryFolder.vue
#	client/src/components/Libraries/LibraryPermissions/PermissionsInputField.vue
#	client/src/components/Login/LoginForm.vue
#	client/src/components/Markdown/Sections/Elements/HistoryDatasetCollection/CollectionTree.vue
#	client/src/components/Markdown/Sections/Elements/HistoryDatasetDetails.vue
#	client/src/components/Register/RegisterForm.vue
#	client/src/components/Tool/ToolForm.vue
#	client/src/components/Tool/ToolSourceSchema.json
#	client/src/components/Upload/UploadContainer.vue
#	client/src/components/Workflow/Editor/Index.test.ts
#	client/src/components/Workflow/Editor/Index.vue
#	client/src/components/Workflow/Invocation/Graph/WorkflowInvocationSteps.vue
#	client/src/entry/analysis/App.vue
#	client/src/stores/historyStore.ts
#	lib/galaxy/authnz/psa_authnz.py
#	lib/galaxy/config/__init__.py
#	lib/galaxy/tool_util/parser/yaml.py
#	lib/galaxy/tool_util_models/__init__.py
#	lib/galaxy/tools/__init__.py
#	lib/galaxy/tools/execute.py
#	lib/galaxy/util/unittest_utils/__init__.py
#	lib/galaxy_test/api/test_workflows.py
#	lib/tool_shed/webapp/api2/repositories.py
#	test/integration/oidc/test_auth_oidc.py
#	test/unit/workflows/test_trs_proxy.py
2026-10-02 10:53:08 +02:00

157 lines
5.3 KiB
Python

"""Direct tests for the semantic validators on ``UserToolSource``.
The corpus of cases lives in ``user_tool_source_validation_cases.yml`` so it
can be replayed by external validators (the TS port in
``galaxy-tool-util-ts``, MCP clients, IDE plugins). Each case overrides
``VALID_TOOL`` with its ``doc`` and either validates cleanly (``valid: true``)
or raises a ``ValidationError`` whose distilled output matches the listed
``expected_errors`` by stable error ``code``.
Container *shape* is enforced by the lint framework, not pydantic — see
``test_container_shape_lint.py``.
"""
from copy import deepcopy
from pathlib import Path
from typing import (
Any,
)
import pytest
import yaml
from pydantic import ValidationError
from galaxy.tool_util_models import (
format_validation_errors,
UserToolSource,
UserToolSourceAuthoringView,
YamlToolSource,
)
from galaxy.util.resources import resource_string
VALID_TOOL: dict[str, Any] = {
"class": "GalaxyUserTool",
"id": "my-cool-tool",
"name": "My Cool Tool",
"version": "0.1.0",
"description": "A cool tool.",
"container": "quay.io/biocontainers/python:3.13",
"shell_command": "head -n '$(inputs.n_lines)' '$(inputs.data_input.path)' > out.txt",
"inputs": [
{"type": "integer", "name": "n_lines"},
{"type": "data", "name": "data_input"},
],
"outputs": [
{"type": "data", "name": "out", "from_work_dir": "out.txt"},
],
"citations": [
{"type": "doi", "content": "10.1234/abc.def"},
],
}
def _load_cases() -> list[dict[str, Any]]:
try:
yaml_str = resource_string(__name__, "user_tool_source_validation_cases.yml")
except AttributeError:
# Fallback for invocations that bypass importlib.resources; resolve
# relative to this file rather than cwd.
yaml_str = (Path(__file__).parent / "user_tool_source_validation_cases.yml").read_text()
return yaml.safe_load(yaml_str)["cases"]
CASES = _load_cases()
def _doc_for(case: dict[str, Any]) -> dict[str, Any]:
base = deepcopy(VALID_TOOL)
base.update(case.get("doc") or {})
return base
def _flatten_loc(loc: Any) -> str:
if isinstance(loc, (list, tuple)):
return ".".join(str(p) for p in loc if p != "__root__")
return str(loc)
@pytest.mark.parametrize("case", CASES, ids=lambda c: c["name"])
def test_user_tool_source_corpus(case: dict[str, Any]) -> None:
doc = _doc_for(case)
if case.get("valid"):
UserToolSource.model_validate(doc)
return
with pytest.raises(ValidationError) as info:
UserToolSource.model_validate(doc)
if "expected_format" in case:
assert format_validation_errors(info.value) == case["expected_format"]
raised = [{"loc": _flatten_loc(err["loc"]), "code": err["type"], "msg": err["msg"]} for err in info.value.errors()]
for expected in case.get("expected_errors") or []:
match = next(
(
e
for e in raised
if e["code"] == expected["code"]
and ("loc" not in expected or e["loc"] == expected["loc"])
and ("msg_contains" not in expected or expected["msg_contains"] in e["msg"])
),
None,
)
assert match is not None, f"no error matched {expected!r}; raised={raised!r}"
def _tool_without(*fields: str) -> dict[str, Any]:
doc = deepcopy(VALID_TOOL)
for field in fields:
doc.pop(field, None)
return doc
def test_authoring_view_requires_inputs_and_outputs() -> None:
"""The LLM-facing authoring view forces ``inputs``/``outputs`` into the
structured-output ``required`` set so grammar-constrained models can't drop
them (and then reference an input they never declared)."""
required = UserToolSourceAuthoringView.model_json_schema().get("required", [])
assert "inputs" in required
assert "outputs" in required
with pytest.raises(ValidationError):
UserToolSourceAuthoringView.model_validate(_tool_without("inputs", "outputs"))
def test_canonical_model_stays_lenient_about_inputs_and_outputs() -> None:
"""The required-ness is an authoring-view nudge only -- the canonical model
(API surface, stored rows) must still accept tools that omit them."""
required = UserToolSource.model_json_schema().get("required", [])
assert "inputs" not in required
assert "outputs" not in required
# A self-contained command that references no inputs, so omitting inputs/outputs
# is structurally fine on the canonical model.
tool = UserToolSource.model_validate(
{
"class": "GalaxyUserTool",
"id": "no-io-tool",
"name": "No IO Tool",
"version": "0.1.0",
"container": "quay.io/biocontainers/coreutils:9.5",
"shell_command": "date > out.txt",
}
)
assert tool.inputs == []
assert tool.outputs == []
def test_admin_yaml_tool_rejects_label_referencing_undeclared_input() -> None:
doc = {
**VALID_TOOL,
"class": "GalaxyTool",
"outputs": [{"type": "data", "name": "out", "from_work_dir": "out.txt", "label": "$(inputs.missing.name)"}],
}
with pytest.raises(ValidationError) as exc_info:
YamlToolSource(**doc)
assert [error["type"] for error in exc_info.value.errors()] == ["dynamic_tool.undeclared_input_ref"]