Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CLI-based validation of JSON-LD contexts #1096

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions src/bioregistry/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .export.cli import export
from .lint import lint
from .utils import OLSBroken, get_hexdigests, secho
from .validate.cli import validate
from .version import VERSION


Expand Down Expand Up @@ -79,6 +80,7 @@ def align(skip_fairsharing: bool, skip_re3data: bool, skip_slow: bool, no_force:
main.add_command(lint)
main.add_command(compare)
main.add_command(export)
main.add_command(validate)
main.add_command(web)


Expand Down
1 change: 1 addition & 0 deletions src/bioregistry/validate/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Validation utilities."""
66 changes: 66 additions & 0 deletions src/bioregistry/validate/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Validation command line interface.

JSON-LD Validation

1. Passes ``bioregistry validate jsonld "https://bioregistry.io/api/collection/0000002?format=context"``
1. Fails ``bioregistry validate jsonld "https://raw.githubusercontent.com/prefixcommons/prefixcommons-py/master/prefixcommons/registry/go_context.jsonld"``
2.
"""

import json
import sys
from pathlib import Path

import click
import requests

from .utils import validate_jsonld

__all__ = [
"validate",
]


@click.group()
def validate():
"""Validate data with the Bioregistry."""


@validate.command()
@click.argument("location")
@click.option("--relax", is_flag=True)
def jsonld(location: str, relax: bool):
"""Validate a JSON-LD file."""
if location.startswith("http://") or location.startswith("https://"):
res = requests.get(location)
res.raise_for_status()
obj = res.json()
else:
path = Path(location).resolve()
if not path.is_file():
raise ValueError
obj = json.loads(path.read_text())

messages = validate_jsonld(obj, strict=not relax)
for message in messages:
error, prefix, solution, level = (
message["error"],
message["prefix"],
message["solution"],
message["level"],
)
click.secho(f"{prefix} - {error}", fg=LEVEL_TO_COLOR[level], nl=False)
if solution:
click.echo(" > " + solution)
else:
click.echo("")

if any(message["level"] == "error" for message in messages):
click.secho("failed", fg="red")
sys.exit(1)


LEVEL_TO_COLOR = {
"warning": "yellow",
"error": "red",
}
41 changes: 41 additions & 0 deletions src/bioregistry/validate/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Validation utilities."""

from typing import Mapping

import bioregistry

__all__ = [
"validate_jsonld",
]


def validate_jsonld(obj: Mapping[str, Mapping[str, str]], strict: bool = True):
if not isinstance(obj, dict):
raise TypeError(f"data is not a dictionary")
context = obj.get("@context")
if context is None:
raise TypeError(f"data is missing a @context field")
if not isinstance(context, dict):
raise TypeError(f"@context is not a dictionary: {context}")
messages = []
for prefix, uri_prefix in context.items():
norm_prefix = bioregistry.normalize_prefix(prefix)
if norm_prefix is None:
messages.append(
{
"prefix": prefix,
"error": "invalid",
"solution": None,
"level": "error",
}
)
elif norm_prefix != prefix:
messages.append(
{
"prefix": prefix,
"error": "nonstandard",
"solution": f"Switch to standard prefix: {norm_prefix}",
"level": "error" if strict else "warning",
}
)
return messages
32 changes: 32 additions & 0 deletions tests/test_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Test for validation utilities."""

import unittest

from bioregistry.validate.utils import validate_jsonld


class TestValidation(unittest.TestCase):
"""Test case for validation utilities."""

def test_validate_jsonld(self):
"""Test validating JSON-LD."""
with self.assertRaises(TypeError):
validate_jsonld(None)
with self.assertRaises(TypeError):
validate_jsonld({})
with self.assertRaises(TypeError):
validate_jsonld({"@context": None})

test_context = {
"@context": {
"GO": ...,
"nope": ...,
}
}
warnings, errors = validate_jsonld(test_context, strict=True)
self.assertEqual([("GO", "nonstandard"), ("nope", "invalid")], errors)
self.assertEqual([], warnings)

warnings, errors = validate_jsonld(test_context, strict=False)
self.assertEqual([("nope", "invalid")], errors)
self.assertEqual([("GO", "nonstandard")], warnings)
Loading