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

Generate JSON-LD context from a DefinedNamespace #1706

Merged
merged 8 commits into from
Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
14 changes: 12 additions & 2 deletions rdflib/namespace/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import json
import logging
import warnings
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, Iterable
from unicodedata import category

from pathlib import Path
from urllib.parse import urldefrag
from urllib.parse import urljoin

Expand Down Expand Up @@ -239,6 +239,16 @@ def __dir__(cls) -> Iterable[str]:
values = {cls[str(x)] for x in cls.__annotations__}
return values

def jsonld_context(self, pfx: str) -> str:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still would collide with any jsonld_context term in a namespace. It should thus at least be renamed or moved to a utility function. It also makes sense to let it return a dict, to allow the user of the function to decide serialization form (indent, sorting, etc.).

"""This function creates a JSON-LD 'context' JSON object from this
DefinedNamespace namespace and it's members"""
terms = {pfx: str(self._NS)}
for key, term in self.__annotations__.items():
if issubclass(term, URIRef):
terms[key] = f'{pfx}:{key}'

return json.dumps({'@context': terms}, sort_keys=True)


class DefinedNamespace(metaclass=DefinedNamespaceMeta):
"""
Expand Down
1 change: 1 addition & 0 deletions rdflib/term.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

__all__ = [
"bind",
"_is_valid_uri",
"Node",
"IdentifiedNode",
"Identifier",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import sys
import subprocess
from pathlib import Path
from rdflib import RDF, SKOS
import json


def test_definednamespace_creator_qb():
Expand Down Expand Up @@ -92,3 +94,81 @@ def test_definednamespace_creator_bad_ns():
universal_newlines=True,
)
assert completed.returncode == 1, "subprocess exited incorrectly (failure expected)"


def test_definednamespace_dir():
x = dir(RDF)

values = [
RDF.nil,
RDF.direction,
RDF.first,
RDF.language,
RDF.object,
RDF.predicate,
RDF.rest,
RDF.subject,
RDF.type,
RDF.value,
RDF.Alt,
RDF.Bag,
RDF.CompoundLiteral,
RDF.List,
RDF.Property,
RDF.Seq,
RDF.Statement,
RDF.HTML,
RDF.JSON,
RDF.PlainLiteral,
RDF.XMLLiteral,
RDF.langString,
]

assert len(values) == len(x)

for value in values:
assert value in x


def test_definednamespace_jsonld_context():
expected = json.dumps({
"@context": {
"skos": "http://www.w3.org/2004/02/skos/core#",
"altLabel": "skos:altLabel",
"broadMatch": "skos:broadMatch",
"broader": "skos:broader",
"broaderTransitive": "skos:broaderTransitive",
"changeNote": "skos:changeNote",
"closeMatch": "skos:closeMatch",
"definition": "skos:definition",
"editorialNote": "skos:editorialNote",
"exactMatch": "skos:exactMatch",
"example": "skos:example",
"hasTopConcept": "skos:hasTopConcept",
"hiddenLabel": "skos:hiddenLabel",
"historyNote": "skos:historyNote",
"inScheme": "skos:inScheme",
"mappingRelation": "skos:mappingRelation",
"member": "skos:member",
"memberList": "skos:memberList",
"narrowMatch": "skos:narrowMatch",
"narrower": "skos:narrower",
"narrowerTransitive": "skos:narrowerTransitive",
"notation": "skos:notation",
"note": "skos:note",
"prefLabel": "skos:prefLabel",
"related": "skos:related",
"relatedMatch": "skos:relatedMatch",
"scopeNote": "skos:scopeNote",
"semanticRelation": "skos:semanticRelation",
"topConceptOf": "skos:topConceptOf",
"Collection": "skos:Collection",
"Concept": "skos:Concept",
"ConceptScheme": "skos:ConceptScheme",
"OrderedCollection": "skos:OrderedCollection"
}
}, sort_keys=True)

actual = SKOS.jsonld_context("skos")

assert actual == expected
35 changes: 0 additions & 35 deletions test/test_definednamespace_dir.py

This file was deleted.