示例#1
0
def test_simple_deserialization():
    class Book:
        def __init__(self, _id, name, *args, test="Bla", **kwargs):
            self._id = _id
            self.name = name

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Book
            model = Book

    data = {
        "@id": "http://example.com/books/1",
        "@type": "http://schema.org/Book",
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
    }

    book = BookSchema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"
示例#2
0
def test_simple_deserialization_with_value_type():
    class Book:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Book
            model = Book
            add_value_types = True

    data = {
        "@id": "http://example.com/books/1",
        "@type": "http://schema.org/Book",
        "http://schema.org/name": {
            "@type": "http://www.w3.org/2001/XMLSchema#string",
            "@value": "Hitchhikers Guide to the Galaxy",
        },
    }
    book = BookSchema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"
示例#3
0
def test_annotation_meta_option():
    """Test annotation support with marshmallow meta option."""
    schema = fields.Namespace("http://schema.org/")

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name=""):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book
            exclude = ("name", )

    data = {
        "@id": "http://example.com/books/1",
        "@type": ["http://schema.org/Book"]
    }

    book = Book.schema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == ""

    dumped = Book.schema().dump(book)
    assert data == dumped
    assert "http://schema.org/name" not in data

    dumped = book.dump()
    assert data == dumped
    assert "http://schema.org/name" not in data
def test_iri_field_serialization():
    """Tests serialization of IRI fields."""
    class A(object):
        def __init__(self, _id, url):
            super().__init__()
            self._id = _id
            self.url = url

    schema = fields.Namespace("http://schema.org/")

    class ASchema(JsonLDSchema):
        _id = fields.Id()
        url = fields.IRI(schema.url)

        class Meta:
            rdf_type = schema.A
            model = A

    a = A("http://example.com/1", "http://datascience.ch")

    jsonld = ASchema().dump(a)

    assert "http://schema.org/url" in jsonld
    assert "@id" in jsonld["http://schema.org/url"]
    assert jsonld["http://schema.org/url"]["@id"] == "http://datascience.ch"
def test_simple_verification_deserialization():
    """Shouldn't raise any error while deserializing"""
    class Book:
        def __init__(self, _id, name, author):
            self._id = _id
            self.name = name
            self.author = author

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        author = fields.String(schema.author)

        class Meta:
            rdf_type = schema.Book
            model = Book

    data = {
        "@id": "http://example.com/books/4",
        "@type": "http://schema.org/Book",
        "http://schema.org/name": "Harry Potter & The Chamber of Secrets",
        "http://schema.org/author": "J. K. Rowling",
        "http://schema.org/publishedYear": 1998,
    }

    verified_data = BookSchema().validate_properties(
        data, "tests/fixtures/book_ontology.owl", return_valid_data=True)

    assert BookSchema().load(verified_data)
def test_simple_serialization_with_value_type():
    class Book:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Book
            model = Book
            add_value_types = True

    b = Book("http://example.com/books/1", "Hitchhikers Guide to the Galaxy")

    jsonld = BookSchema().dump(b)

    assert "http://schema.org/name" in jsonld
    assert "@type" in jsonld["http://schema.org/name"]
    assert jsonld["http://schema.org/name"]["@value"] == b.name
    assert "@id" in jsonld
    assert jsonld["@id"] == b._id
    assert "@type" in jsonld
    assert jsonld["@type"] == ["http://schema.org/Book"]
示例#7
0
def test_missing_reverse_simple_deserialization():
    class Author:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name
            self.organization = None

    schema = fields.Namespace("http://schema.org/")

    class AuthorSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        organization = fields.IRI(schema.organization, reverse=True)

        class Meta:
            rdf_type = schema.Person
            model = Author

    data = {
        "@id": "http://example.com/authors/2",
        "@type": "http://schema.org/Person",
        "http://schema.org/name": "Douglas Adams",
    }

    author = AuthorSchema().load(data)

    assert author.name == "Douglas Adams"
    assert author._id == "http://example.com/authors/2"
    assert author.organization == None
示例#8
0
def test_date_time_serialization():
    """Tests serialization of different date/time fields."""
    class A(object):
        def __init__(self, _id, dt, naive_dt, aware_dt, date, time):
            super().__init__()
            self._id = _id
            self.dt = dt
            self.naive_dt = naive_dt
            self.aware_dt = aware_dt
            self.date = date
            self.time = time

    schema = fields.Namespace("http://schema.org/")

    class ASchema(JsonLDSchema):
        _id = fields.Id()
        dt = fields.DateTime(schema.dateTime)
        naive_dt = fields.NaiveDateTime(schema.naiveDateTime)
        aware_dt = fields.AwareDateTime(schema.awareDateTime)
        date = fields.Date(schema.date)
        time = fields.Time(schema.time)

        class Meta:
            rdf_type = schema.A
            model = A

    import datetime as dt

    a = A(
        "http://example.com/1",
        dt.datetime(2007, 12, 6, 16, 29, 43),
        dt.datetime(2020, 8, 18, 12, 45, 43),
        dt.datetime(2020,
                    6,
                    6,
                    23,
                    59,
                    59,
                    tzinfo=dt.timezone(dt.timedelta(hours=1))),
        dt.date(2002, 12, 31),
        dt.time(12, 10, 30),
    )

    jsonld = ASchema().dump(a)

    assert "http://schema.org/awareDateTime" in jsonld
    assert jsonld[
        "http://schema.org/awareDateTime"] == "2020-06-06T23:59:59+01:00"

    assert "http://schema.org/date" in jsonld
    assert jsonld["http://schema.org/date"] == "2002-12-31"

    assert "http://schema.org/dateTime" in jsonld
    assert jsonld["http://schema.org/dateTime"] == "2007-12-06T16:29:43"

    assert "http://schema.org/naiveDateTime" in jsonld
    assert jsonld["http://schema.org/naiveDateTime"] == "2020-08-18T12:45:43"

    assert "http://schema.org/time" in jsonld
    assert jsonld["http://schema.org/time"] == "12:10:30"
def test_init_name_failure():
    """Test deserialization of fields with init_name fails in case of duplication."""
    class Entity:
        def __init__(self, field, another_field):
            self.field = field
            self.another_field = another_field

    schema = fields.Namespace("http://schema.org/")

    class EntitySchema(JsonLDSchema):
        field = fields.Boolean(schema.field, init_name="another_field")
        another_field = fields.Boolean(schema.another_field, missing=False)

        class Meta:
            rdf_type = schema.Entity
            model = Entity

    data = {
        "@type": ["http://schema.org/Entity"],
        "http://schema.org/field": "true"
    }

    with pytest.raises(ValueError) as e:
        EntitySchema().load(data)
        assert "Initialization name another_field for field is already in data" in str(
            e)
def test_iri_field_deserialization():
    """Tests deserialization of IRI fields."""
    class A(object):
        def __init__(self, _id, url):
            super().__init__()
            self._id = _id
            self.url = url

    schema = fields.Namespace("http://schema.org/")

    class ASchema(JsonLDSchema):
        _id = fields.Id()
        url = fields.IRI(schema.url)

        class Meta:
            rdf_type = schema.A
            model = A

    data = {
        "@id": "http://example.com/1",
        "@type": ["http://schema.org/A"],
        "http://schema.org/url": {
            "@id": "http://datascience.ch"
        },
    }

    a = ASchema().load(data)

    assert a.url == "http://datascience.ch"
示例#11
0
def test_annotation():
    """Test annotation support."""
    schema = fields.Namespace("http://schema.org/")

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

    data = {
        "@id": "http://example.com/books/1",
        "@type": ["http://schema.org/Book"],
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
    }

    book = Book.schema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"

    dumped = Book.schema().dump(book)
    assert data == dumped

    dumped = book.dump()
    assert data == dumped
示例#12
0
def test_annotation_with_default():
    """Test annotation with default values."""
    schema = fields.Namespace("http://schema.org/")

    def default_surname():
        return "Doe"

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id(default="http://example.com/book/1")
        name = fields.String(schema.name, default=lambda: "Bill")
        surname = fields.String(schema.surname, default=default_surname)

        class Meta:
            rdf_type = schema.Book

    b = Book()

    assert b._id == "http://example.com/book/1"
    assert b.name == "Bill"
    assert b.surname == "Doe"

    book_dict = b.dump()

    assert "@id" in book_dict
    assert book_dict["@id"] == b._id
    assert "http://schema.org/name" in book_dict
    assert b.name == book_dict["http://schema.org/name"]
    assert b.surname == book_dict["http://schema.org/surname"]
示例#13
0
def test_flattened_serialization():
    """Test that we can output flattened jsonld."""
    class Book:
        def __init__(self, _id, name, author):
            self._id = _id
            self.name = name
            self.author = author

    class Author:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    schema = fields.Namespace("http://schema.org/")

    class AuthorSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Person
            model = Author

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        author = fields.Nested(schema.author, AuthorSchema)

        class Meta:
            rdf_type = schema.Book
            model = Book

    a = Author("http://example.com/authors/2", "Douglas Adams")
    b = Book("http://example.com/books/1", "Hitchhikers Guide to the Galaxy",
             a)

    jsonld = BookSchema(flattened=True).dump(b)

    assert len(jsonld) == 2

    book = next(e for e in jsonld if e["@id"] == "http://example.com/books/1")
    author = next(e for e in jsonld
                  if e["@id"] == "http://example.com/authors/2")

    assert "http://schema.org/name" in author
    assert author["http://schema.org/name"][0]["@value"] == a.name
    assert "@id" in author
    assert author["@id"] == a._id
    assert "@type" in author
    assert author["@type"] == ["http://schema.org/Person"]

    assert "http://schema.org/name" in book
    assert book["http://schema.org/name"][0]["@value"] == b.name
    assert "@id" in book
    assert book["@id"] == b._id
    assert "@type" in book
    assert book["@type"] == ["http://schema.org/Book"]
    assert "http://schema.org/author" in book
    assert book["http://schema.org/author"][0]["@id"] == a._id
示例#14
0
def test_annotation_hook_inheritance_with_additional_decorator():
    """Test that inheritance works for hooks declared on annotated classes with decorators other than the hook."""
    schema = fields.Namespace("http://schema.org/")

    def my_decorator(value):
        def actual_decorator(func):
            @functools.wraps(func)
            def wrapper_my_decorator(self, in_data, *args, **kwargs):
                in_data["@id"] += f"dec{value}"
                return func(self, in_data, *args, **kwargs)

            return wrapper_my_decorator

        return actual_decorator

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

            @pre_load
            @my_decorator(1)
            def _preload(self, in_data, **kwargs):
                in_data["@id"] += "hook1"
                return in_data

    class Schoolbook(Book):
        course = fields.String(schema.course)

        def __init__(self, _id, name, course):
            self.course = course
            super().__init__(_id, name)

        class Meta(Book.Meta):
            rdf_type = Book.Meta.rdf_type

            @my_decorator(2)
            @pre_load
            def _preload(self, in_data, **kwargs):
                super()._preload(in_data, **kwargs)
                in_data["@id"] += "hook2"
                return in_data

    data = {
        "@id": "http://example.com/books/1",
        "@type": ["http://schema.org/Book"],
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
        "http://schema.org/course": "Literature",
    }

    book = Schoolbook.schema().load(data)

    assert book._id.endswith("dec2dec1hook1hook2")
示例#15
0
def test_nested_reverse_serialization():
    class Book:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    class Author:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name
            self.books = []

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Book
            model = Book

    class AuthorSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        books = fields.Nested(schema.author,
                              BookSchema,
                              reverse=True,
                              many=True)

        class Meta:
            rdf_type = schema.Person
            model = Author

    b = Book("http://example.com/books/1", "Hitchhikers Guide to the Galaxy")
    a = Author("http://example.com/authors/2", "Douglas Adams")
    a.books.append(b)

    jsonld = AuthorSchema().dump(a)

    assert "http://schema.org/name" in jsonld
    assert jsonld["http://schema.org/name"] == a.name
    assert "@id" in jsonld
    assert jsonld["@id"] == a._id
    assert "@type" in jsonld
    assert jsonld["@type"] == ["http://schema.org/Person"]

    assert "@reverse" in jsonld
    reverse = jsonld["@reverse"]
    assert "http://schema.org/author" in reverse
    book = reverse["http://schema.org/author"][0]

    assert "http://schema.org/name" in book
    assert book["http://schema.org/name"] == b.name
    assert "@id" in book
    assert book["@id"] == b._id
    assert "@type" in book
    assert book["@type"] == ["http://schema.org/Book"]
示例#16
0
def test_annotation_without_inheritance_multiple():
    """Test that inheritance works for annotated classes with type inheritance enabled selectively."""
    schema = fields.Namespace("http://schema.org/")

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

    class Schoolbook(Book):
        course = fields.String(schema.course)

        def __init__(self, _id, name, course):
            self.course = course
            super().__init__(_id, name)

        class Meta:
            rdf_type = schema.SchoolBook
            inherit_parent_types = False

    class Biologybook(Schoolbook):
        topic = fields.String(schema.topic)

        def __init__(self, _id, name, course, topic):
            self.topic = topic
            super().__init__(_id, name, course)

        class Meta:
            rdf_type = schema.BiologyBook
            inherit_parent_types = True

    data = {
        "@id": "http://example.com/books/1",
        "@type":
        ["http://schema.org/BiologyBook", "http://schema.org/SchoolBook"],
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
        "http://schema.org/course": "Literature",
        "http://schema.org/topic": "Genetics",
    }

    book = Biologybook.schema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"
    assert book.course == "Literature"
    assert book.topic == "Genetics"

    dumped = Biologybook.schema().dump(book)
    assert data == dumped

    dumped = book.dump()
    assert data == dumped
示例#17
0
def test_annotation_hook_interrupted_inheritance():
    """Test that inheritance works for occasional hooks declared on annotated classes."""
    schema = fields.Namespace("http://schema.org/")

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

            @pre_load
            def _preload(self, in_data, **kwargs):
                in_data["@id"] += "hook1"
                return in_data

    class Schoolbook(Book):
        course = fields.String(schema.course)

        def __init__(self, _id, name, course):
            self.course = course
            super().__init__(_id, name)

        class Meta:
            rdf_type = Book.Meta.rdf_type

    class Biologybook(Schoolbook):
        topic = fields.String(schema.topic)

        def __init__(self, _id, name, course, topic):
            self.topic = topic
            super().__init__(_id, name, course)

        class Meta:
            rdf_type = schema.BiologyBook

            @pre_load
            def _preload(self, in_data, **kwargs):
                super()._preload(in_data, **kwargs)
                in_data["@id"] += "hook2"
                return in_data

    data = {
        "@id": "http://example.com/books/1",
        "@type": ["http://schema.org/BiologyBook"],
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
        "http://schema.org/course": "Literature",
        "http://schema.org/topic": "Genetics",
    }

    book = Biologybook.schema().load(data)

    assert book._id.endswith("hook1hook2")
示例#18
0
def test_nested_flattened_deserialization():
    """Test deserialisation of flattened jsonld."""

    class Book:
        def __init__(self, _id, name, author):
            self._id = _id
            self.name = name
            self.author = author

    class Author:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    schema = fields.Namespace("http://schema.org/")

    class AuthorSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Person
            model = Author

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        author = fields.Nested(schema.author, AuthorSchema)

        class Meta:
            rdf_type = schema.Book
            model = Book

    data = [
        {
            "@id": "http://example.com/authors/2",
            "@type": ["http://schema.org/Person"],
            "http://schema.org/name": [{"@value": "Douglas Adams"}],
        },
        {
            "@id": "http://example.com/books/1",
            "@type": ["http://schema.org/Book"],
            "http://schema.org/author": [{"@id": "http://example.com/authors/2"}],
            "http://schema.org/name": [{"@value": "Hitchhikers Guide to the Galaxy"}],
        },
    ]

    book = BookSchema(flattened=True).load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"

    author = book.author

    assert author.name == "Douglas Adams"
    assert author._id == "http://example.com/authors/2"
示例#19
0
def test_simple_verification_serialization():
    """The ontology doesn't contain the property of publishedYear so it shoudn't be included in the jsonld returned"""
    class Book:
        def __init__(self, _id, name, author, publishedYear):
            self._id = _id
            self.name = name
            self.author = author
            self.publishedYear = publishedYear

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        author = fields.String(schema.author)
        publishedYear = fields.Integer(schema.publishedYear)

        class Meta:
            rdf_type = schema.Book
            model = Book

    book = Book(_id="http://example.com/books/1",
                name="The Great Gatsby",
                author="F. Scott Fitzgerald",
                publishedYear=1925)

    jsonld_pure = BookSchema().dump(book)

    with pytest.raises(ValueError,
                       match="Invalid properties found in ontology.*"):
        jsonld_validated = BookSchema().validate_properties(
            book,
            "tests/fixtures/book_ontology.owl",
            return_valid_data=True,
            strict=True)

    jsonld_validated = BookSchema().validate_properties(
        book, "tests/fixtures/book_ontology.owl", return_valid_data=True)

    assert "http://schema.org/name" in jsonld_validated
    assert jsonld_validated["http://schema.org/name"] == book.name
    assert "@id" in jsonld_validated
    assert jsonld_validated["@id"] == book._id
    assert "@type" in jsonld_validated
    assert jsonld_validated["@type"] == ["http://schema.org/Book"]
    assert "http://schema.org/author" in jsonld_validated
    assert jsonld_validated["http://schema.org/author"] == book.author

    assert "http://schema.org/publishedYear" not in jsonld_validated
    assert "http://schema.org/publishedYear" in jsonld_pure
示例#20
0
def test_annotation_hook_inheritance_with_extra_closure():
    """Test that inheritance works for hooks declared on annotated classes with extra closures in the hook."""
    schema = fields.Namespace("http://schema.org/")

    x = 3
    y = 4

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

            @pre_load
            def _preload(self, in_data, **kwargs):
                in_data["@id"] += f"hook{x}"
                return in_data

    class Schoolbook(Book):
        course = fields.String(schema.course)

        def __init__(self, _id, name, course):
            self.course = course
            super().__init__(_id, name)

        class Meta(Book.Meta):
            rdf_type = Book.Meta.rdf_type

            @pre_load
            def _preload(self, in_data, **kwargs):
                super()._preload(in_data, **kwargs)
                in_data["@id"] += f"hook{y}"
                return in_data

    data = {
        "@id": "http://example.com/books/1",
        "@type": ["http://schema.org/Book"],
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
        "http://schema.org/course": "Literature",
    }

    book = Schoolbook.schema().load(data)

    assert book._id.endswith(f"hook{x}hook{y}")
示例#21
0
def test_schema_hierarchy():
    class Entity:
        def __init__(self, _id):
            self._id = _id

    class CreativeWork(Entity):
        pass

    class Dataset(CreativeWork):
        pass

    prov = fields.Namespace("http://www.w3.org/ns/prov#")
    schema = fields.Namespace("http://schema.org/")

    class EntitySchema(JsonLDSchema):
        _id = fields.Id()

        class Meta:
            rdf_type = [prov.Entity, prov.Location]
            model = Entity

    class CreativeWorkSchema(EntitySchema):
        class Meta:
            rdf_type = schema.CreativeWork
            model = CreativeWork

    class DatasetSchema(CreativeWorkSchema):
        class Meta:
            rdf_type = schema.Dataset
            model = Dataset

    assert EntitySchema.opts.rdf_type == sorted([prov.Entity, prov.Location])
    assert CreativeWorkSchema.opts.rdf_type == sorted(
        [prov.Entity, prov.Location, schema.CreativeWork])
    assert DatasetSchema.opts.rdf_type == sorted(
        [prov.Entity, prov.Location, schema.CreativeWork, schema.Dataset])
示例#22
0
def test_namespace_verification():
    """The ontology doesn't contain the property of publishedYear so it shoudn't be included in the jsonld returned"""

    schema = fields.Namespace("http://schema.org/",
                              ontology="tests/fixtures/book_ontology.owl")

    with pytest.raises(
            ValueError,
            match=
            "Property publishedYear does not exist in namespace http://schema.org/"
    ):
        schema.publishedYear

    # this should not throw an exception, so the test passes
    assert schema.name
    assert schema.author
示例#23
0
def test_missing_reverse_nested_deserialization():
    class Book:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    class Author:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name
            self.books = []

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Book
            model = Book

    class AuthorSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        books = fields.Nested(schema.author,
                              BookSchema,
                              reverse=True,
                              many=True)

        class Meta:
            rdf_type = schema.Person
            model = Author

    data = {
        "@id": "http://example.com/authors/2",
        "@type": "http://schema.org/Person",
        "http://schema.org/name": "Douglas Adams",
    }

    author = AuthorSchema().load(data)

    assert author.name == "Douglas Adams"
    assert author._id == "http://example.com/authors/2"
    assert len(author.books) == 0
示例#24
0
def test_annotation_inheritance():
    """Test that inheritance works for annotated classes."""
    schema = fields.Namespace("http://schema.org/")

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

    class Schoolbook(Book):
        course = fields.String(schema.course)

        def __init__(self, _id, name, course):
            self.course = course
            super().__init__(_id, name)

        class Meta(Book.Meta):
            rdf_type = Book.Meta.rdf_type

    data = {
        "@id": "http://example.com/books/1",
        "@type": ["http://schema.org/Book"],
        "http://schema.org/name": "Hitchhikers Guide to the Galaxy",
        "http://schema.org/course": "Literature",
    }

    book = Schoolbook.schema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"
    assert book.course == "Literature"

    dumped = Schoolbook.schema().dump(book)
    assert data == dumped

    dumped = book.dump()
    assert data == dumped
示例#25
0
def test_blank_node_serialization():
    """Test serialization with blank-node ids."""
    class A(object):
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    class B(object):
        def __init__(self, _id, value):
            self._id = _id
            self.value = value

    schema = fields.Namespace("http://schema.org/")

    class ASchema(JsonLDSchema):
        _id = fields.BlankNodeId()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.A
            model = A

    class BSchema(JsonLDSchema):
        _id = fields.BlankNodeId()
        value = fields.Nested(schema.specifiedBy, ASchema)

        class Meta:
            rdf_type = schema.B
            model = B

    b = B("dummyid2", A("dummyid1", "test"))

    jsonld = BSchema().dump(b)

    assert "@id" in jsonld
    assert jsonld["@id"] == "_:dummyid2"
    assert "http://schema.org/specifiedBy" in jsonld

    dumped_a = jsonld["http://schema.org/specifiedBy"]

    assert "@id" in dumped_a
    assert dumped_a["@id"] == "_:dummyid1"
示例#26
0
def test_generated_id_deserialization():
    """Test deserialization with `id_generation_strategy` used."""
    class A(object):
        def __init__(self, name):
            self.name = name

    class B(object):
        def __init__(self, value):
            self.value = value

    schema = fields.Namespace("http://schema.org/")

    class ASchema(JsonLDSchema):
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.A
            model = A
            id_generation_strategy = blank_node_id_strategy

    class BSchema(JsonLDSchema):
        value = fields.Nested(schema.specifiedBy, ASchema)

        class Meta:
            rdf_type = schema.B
            model = B
            id_generation_strategy = blank_node_id_strategy

    data = {
        "@id": "_:cd54868014124a1e91420cbba92b507e",
        "@type": ["http://schema.org/B"],
        "http://schema.org/specifiedBy": {
            "@id": "_:68bde922a8d1479cb66c705f7a0c8498",
            "@type": ["http://schema.org/A"],
            "http://schema.org/name": "test",
        },
    }

    b = BSchema().load(data)

    assert b.value
    assert b.value.name == "test"
def test_nested_reverse_deserialization(data):
    class Book:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name

    class Author:
        def __init__(self, _id, name):
            self._id = _id
            self.name = name
            self.books = []

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.Book
            model = Book

    class AuthorSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        books = fields.Nested(schema.author,
                              BookSchema,
                              reverse=True,
                              many=True)

        class Meta:
            rdf_type = schema.Person
            model = Author

    author = AuthorSchema().load(data)

    assert author.name == "Douglas Adams"
    assert author._id == "http://example.com/authors/2"
    assert len(author.books) == 1
    assert author.books[0]._id == "http://example.com/books/1"
    assert author.books[0].name == "Hitchhikers Guide to the Galaxy"
示例#28
0
def test_blank_node_id_generation():
    """Test serialization with generated blank-node ids."""
    class A(object):
        def __init__(self, name):
            self.name = name

    class B(object):
        def __init__(self, value):
            self.value = value

    schema = fields.Namespace("http://schema.org/")

    class ASchema(JsonLDSchema):
        name = fields.String(schema.name)

        class Meta:
            rdf_type = schema.A
            model = A
            id_generation_strategy = blank_node_id_strategy

    class BSchema(JsonLDSchema):
        value = fields.Nested(schema.specifiedBy, ASchema)

        class Meta:
            rdf_type = schema.B
            model = B
            id_generation_strategy = blank_node_id_strategy

    b = B(A("test"))

    jsonld = BSchema().dump(b)

    assert "@id" in jsonld
    assert jsonld["@id"].startswith("_:")
    assert "http://schema.org/specifiedBy" in jsonld

    dumped_a = jsonld["http://schema.org/specifiedBy"]

    assert "@id" in dumped_a
    assert dumped_a["@id"].startswith("_:")
示例#29
0
def test_nested_annotation():
    """Test that nesting works for annotated classes."""

    schema = fields.Namespace("http://schema.org/")

    class Book(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)

        def __init__(self, _id, name):
            self._id = _id
            self.name = name

        class Meta:
            rdf_type = schema.Book

    class Author(metaclass=JsonLDAnnotation):
        _id = fields.Id()
        name = fields.String(schema.name)
        books = fields.Nested(schema.author, Book, reverse=True, many=True)

        def __init__(self, _id, name, books):
            self._id = _id
            self.name = name
            self.books = books

        class Meta:
            rdf_type = schema.Person

    b = Book("http://example.com/book/1", "Le Petit Prince")
    a = Author("http://example.com/authors/1", "Antoine de Saint-Exupéry", [b])

    author_dict = a.dump()

    assert "@reverse" in author_dict
    assert "http://schema.org/author" in author_dict["@reverse"]
    books = author_dict["@reverse"]["http://schema.org/author"]
    assert len(books) == 1
    assert books[0]["http://schema.org/name"] == b.name
示例#30
0
def test_simple_deserialization():
    class Book:
        def __init__(self,
                     _id,
                     name="Hitchhikers Guide to the Galaxy",
                     copyright_year=1979,
                     **kwargs):
            self._id = _id
            self.name = name
            self.copyright_year = copyright_year
            for k, v in kwargs.items():
                setattr(self, k, v)

    schema = fields.Namespace("http://schema.org/")

    class BookSchema(JsonLDSchema):
        _id = fields.Id()
        name = fields.String(schema.name)
        isbn = fields.String(schema.isbn)
        copyright_year = fields.Integer(schema.copyrightYear)

        class Meta:
            rdf_type = schema.Book
            model = Book

    data = {
        "@id": "http://example.com/books/1",
        "@type": "http://schema.org/Book",
        "http://schema.org/isbn": "0-330-25864-8",
        "http://schema.org/copyrightYear": 1979,
    }

    book = BookSchema().load(data)

    assert book._id == "http://example.com/books/1"
    assert book.name == "Hitchhikers Guide to the Galaxy"
    assert book.isbn == "0-330-25864-8"
    assert book.copyright_year == 1979