Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
86 changes: 54 additions & 32 deletions src/linkml_reference_validator/cli/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,10 @@ def text_file_command(

@validate_app.command(name="data")
def data_command(
data_file: Annotated[Path, typer.Argument(help="Path to data file (YAML/JSON)")],
data_files: Annotated[
list[Path],
typer.Argument(help="Path(s) to data file(s) (YAML/JSON)"),
],
schema_file: Annotated[
Path,
typer.Option("--schema", "-s", help="Path to LinkML schema file"),
Expand All @@ -240,10 +243,17 @@ def data_command(
This command validates that quoted text (supporting_text) in your data
actually appears in the referenced publications using deterministic substring matching.

Accepts one or more data files; each is validated independently against the
same schema. The schema is parsed (and the Validator built) once and reused
across all files, so validating many files in a single invocation is far
faster than spawning one process per file.

Examples:

linkml-reference-validator validate data data.yaml --schema schema.yaml

linkml-reference-validator validate data a.yaml b.yaml c.yaml --schema schema.yaml

linkml-reference-validator validate data data.yaml --schema schema.yaml --target-class Statement --verbose
"""
setup_logging(verbose)
Expand Down Expand Up @@ -272,48 +282,60 @@ def data_command(

plugin = ReferenceValidationPlugin(config=config)

typer.echo(f"Validating {data_file} against schema {schema_file}")
typer.echo(f"Cache directory: {config.cache_dir}")

# Build the Validator once (parsing the schema is the expensive step) and reuse
# it for every data file.
validator = Validator(
schema=str(schema_file),
validation_plugins=[plugin],
)

yaml = YAML(typ="safe")
with open(data_file) as f:
data = yaml.load(f)

# Validate each instance
all_results = []
if isinstance(data, list):
for instance in data:
report = validator.validate(instance, target_class=target_class)
all_results.extend(report.results)
elif isinstance(data, dict):
report = validator.validate(data, target_class=target_class)
all_results = report.results
else:
typer.echo(f"Error: Unexpected data format in {data_file}", err=True)
raise typer.Exit(1)

if all_results:
typer.echo(f"\nValidation Issues ({len(all_results)}):")
for result in all_results:
severity = result.severity.value if hasattr(result.severity, "value") else result.severity
typer.echo(f" [{severity}] {result.message}")
if hasattr(result, "instantiates") and result.instantiates:
typer.echo(f" Location: {result.instantiates}")
# Show reference ID if available in instance data
if hasattr(result, "instance") and result.instance:
if isinstance(result.instance, dict) and "reference_id" in result.instance:
typer.echo(f" Reference: {result.instance['reference_id']}")
total_results = 0
files_with_issues = 0

for data_file in data_files:
typer.echo(f"\nValidating {data_file} against schema {schema_file}")

with open(data_file) as f:
data = yaml.load(f)

# Validate each instance in this file
file_results = []
if isinstance(data, list):
for instance in data:
report = validator.validate(instance, target_class=target_class)
file_results.extend(report.results)
elif isinstance(data, dict):
report = validator.validate(data, target_class=target_class)
file_results = report.results
else:
typer.echo(f"Error: Unexpected data format in {data_file}", err=True)
files_with_issues += 1
continue
Comment on lines +313 to +316

if file_results:
typer.echo(f" Validation Issues ({len(file_results)}):")
for result in file_results:
severity = result.severity.value if hasattr(result.severity, "value") else result.severity
typer.echo(f" [{severity}] {result.message}")
if hasattr(result, "instantiates") and result.instantiates:
typer.echo(f" Location: {result.instantiates}")
# Show reference ID if available in instance data
if hasattr(result, "instance") and result.instance:
if isinstance(result.instance, dict) and "reference_id" in result.instance:
typer.echo(f" Reference: {result.instance['reference_id']}")
files_with_issues += 1

total_results += len(file_results)

typer.echo("\nValidation Summary:")
typer.echo(f" Total checks: {len(all_results)}")
typer.echo(f" Files validated: {len(data_files)}")
typer.echo(f" Total checks: {total_results}")

if all_results:
typer.echo(f" Issues found: {len(all_results)}")
if total_results:
typer.echo(f" Issues found: {total_results} in {files_with_issues} file(s)")
raise typer.Exit(1)
else:
typer.echo(" All validations passed!")
Expand Down
170 changes: 170 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,176 @@ def test_validate_data_command_failure(tmp_path, fixtures_dir):
assert "Issues found" in result.stdout or "ERROR" in result.stdout


def test_validate_data_command_multiple_files(tmp_path, fixtures_dir):
"""validate-data accepts multiple data files in one invocation.

Each file is validated independently (the schema/Validator is built once and
reused), and any invalid file makes the overall run fail.
"""
cache_dir = tmp_path / "cache"
cache_dir.mkdir()
for fixture_file in fixtures_dir.glob("*.txt"):
(cache_dir / fixture_file.name).write_text(fixture_file.read_text())

schema_file = tmp_path / "test_schema.yaml"
schema_file.write_text("""
id: https://example.org/test
name: test
prefixes:
linkml: https://w3id.org/linkml/
test: https://example.org/test/
default_prefix: test

classes:
Evidence:
attributes:
reference:
range: Reference
implements:
- linkml:authoritative_reference
supporting_text:
range: string
implements:
- linkml:excerpt

Reference:
attributes:
id:
identifier: true
range: string
title:
range: string

Statement:
tree_root: true
attributes:
text:
range: string
has_evidence:
range: Evidence
multivalued: true
""")

good_file = tmp_path / "good.yaml"
good_file.write_text("""
text: "Test statement"
has_evidence:
- reference:
id: "PMID:TEST001"
title: "Protein X functions in cell cycle regulation"
supporting_text: "Protein X functions in cell cycle regulation and plays a critical role in DNA repair mechanisms"
""")

bad_file = tmp_path / "bad.yaml"
bad_file.write_text("""
text: "Test statement"
has_evidence:
- reference:
id: "PMID:TEST001"
title: "Protein X functions in cell cycle regulation"
supporting_text: "This text is definitely not in the reference at all"
""")

result = runner.invoke(
app,
[
"validate-data",
str(good_file),
str(bad_file),
"--schema",
str(schema_file),
"--cache-dir",
str(cache_dir),
],
)

# One of the two files is invalid -> overall failure.
assert result.exit_code == 1, result.stdout
# Both files were processed.
assert "good.yaml" in result.stdout
assert "bad.yaml" in result.stdout
# The invalid file's issue is reported.
assert "ERROR" in result.stdout or "Issues" in result.stdout


def test_validate_data_command_multiple_valid_files(tmp_path, fixtures_dir):
"""Multiple valid data files in one invocation all pass."""
cache_dir = tmp_path / "cache"
cache_dir.mkdir()
for fixture_file in fixtures_dir.glob("*.txt"):
(cache_dir / fixture_file.name).write_text(fixture_file.read_text())

schema_file = tmp_path / "test_schema.yaml"
schema_file.write_text("""
id: https://example.org/test
name: test
prefixes:
linkml: https://w3id.org/linkml/
test: https://example.org/test/
default_prefix: test

classes:
Evidence:
attributes:
reference:
range: Reference
implements:
- linkml:authoritative_reference
supporting_text:
range: string
implements:
- linkml:excerpt

Reference:
attributes:
id:
identifier: true
range: string
title:
range: string

Statement:
tree_root: true
attributes:
text:
range: string
has_evidence:
range: Evidence
multivalued: true
""")

valid_text = """
text: "Test statement"
has_evidence:
- reference:
id: "PMID:TEST001"
title: "Protein X functions in cell cycle regulation"
supporting_text: "Protein X functions in cell cycle regulation and plays a critical role in DNA repair mechanisms"
"""
f1 = tmp_path / "a.yaml"
f1.write_text(valid_text)
f2 = tmp_path / "b.yaml"
f2.write_text(valid_text)

result = runner.invoke(
app,
[
"validate-data",
str(f1),
str(f2),
"--schema",
str(schema_file),
"--cache-dir",
str(cache_dir),
],
)

assert result.exit_code == 0, result.stdout
assert "All validations passed" in result.stdout
assert "a.yaml" in result.stdout
assert "b.yaml" in result.stdout


def test_validate_data_verbose_mode(tmp_path, fixtures_dir):
"""Test validate-data with verbose flag."""
# Set up cache
Expand Down
Loading