Files
galaxy/test/unit/tool_util/test_parameter_specification_json_schema.py
mvdbeek 96c96687be Merge branch 'release_26.1' into dev
Conflict resolutions:
- tool_util_models: keep the 26.1 field documentation using dev's typing
  syntax; keep both dev's container-requirement rejection and the 26.1
  _require_container validator, so a missing container now reports
  "set the top-level container field" instead of "Field required".
- api/mcp.py: dev's page tools plus the 26.1 ASGI route mounting.
- managers/markdown_util.py: 26.1 job label resolution with dev's typed
  signature.
- tool_shed/managers/tools.py: 26.1 stock_tool_sources_by_id refactor.
- CustomToolEditor.vue: 26.1 toolbar, which already uses icon-only.
- Regenerated ToolSourceSchema.json and the api-client schema.ts.
2026-09-22 12:36:32 +02:00

265 lines
10 KiB
Python

"""Validate parameter_specification.yml entries against JSON Schema generated from Pydantic models.
This mirrors test_parameter_specification.py but validates against JSON Schema (Draft 2020-12)
instead of Pydantic models directly. The goal is to prove the exported JSON Schemas are usable
from non-Python toolkits.
Many Galaxy validators now emit native JSON Schema keywords (pattern, minimum/maximum,
minLength/maxLength, exclusiveMinimum/exclusiveMaximum, and negated length via not:{}).
Remaining AfterValidator-only constraints (expression, empty_field) that cannot be represented
in JSON Schema are annotated with _json_schema_skip in parameter_specification.yml so the test
knows to tolerate those *_invalid entries passing validation. A skip value is either a string
(tolerate every entry in that combo) or a mapping of index -> reason (tolerate only those
entries, keeping JSON-Schema-catchable cases in the same combo under test).
"""
import sys
from typing import (
Any,
)
import jsonschema
import jsonschema.exceptions
import pytest
import yaml
from pydantic_extra_types.color import Color as _Color
from galaxy.tool_util.parameters.convert import OPENAPI_REF_TEMPLATE
from galaxy.tool_util.parameters.json import to_json_schema
from galaxy.tool_util.unittest_utils.parameters import (
parameter_bundle_for_file,
)
from galaxy.tool_util_models.parameters import (
create_field_model,
RawStateDict,
StateRepresentationT,
ToolParameterBundleModel,
)
from galaxy.util.resources import resource_string
pytestmark = pytest.mark.skipif(
sys.version_info < (3, 9), reason="jsonschema<4.24 on Python 3.8 mishandles additionalProperties in anyOf"
)
REPRESENTATION_KEYS = [
"relaxed_request",
"request",
"request_internal",
"request_internal_dereferenced",
"landing_request",
"landing_request_internal",
"job_internal",
"job_runtime",
"test_case_xml",
"test_case_json",
"workflow_step",
"workflow_step_linked",
]
STATE_REPRESENTATION_FOR_KEY: dict[str, StateRepresentationT] = {k: k for k in REPRESENTATION_KEYS} # type: ignore[misc]
def specification_object():
try:
yaml_str = resource_string(__name__, "parameter_specification.yml")
except AttributeError:
yaml_str = open("test/unit/tool_util/parameter_specification.yml").read()
return yaml.safe_load(yaml_str)
def _json_schema_for(bundle: ToolParameterBundleModel, state_representation: StateRepresentationT) -> dict[str, Any]:
model = create_field_model(bundle.parameters, name="TestModel", state_representation=state_representation)
return to_json_schema(model)
_FORMAT_CHECKER = jsonschema.FormatChecker()
@_FORMAT_CHECKER.checks("color", raises=jsonschema.exceptions.FormatError)
def _check_color_format(value: object) -> bool:
if isinstance(value, str):
try:
_Color(value)
except Exception as e:
raise jsonschema.exceptions.FormatError(f"{value!r} is not a valid color", cause=e)
return True
def _json_schema_validates(schema: dict[str, Any], state_dict: RawStateDict) -> bool:
validator = jsonschema.Draft202012Validator(schema, format_checker=_FORMAT_CHECKER)
errors = list(validator.iter_errors(state_dict))
return len(errors) == 0
def _test_file_json_schema(
file: str,
specification=None,
parameter_bundle: ToolParameterBundleModel | None = None,
):
spec = specification or specification_object()
combos = spec[file]
if parameter_bundle is None:
parameter_bundle = parameter_bundle_for_file(file)
assert parameter_bundle
# A skip value may be a string (skip every entry in the combo, for combos where all cases
# exercise the same AfterValidator-only constraint) or a mapping of index -> reason (skip only
# those entries, so JSON-Schema-catchable cases in the same combo remain covered).
json_schema_skip: dict[str, Any] = combos.get("_json_schema_skip", {}) or {}
json_schema_valid_skip: dict[str, Any] = combos.get("_json_schema_valid_skip", {}) or {}
def _is_skipped(skip_map: dict[str, Any], key: str, index: int) -> bool:
entry = skip_map.get(key)
if entry is None:
return False
if isinstance(entry, dict):
return index in entry
return True
failures: list[str] = []
for combo_key, test_cases in combos.items():
if combo_key in ("_json_schema_skip", "_json_schema_valid_skip"):
continue
if not isinstance(test_cases, list):
continue
if combo_key.endswith("_valid"):
is_valid = True
rep_key = combo_key[: -len("_valid")]
elif combo_key.endswith("_invalid"):
is_valid = False
rep_key = combo_key[: -len("_invalid")]
else:
continue
state_representation = STATE_REPRESENTATION_FOR_KEY.get(rep_key)
if state_representation is None:
continue
schema = _json_schema_for(parameter_bundle, state_representation)
for i, test_case in enumerate(test_cases):
passes = _json_schema_validates(schema, test_case)
if is_valid and not passes and not _is_skipped(json_schema_valid_skip, combo_key, i):
failures.append(f"{file}/{combo_key}[{i}]: valid entry REJECTED by JSON Schema: {test_case}")
elif not is_valid and passes and not _is_skipped(json_schema_skip, combo_key, i):
failures.append(
f"{file}/{combo_key}[{i}]: invalid entry ACCEPTED by JSON Schema (not skipped): {test_case}"
)
if failures:
raise AssertionError(
f"{len(failures)} JSON Schema validation divergence(s) for {file}:\n" + "\n".join(failures)
)
def test_specification_json_schema():
parameter_spec = specification_object()
for file in parameter_spec.keys():
_test_file_json_schema(file, parameter_spec)
def _conditional_type_def(
file: str, state_representation: StateRepresentationT = "request"
) -> tuple[dict[str, Any], dict[str, Any]]:
bundle = parameter_bundle_for_file(file)
schema = _json_schema_for(bundle, state_representation)
defs = schema.get("$defs", {})
matches = {k: v for k, v in defs.items() if "oneOf" in v}
assert len(matches) == 1, f"Expected exactly one oneOf def, got {list(matches.keys())}"
return next(iter(matches.values())), defs
def test_boolean_conditional_discriminator():
cond_def, defs = _conditional_type_def("gx_conditional_boolean")
disc = cond_def.get("discriminator")
assert disc is not None
assert disc["propertyName"] == "test_parameter"
mapping = disc["mapping"]
assert "true" in mapping
assert "false" in mapping
assert len(mapping) == 2
assert defs["When_test_parameter_True"]["title"] == "When test_parameter = True"
assert defs["When_test_parameter_False"]["title"] == "When test_parameter = False"
assert defs["When_test_parameter___absent"]["title"] == "When test_parameter is absent"
def test_select_conditional_discriminator():
cond_def, defs = _conditional_type_def("gx_conditional_select")
disc = cond_def.get("discriminator")
assert disc is not None
assert disc["propertyName"] == "test_parameter"
mapping = disc["mapping"]
assert set(mapping.keys()) == {"a", "b", "c"}
assert defs["When_test_parameter_a"]["title"] == "When test_parameter = a"
assert defs["When_test_parameter___absent"]["title"] == "When test_parameter is absent"
def test_job_internal_no_discriminator():
bundle = parameter_bundle_for_file("gx_conditional_boolean")
schema = _json_schema_for(bundle, "job_internal")
defs = schema.get("$defs", {})
for def_schema in defs.values():
assert "discriminator" not in def_schema
def _resolve_json_pointer(document: dict[str, Any], pointer: str) -> Any:
assert pointer.startswith("#/"), f"Expected a local JSON pointer, got {pointer!r}"
node: Any = document
for token in pointer[2:].split("/"):
token = token.replace("~1", "/").replace("~0", "~")
node = node[token]
return node
def _collect_pointers(node: Any, path: str = "#") -> list[tuple[str, str]]:
"""Return (location, pointer) for every $ref and every discriminator mapping value."""
pointers: list[tuple[str, str]] = []
if isinstance(node, dict):
for key, value in node.items():
location = f"{path}/{key}"
if key == "$ref" and isinstance(value, str):
pointers.append((location, value))
elif key == "discriminator" and isinstance(value, dict):
for tag, target in value.get("mapping", {}).items():
pointers.append((f"{location}/mapping/{tag}", target))
else:
pointers.extend(_collect_pointers(value, location))
elif isinstance(node, list):
for index, item in enumerate(node):
pointers.extend(_collect_pointers(item, f"{path}/{index}"))
return pointers
def _assert_pointers_resolve(document: dict[str, Any]) -> None:
pointers = _collect_pointers(document)
mapping_pointers = [pointer for location, pointer in pointers if "/discriminator/mapping/" in location]
assert mapping_pointers, "expected the collection element union to carry a discriminator mapping"
dangling = []
for location, pointer in pointers:
try:
_resolve_json_pointer(document, pointer)
except (KeyError, IndexError, TypeError, AssertionError):
dangling.append(f"{location} -> {pointer}")
assert not dangling, "pointers that do not resolve within the document:\n" + "\n".join(dangling)
@pytest.mark.parametrize("file", ["gx_data_multiple", "gx_data_collection"])
def test_request_schema_pointers_resolve(file: str):
bundle = parameter_bundle_for_file(file)
schema = _json_schema_for(bundle, "request")
_assert_pointers_resolve(schema)
@pytest.mark.parametrize("file", ["gx_data_multiple", "gx_data_collection"])
def test_openapi_schema_pointers_resolve(file: str):
bundle = parameter_bundle_for_file(file)
model = create_field_model(bundle.parameters, name="TestModel", state_representation="request")
schema = model.model_json_schema(ref_template=OPENAPI_REF_TEMPLATE)
document = {"components": {"schemas": schema.pop("$defs")}, "paths": {"/": schema}}
_assert_pointers_resolve(document)