Skip to content

Commit

Permalink
Merge pull request #63 from iolanta-tech/ter56-failing
Browse files Browse the repository at this point in the history
`#ter56` failing
  • Loading branch information
anatoly-scherbakov authored Apr 28, 2024
2 parents 2a6881a + 66461de commit 8cf9149
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 65 deletions.
81 changes: 48 additions & 33 deletions tests/test_specification.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import operator
from pathlib import Path
from typing import Callable

import pytest
from pyld import jsonld
Expand All @@ -16,6 +17,8 @@
from yaml_ld.errors import YAMLLDError
from lambdas import _

from yaml_ld.expand import ExpandOptions

tests = Namespace('https://w3c.github.io/json-ld-api/tests/vocab#')


Expand Down Expand Up @@ -67,41 +70,53 @@ def test_to_rdf(test_case: TestCase):
assert actual_graph.isomorphic(expected_graph)


@pytest.mark.parametrize('test_case', load_tests(tests.ExpandTest), ids=_get_id)
def test_expand(test_case: TestCase):
if isinstance(test_case.result, str):
try:
expanded_document = yaml_ld.expand(
test_case.input,
extract_all_scripts=test_case.extract_all_scripts,
)
except YAMLLDError as error:
assert error.code == test_case.result
else:
pytest.fail(str(FailureToFail(
test_case=test_case,
expected_error_code=test_case.result,
raw_document=test_case.raw_document,
expanded_document=expanded_document,
)))
@pytest.fixture()
def test_against_ld_library():
def _test(test_case: TestCase, parse: Callable, expand: Callable) -> None:
match test_case.result:
case str() as error_code:
try:
expanded_document = expand(
test_case.input,
options=ExpandOptions(
extract_all_scripts=test_case.extract_all_scripts,
).model_dump(),
)
except YAMLLDError as error:
assert error.code == error_code
else:
pytest.fail(str(FailureToFail(
test_case=test_case,
expected_error_code=test_case.result,
raw_document=test_case.raw_document,
expanded_document=expanded_document,
)))

case Path() as result_path:
expected = parse(result_path.read_text())
actual = expand(
test_case.input,
options=ExpandOptions(
extract_all_scripts=test_case.extract_all_scripts,
base=test_case.base,
).model_dump(by_alias=True),
)

elif isinstance(test_case.result, Path):
expected = yaml_ld.parse(test_case.result.read_text())
actual = yaml_ld.expand(
test_case.input,
extract_all_scripts=test_case.extract_all_scripts,
base=test_case.base,
)
assert actual == expected

if actual != expected:
# Try running `pyld` against this example.
jsonld_actual = jsonld.expand(json.loads(test_case.result.read_text()))
case _:
raise ValueError(f'What to do with this test? {test_case}')

if jsonld_actual == expected:
# PyLD is fine. We're having a trouble with YAML-LD.
assert actual == expected
return _test

pytest.skip('PyLD fails on this test, skipping it.')

else:
raise ValueError(f'What to do with this test? {test_case}')
@pytest.mark.parametrize('test_case', load_tests(tests.ExpandTest), ids=_get_id)
def test_expand(
test_case: TestCase,
test_against_ld_library,
):
test_against_ld_library(
test_case=test_case,
parse=yaml_ld.parse,
expand=yaml_ld.expand,
)
43 changes: 18 additions & 25 deletions yaml_ld/expand.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from pathlib import Path
from typing import Annotated
from typing import Annotated, TypedDict

from pydantic import Field
from pydantic import Field, validate_call
from pyld import jsonld
from urlpath import URL

Expand All @@ -23,40 +23,33 @@ class ExpandOptions(BaseOptions):
context: Document | None = Field(default=None, alias='expandContext')


class ExpandOptionsDict(TypedDict):
context: Document | None
base: str | None
extract_all_scripts: ExtractAllScripts
document_loader: DocumentLoader | None


@specified_by(API / '#dom-jsonldprocessor-expand')
@validate_call(config=dict(arbitrary_types_allowed=True))
def expand( # noqa: C901, WPS211
document: SerializedDocument | Document,
base: Annotated[str | None, Help('The base IRI to use.')] = None,
context: Annotated[
Document | None,
Help('A context to expand with.'),
] = None,
extract_all_scripts: ExtractAllScripts = False,
mode: ProcessingMode = ProcessingMode.JSON_LD_1_1,
document_loader: DocumentLoader | None = None,
options: ExpandOptions = ExpandOptions(),
) -> Document | list[Document]:
"""Expand a YAML-LD document."""
if isinstance(document, (str, bytes, Path, URL)):
if isinstance(document, Path) and base is None:
base = f'file://{document.parent}/'
if isinstance(document, Path) and options.base is None:
options.base = f'file://{document.parent}/'

document = parse(document, extract_all_scripts=extract_all_scripts)

options = ExpandOptions(
base=base,
context=context,
extract_all_scripts=extract_all_scripts,
mode=mode,
document_loader=document_loader,
).model_dump(
exclude_defaults=True,
by_alias=True,
)
document = parse(
document,
extract_all_scripts=options.extract_all_scripts,
)

try:
return jsonld.expand(
input_=document,
options=options,
options=options.model_dump(),
)
except TypeError as err:
raise MappingKeyError() from err
Expand Down
8 changes: 3 additions & 5 deletions yaml_ld/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from pathlib import Path
from typing import Any, Annotated, NewType

from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, ConfigDict
from urlpath import URL

Document = dict[str, Any] # type: ignore
Expand Down Expand Up @@ -43,11 +43,9 @@ class BaseOptions(BaseModel):

base: str | None = Field(default=None)
extract_all_scripts: bool = Field(default=False, alias='extractAllScripts')
mode: ProcessingMode = Field(
default=ProcessingMode.JSON_LD_1_1,
alias='processingMode',
)
document_loader: DocumentLoader | None = Field(
default=None,
alias='documentLoader',
)

model_config = ConfigDict(populate_by_name=True)
7 changes: 5 additions & 2 deletions yaml_ld/to_rdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import yaml_ld
from yaml_ld.annotations import Help
from yaml_ld.expand import ExpandOptions
from yaml_ld.models import (
Document, DocumentLoader, ExtractAllScripts,
SerializedDocument,
Expand All @@ -22,8 +23,10 @@ def to_rdf(
"""Convert a YAML-LD document to RDF."""
expanded_document = yaml_ld.expand(
document=document,
document_loader=document_loader,
extract_all_scripts=extract_all_scripts,
options=ExpandOptions(
document_loader=document_loader,
extract_all_scripts=extract_all_scripts,
),
)

return jsonld.to_rdf(
Expand Down

0 comments on commit 8cf9149

Please sign in to comment.