Skip to content

Commit

Permalink
fix: JSON-LD context construction from a dict
Browse files Browse the repository at this point in the history
A variable was only being initialized for string-valued inputs, but if a `dict`
input was passed the variable would still be accessed, resulting in a
`UnboundLocalError`.

This change initializes the variable always, instead of only when string-valued
input is used to construct a JSON-LD context.

- Closes <#2303>.
  • Loading branch information
aucampia committed Mar 22, 2023
1 parent cfe6e37 commit 73fd02e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion rdflib/plugins/shared/jsonld/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,13 +421,13 @@ def _prep_sources(
):
for source in inputs:
source_url = in_source_url
new_base = base
if isinstance(source, str):
source_url = source
source_doc_base = base or self.doc_base
new_ctx = self._fetch_context(
source, source_doc_base, referenced_contexts
)
new_base = base
if new_ctx is None:
continue
else:
Expand Down
21 changes: 21 additions & 0 deletions test/jsonld/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

from functools import wraps
from pathlib import Path
from typing import Any, Dict

from rdflib.plugins.shared.jsonld import context, errors
Expand Down Expand Up @@ -213,3 +214,23 @@ def test_invalid_remote_context():
ctx_url = "http://example.org/recursive.jsonld"
SOURCES[ctx_url] = {"key": "value"}
ctx = Context(ctx_url)


def test_file_source(tmp_path: Path) -> None:
"""
A file URI source to `Context` gets processed correctly.
"""
file = tmp_path / "context.jsonld"
file.write_text(r"""{ "@context": { "ex": "http://example.com/" } }""")
ctx = Context(source=file.as_uri())
assert "http://example.com/" == ctx.terms["ex"].id


def test_dict_source(tmp_path: Path) -> None:
"""
A dictionary source to `Context` gets processed correctly.
"""
file = tmp_path / "context.jsonld"
file.write_text(r"""{ "@context": { "ex": "http://example.com/" } }""")
ctx = Context(source=[{"@context": file.as_uri()}])
assert "http://example.com/" == ctx.terms["ex"].id

0 comments on commit 73fd02e

Please sign in to comment.