Example #1
0
def test_parse(component_validator):
    """Test that entity data is properly parsed.

    1. Create an entity.
    2. Create an entity parser.
    3. Replace parser methods so that they return predefined data.
    4. Parse the entity.
    5. Check the entity data.
    """
    entity = Entity(
        classes=("parsed class 1", "parsed class 2"),
        properties={
            "property 1": 1,
            "property 2": [1, 2]
        },
        entities=(
            EmbeddedLink(target="/embedded/link/target",
                         relations=["relation"]),
            EmbeddedRepresentation(relations=["relation"]),
        ),
        links=[Link(target="/link/target", relations=["relation"])],
        actions=[Action(target="/action/target", name="action")],
        title="parsed title",
    )

    parser = EntityParser(data={}, parser=JSONParser())
    parser.parse_classes = lambda: entity.classes
    parser.parse_properties = lambda: entity.properties
    parser.parse_entities = lambda: entity.entities
    parser.parse_links = lambda: entity.links
    parser.parse_actions = lambda: entity.actions
    parser.parse_title = lambda: entity.title

    actual_entity = parser.parse()
    component_validator.validate_entity(actual_entity, entity)
Example #2
0
    def parse(self):
        """Parse the link.

        :returns: :class:`Link <lila.core.link.Link>`.
        :raises: :class:ValueError.
        """
        logger = logging.getLogger(__name__)
        logger.debug("Try to parse a link")

        link_relations = self.parse_relations()
        link_classes = self.parse_classes()
        link_target = self.parse_target()
        link_title = self.parse_title()
        link_target_media_type = self.parse_target_media_type()

        try:
            link = Link(
                relations=link_relations,
                classes=link_classes,
                target=link_target,
                title=link_title,
                target_media_type=link_target_media_type,
            )
        except Exception as error:
            logger.error("Failed to create a link with provided data")
            raise ValueError(
                "Failed to create a link with provided data") from error
        else:
            logger.info("Successfully parsed a link")

        return link
def test_non_marshalable_links():
    # pylint: disable=line-too-long
    """Test that ValueError is raised if one of links of the embedded representation is not marshallable.

    1. Create json marshaler that raises exception when marshal_link method is called.
    2. Create an embedded representation marshaler.
    3. Try to call marshal_links method.
    4. Check that ValueError is raised.
    5. Check the error message.
    """

    # pylint: enable=line-too-long
    class _LinkErrorMarshaler(JSONMarshaler):
        def marshal_link(self, link):
            raise Exception()

    LinksRepresentation = namedtuple("LinksRepresentation", "links")

    links = [Link(relations=["first"], target="/first")]
    marshaler = RepresentationMarshaler(
        marshaler=_LinkErrorMarshaler(),
        embedded_representation=LinksRepresentation(links=links),
    )
    with pytest.raises(ValueError) as error_info:
        marshaler.marshal_links()

    expected_message = "Failed to marshal links of the embedded representation"
    assert error_info.value.args[0] == expected_message, "Wrong error"
Example #4
0
def test_embedded_representation(component_validator):
    """Test that embedded representation can be marshaled and parsed back.

    1. Create an embedded representation.
    2. Create JSON parser and marshaler.
    3. Marshal the embedded representation.
    4. Parse the data.
    5. Check that parsed embedded representation has the same data as the original one.
    """
    representation = EmbeddedRepresentation(
        relations=["representation relation 1", "representation relation 2"],
        classes=("representation class 1", "representation class 2"),
        properties={
            "representation property 1": 1,
            "representation property 2": [1, 2]
        },
        entities=(
            EmbeddedLink(target="/embedded/link/target",
                         relations=["relation"]),
            EmbeddedRepresentation(relations=["relation"]),
        ),
        links=[Link(target="/link/target", relations=["relation"])],
        actions=[
            Action(target="/action/target", name="representation action")
        ],
        title="representation title",
    )

    representation_data = JSONMarshaler().marshal_embedded_representation(
        representation)
    actual_representation = JSONParser().parse_embedded_representation(
        representation_data)

    component_validator.validate_embedded_representation(
        actual_representation, representation)
Example #5
0
def test_parse(component_validator):
    """Test that link data is properly parsed.

    1. Create a link.
    2. Create a link parser.
    3. Replace parser methods so that they return predefined data.
    4. Parse the link.
    5. Check the parsed data.
    """
    link = Link(
        relations=("parsed relation 1", "parsed relation 2"),
        classes=("parsed class 1", "parsed class 2"),
        title="parsed title",
        target="/parsed/target",
        target_media_type="application/parsed+media+type",
        )

    parser = LinkParser(data={})
    parser.parse_relations = lambda: link.relations
    parser.parse_classes = lambda: link.classes
    parser.parse_target = lambda: link.target
    parser.parse_title = lambda: link.title
    parser.parse_target_media_type = lambda: link.target_media_type

    actual_link = parser.parse()
    component_validator.validate_link(actual_link, link)
Example #6
0
def test_marshal():
    """Test that link data is properly marshaled.

    1. Create a link.
    2. Create a link marshaler for the link.
    3. Replace marshaler methods so that they return predefined data.
    4. Marshal the link.
    5. Check the marshaled data.
    """
    marshaler = LinkMarshaler(Link(relations=["self"], target="/link"))
    marshaler.marshal_relations = lambda: "marshal_relations"
    marshaler.marshal_classes = lambda: "marshal_classes"
    marshaler.marshal_target = lambda: "marshal_target"
    marshaler.marshal_title = lambda: "marshal_title"
    marshaler.marshal_target_media_type = lambda: "marshal_target_media_type"

    actual_data = marshaler.marshal()
    expected_data = {
        "rel": "marshal_relations",
        "class": "marshal_classes",
        "href": "marshal_target",
        "title": "marshal_title",
        "type": "marshal_target_media_type",
    }
    assert actual_data == expected_data, "Field is not properly marshaled"
Example #7
0
def test_entity(component_validator):
    """Test that entity can be marshaled and parsed back.

    1. Create an entity.
    2. Create JSON parser and marshaler.
    3. Marshal the entity.
    4. Parse the data.
    5. Check that parsed entity has the same data as the original one.
    """
    entity = Entity(
        classes=("entity class 1", "entity class 2"),
        properties={
            "entity property 1": 1,
            "entity property 2": [1, 2]
        },
        entities=(
            EmbeddedLink(target="/embedded/link/target",
                         relations=["relation"]),
            EmbeddedRepresentation(relations=["relation"]),
        ),
        links=[Link(target="/link/target", relations=["relation"])],
        actions=[Action(target="/action/target", name="entity action")],
        title="entity title",
    )

    entity_data = JSONMarshaler().marshal_entity(entity)
    actual_entity = JSONParser().parse_entity(entity_data)

    component_validator.validate_entity(actual_entity, entity)
Example #8
0
def test_default_title():
    """Check default title of a link.

    1. Create a link without specifying a title.
    2. Check the title of the link.
    """
    link = Link(relations=DEFAULT_RELATIONS, target="#")
    assert link.title is None, "Wrong title"
Example #9
0
def test_invalid_relations():
    """Check that ValueError is raised if invalid relations are passed.

    1. Try to create a link with non-iterable relations.
    2. Check that ValueError is raised.
    """
    with pytest.raises(ValueError):
        Link(relations=None, target="#")
Example #10
0
def test_default_classes():
    """Check default classes of a link.

    1. Create a link without specifying classes.
    2. Check classes of the link.
    """
    link = Link(relations=DEFAULT_RELATIONS, target="#")
    assert link.classes == (), "Wrong classes"
Example #11
0
def test_invalid_classes():
    """Check that ValueError is raised if invalid classes are passed.

    1. Try to create a link with non-iterable classes.
    2. Check that ValueError is raised.
    """
    with pytest.raises(ValueError):
        Link(relations=DEFAULT_RELATIONS, target="#", classes=1)
Example #12
0
def test_default_target_media_type():
    """Check default target media type of a link.

    1. Create a link without specifying media type of the target.
    2. Check the media type of the target of the link.
    """
    link = Link(relations=DEFAULT_RELATIONS, target="#")
    assert link.target_media_type is None, "Wrong media type"
Example #13
0
def test_relations(relations, expected_relations):
    """Test relations of a link.

    1. Create a link with different relations.
    2. Get relations.
    3. Check the relations.
    """
    link = Link(relations=relations, target="#")
    assert link.relations == expected_relations, "Wrong relations"
Example #14
0
def test_target(target, expected_target):
    """Check target of a link.

    1. Create a link with a target.
    2. Get target.
    3. Check the target.
    """
    link = Link(relations=DEFAULT_RELATIONS, target=target)
    assert link.target == expected_target, "Wrong target"
Example #15
0
def test_classes(classes, expected_classes):
    """Check classes of a link.

    1. Create a link with different classes.
    2. Get classes of the link.
    3. Check the classes.
    """
    link = Link(relations=DEFAULT_RELATIONS, target="#", classes=classes)
    assert link.classes == expected_classes, "Wrong classes"
Example #16
0
def test_title(title, expected_title):
    """Check title of a link.

    1. Create a link with different titles.
    2. Get title of the link.
    3. Check the title.
    """
    link = Link(relations=DEFAULT_RELATIONS, target="#", title=title)
    assert link.title == expected_title, "Wrong title"
Example #17
0
def test_target_media_type(target_media_type):
    """Check target media type of a link.

    1. Create a link with different media types of its target.
    2. Get target media type.
    3. Check the media type.
    """
    link = Link(relations=DEFAULT_RELATIONS,
                target="#",
                target_media_type=target_media_type)
    assert link.target_media_type == target_media_type, "Wrong media type"
Example #18
0
def test_marshal_link():
    """Check that NotImplementedError is raised if marshal_link is called.

    1. Create an instance of Marshaler class.
    2. Try to marshal a link.
    3. Check that NotImplementedError is raised.
    4. Check the error message.
    """
    with pytest.raises(NotImplementedError) as error_info:
        Marshaler().marshal_link(link=Link(relations=["self"], target="/link"))

    assert error_info.value.args[0] == "Marshaler does not support siren links"
Example #19
0
def test_default_link_marshaler(monkeypatch):
    """Test that json marshaler use LinkMarshaler to marshal a link.

    1. Create json marshaler.
    2. Replace marshal method of LinkMarshaler so that it returns fake data.
    3. Marshal a link.
    4. Check that returned data are the same as ones from the mocked method.
    """
    monkeypatch.setattr(LinkMarshaler, "marshal", lambda self: "Marshaled link")

    marshaled_link = JSONMarshaler().marshal_link(link=Link(relations=(), target="/target"))
    assert marshaled_link == "Marshaled link", "Wrong link data"
Example #20
0
def test_custom_link_marshaler():
    """Test that json marshaler use custom marshaler to marshal a link.

    1. Create a sub-class of JSONMarshaler with redefined create_link_marshaler factory.
    2. Create json marshaler from the sub-class.
    3. Marshal a link.
    4. Check that custom marshaler is used to marshal a link.
    """
    class _CustomLinkMarshaler(JSONMarshaler):
        create_link_marshaler = _CustomMarshaler("Custom marshaled link")

    marshaled_link = _CustomLinkMarshaler().marshal_link(link=Link(relations=(), target="/target"))
    assert marshaled_link == "Custom marshaled link", "Wrong link data"
Example #21
0
def test_link(component_validator):
    """Test that link can be marshaled and parsed back.

    1. Create a link.
    2. Create JSON parser and marshaler.
    3. Marshal the link.
    4. Parse the data.
    5. Check that parsed link has the same data as the original one.
    """
    link = Link(
        relations=("link relation 1", "link relation 2"),
        classes=("link class 1", "link class 2"),
        title="link title",
        target="/link/target",
        target_media_type="application/link",
    )

    link_data = JSONMarshaler().marshal_link(link)
    actual_link = JSONParser().parse_link(link_data)

    component_validator.validate_link(actual_link, link)
Example #22
0
def test_parse(component_validator):
    """Test that data of embedded representation is properly parsed.

    1. Create an embedded representation.
    2. Create an embedded representation parser.
    3. Replace parser methods so that they return predefined data.
    4. Parse the embedded representation.
    5. Check the data of the embedded representation.
    """
    representation = EmbeddedRepresentation(
        relations=["parsed relation"],
        classes=("parsed class 1", "parsed class 2"),
        properties={
            "property 1": 1,
            "property 2": [1, 2]
        },
        entities=(
            EmbeddedLink(target="/embedded/link/target",
                         relations=["relation"]),
            EmbeddedRepresentation(relations=["relation"]),
        ),
        links=[Link(target="/link/target", relations=["relation"])],
        actions=[Action(target="/action/target", name="action")],
        title="parsed title",
    )

    parser = EmbeddedRepresentationParser(data={}, parser=JSONParser())
    parser.parse_relations = lambda: representation.relations
    parser.parse_classes = lambda: representation.classes
    parser.parse_properties = lambda: representation.properties
    parser.parse_entities = lambda: representation.entities
    parser.parse_links = lambda: representation.links
    parser.parse_actions = lambda: representation.actions
    parser.parse_title = lambda: representation.title

    actual_representation = parser.parse()
    component_validator.validate_embedded_representation(
        actual_representation, representation)
Example #23
0
def test_non_marshalable_links():
    """Test that ValueError is raised if one of links of the entity is not marshallable.

    1. Create json marshaler that raises exception when marshal_link method is called.
    2. Create an entity marshaler.
    3. Try to call marshal_links method.
    4. Check that ValueError is raised.
    5. Check the error message.
    """
    class _LinkErrorMarshaler(JSONMarshaler):
        def marshal_link(self, link):
            raise Exception()

    LinksEntity = namedtuple("LinksEntity", "links")

    links = [Link(relations=["first"], target="/first")]
    marshaler = EntityMarshaler(marshaler=_LinkErrorMarshaler(),
                                entity=LinksEntity(links=links))
    with pytest.raises(ValueError) as error_info:
        marshaler.marshal_links()

    assert error_info.value.args[
        0] == "Failed to marshal entity's links", "Wrong error"
    marshaler = RepresentationMarshaler(
        marshaler=_LinkErrorMarshaler(),
        embedded_representation=LinksRepresentation(links=links),
    )
    with pytest.raises(ValueError) as error_info:
        marshaler.marshal_links()

    expected_message = "Failed to marshal links of the embedded representation"
    assert error_info.value.args[0] == expected_message, "Wrong error"


@pytest.mark.parametrize(
    argnames="links",
    argvalues=[
        [],
        [Link(target="/single", relations=["self"])],
        [
            Link(target="/prev", relations=["prev"]),
            Link(target="/next", relations=["next"])
        ],
    ],
    ids=[
        "Empty list",
        "Single link",
        "Multiple links",
    ],
)
def test_links(links):
    """Test that links are properly marshaled.

    1. Create an embedded representation marshaler.
Example #25
0
    1. Try to create an entity with invalid properties.
    2. Check that ValueError is raised.
    3. Check the error message.
    """
    with pytest.raises(ValueError) as error_info:
        Entity(properties=properties)

    assert error_info.value.args[0] == error_message, "Wrong error message"


@pytest.mark.parametrize(
    argnames="links",
    argvalues=[
        [],
        [Link(relations=["next"], target="/single-link")],
        [
            Link(relations=["next"], target="/first-link"),
            Link(relations="previous", target="/second-link"),
        ],
    ],
    ids=[
        "Without links",
        "Single",
        "Several",
    ],
)
def test_links(links):
    """Check links of an entity.

    1. Create an entity with different number of links.
    1. Try to create an embedded representation with invalid properties.
    2. Check that ValueError is raised.
    3. Check the error message.
    """
    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=DEFAULT_RELATIONS, properties=properties)

    assert error_info.value.args[0] == error_message, "Wrong error message"


@pytest.mark.parametrize(
    argnames="links",
    argvalues=[
        [],
        [Link(relations=["first"], target="/single-link")],
        [
            Link(relations=["first"], target="/first-link"),
            Link(relations="last", target="/second-link"),
        ],
    ],
    ids=[
        "Without links",
        "Single",
        "Several",
    ],
)
def test_links(links):
    """Check links of an embedded representation.

    1. Create an embedded representation with different number of links.