Esempio n. 1
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)
Esempio n. 2
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)
Esempio n. 3
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)
def test_marshal():
    """Test that data of an embedded representation is properly marshaled.

    1. Create an embedded representation.
    2. Create an embedded representation marshaler for the representation.
    3. Replace marshaler methods so that they return predefined data.
    4. Marshal the representation.
    5. Check the marshaled data.
    """
    marshaler = RepresentationMarshaler(
        marshaler=JSONMarshaler(),
        embedded_representation=EmbeddedRepresentation(relations=["self"]),
    )
    marshaler.marshal_relations = lambda: "marshal_relations"
    marshaler.marshal_classes = lambda: "marshal_classes"
    marshaler.marshal_properties = lambda: "marshal_properties"
    marshaler.marshal_entities = lambda: "marshal_entities"
    marshaler.marshal_links = lambda: "marshal_links"
    marshaler.marshal_actions = lambda: "marshal_actions"
    marshaler.marshal_title = lambda: "marshal_title"

    actual_data = marshaler.marshal()
    expected_data = {
        "rel": "marshal_relations",
        "class": "marshal_classes",
        "properties": "marshal_properties",
        "entities": "marshal_entities",
        "links": "marshal_links",
        "actions": "marshal_actions",
        "title": "marshal_title",
    }
    assert actual_data == expected_data, "Embedded represenation is not properly marshaled"
def test_default_title():
    """Check default title of an embedded representation.

    1. Create an embedded representation without specifying a title.
    2. Check the title of the representation.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS)
    assert representation.title is None, "Wrong title"
def test_default_classes():
    """Check default classes of an embedded representation.

    1. Create an embedded representation without specifying classes.
    2. Check classes of the representation.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS)
    assert representation.classes == (), "Wrong classes"
def test_links(links):
    """Check links of an embedded representation.

    1. Create an embedded representation with different number of links.
    2. Get links of the representation.
    3. Check the links.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS, links=links)
    assert representation.links == tuple(links), "Wrong links"
def test_classes(classes, expected_classes):
    """Check classes of an embedded representation.

    1. Create an embedded representation with different classes.
    2. Get classes of the representation.
    3. Check the classes.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS, classes=classes)
    assert representation.classes == expected_classes, "Wrong classes"
def test_default_subentities():
    """Check default set of subentities of an embedded representation.

    1. Create an embedded representation without specifying subentities.
    2. Get subentities of the representation.
    3. Check the subentities.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS)
    assert representation.entities == (), "Wrong subentities"
def test_actions(actions):
    """Check actions of an embedded representation.

    1. Create an embedded representation with different number of actions.
    2. Get actions of the representation.
    3. Check the actions.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS, actions=actions)
    assert representation.actions == tuple(actions), "Wrong actions"
def test_default_actions():
    """Check default set of actions of an embedded representation.

    1. Create an embedded representation without specifying actions.
    2. Get actions of the representation.
    3. Check the actions.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS)
    assert representation.actions == (), "Wrong actions"
def test_relations(relations, expected_relations):
    """Test relations of an embedded representation.

    1. Create an embedded representation with different relations.
    2. Get relations.
    3. Check the relations.
    """
    representation = EmbeddedRepresentation(relations=relations)
    assert representation.relations == expected_relations, "Wrong relations"
def test_title(title, expected_title):
    """Check title of an embedded representation.

    1. Create an embedded representation with different titles.
    2. Get title of the representation.
    3. Check the title.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS, title=title)
    assert representation.title == expected_title, "Wrong title"
def test_subentities(entities):
    """Check subentities of an embedded representation.

    1. Create an embedded representation with different sets of subentities.
    2. Get subentities of the representation.
    3. Check the subentities.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS, entities=entities)
    assert representation.entities == tuple(entities), "Wrong subentities"
def test_invalid_classes():
    """Check that ValueError is raised if invalid classes are passed.

    1. Try to create an embedded representation with non-iterable classes.
    2. Check that ValueError is raised.
    """
    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=DEFAULT_RELATIONS, classes=1)

    assert error_info.value.args[0] == "Classes must be iterable with string values"
def test_invalid_relations():
    """Check that ValueError is raised if invalid relations are passed.

    1. Try to create an embedded representation with non-iterable relations.
    2. Check that ValueError is raised.
    """
    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=None)

    assert error_info.value.args[0] == "Relations must be iterable with string values"
def test_incompatible_subentities(entities):
    """Check that ValueError is raised if at least one of the entities is of incompatible type.

    1. Try to create an embedded representation with incompatible type of subentity.
    2. Check that ValueError is raised.
    3. Check the error message.
    """
    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=DEFAULT_RELATIONS, entities=entities)

    assert error_info.value.args[0] == "Some of the entities are of incompatible type"
def test_invalid_properties(properties, error_message):
    """Check that ValueError is raised if invalid properties are passed.

    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"
def test_missing_relations():
    """Check that ValueError is raised if relations list is empty.

    1. Try to create an embedded representation with empty list of relations.
    2. Check that ValueError is raised.
    3. Check error message.
    """
    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=[])

    expected_message = "No relations are passed to create an embedded representation"
    assert error_info.value.args[0] == expected_message, "Wrong error message"
Esempio n. 20
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)
Esempio n. 21
0
def test_marshal_embedded_representation():
    """Check that NotImplementedError is raised if marshal_embedded_representation is called.

    1. Create an instance of Marshaler class.
    2. Try to marshal an embedded representation.
    3. Check that NotImplementedError is raised.
    4. Check the error message.
    """
    representation = EmbeddedRepresentation(relations=["self"])

    with pytest.raises(NotImplementedError) as error_info:
        Marshaler().marshal_embedded_representation(embedded_representation=representation)

    assert error_info.value.args[0] == "Marshaler does not support siren embedded representation"
def test_properties(properties, expected_properties):
    """Check properties of an embedded representation.

    1. Create an embedded representation with different properties.
    2. Get properties of the representation.
    3. Check the properties.
    4. Change the retrieved dictionary.
    5. Get properties of the representation again.
    6. Check that properties have not been updated.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS, properties=properties)
    actual_properties = representation.properties
    assert actual_properties == expected_properties, "Wrong properties"

    actual_properties["new-key"] = "new value"
    assert representation.properties == expected_properties, "Wrong properies"
def test_default_properties():
    """Check default properties of an embedded representation.

    1. Create an embedded representation without specifying properties.
    2. Get properties of the representation.
    3. Check the properties.
    4. Change the retrieved dictionary.
    5. Get properties of the representation again.
    6. Check that properties have not been updated.
    """
    representation = EmbeddedRepresentation(relations=DEFAULT_RELATIONS)
    actual_properties = representation.properties
    assert actual_properties == {}, "Wrong properties"

    actual_properties["new-key"] = "new value"
    assert representation.properties == {}, "Wrong properies"
def test_duplicated_action_names():
    """Check that ValueError is raised if some of the actions have the same name.

    1. Create 2 actions with the same name.
    1. Try to create an embedded representation with the created actions.
    2. Check that ValueError is raised.
    3. Check the error message.
    """
    actions = [
        Action(name="duplicate", target="/first", title="First action with non-unique name"),
        Action(name="unique", target="/second", title="Action with unique name"),
        Action(name="duplicate", target="/third", title="Second action with non-unique name"),
        ]

    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=DEFAULT_RELATIONS, actions=actions)

    assert error_info.value.args[0] == "Some of the actions have the same name", "Wrong error"
Esempio n. 25
0
def test_default_embedded_representation(monkeypatch):
    """Test that json marshaler use EmbeddedRepresentationMarshaler to marshal a representation.

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

    marshaled_representation = JSONMarshaler().marshal_embedded_representation(
        embedded_representation=EmbeddedRepresentation(relations=["self"]),
        )
    assert marshaled_representation == "Marshaled embedded representation", (
        "Wrong data of the embedded representation"
        )
Esempio n. 26
0
def test_custom_embedded_representation_marshaler():
    """Test that json marshaler use custom marshaler to marshal an embedded representation.

    1. Create a sub-class of JSONMarshaler with redefined create_embedded_representation_marshaler
       factory.
    2. Create json marshaler from the sub-class.
    3. Marshal an embedded representation.
    4. Check that custom marshaler is used to marshal an embedded representation.
    """
    class _CustomEmbeddedRepresentationMarshaler(JSONMarshaler):
        create_embedded_representation_marshaler = _CustomMarshaler(
            "Custom marshaled embedded representation",
            )

    marshaler = _CustomEmbeddedRepresentationMarshaler()
    marshaled_representation = marshaler.marshal_embedded_representation(
        embedded_representation=EmbeddedRepresentation(relations=["self"]),
        )
    assert marshaled_representation == "Custom marshaled embedded representation", (
        "Wrong data of the embedded representation"
        )
Esempio n. 27
0
    def parse(self):
        """Parse the embedded representation.

        :returns: :class:`EmbeddedRepresentation <lila.core.entity.EmbeddedRepresentation>`.
        :raises: :class:ValueError.
        """
        logger = logging.getLogger(__name__)
        logger.debug("Try to parse an embedded representation")

        representation_relations = self.parse_relations()
        representation_classes = self.parse_classes()
        representation_properties = self.parse_properties()
        representation_entities = self.parse_entities()
        representation_links = self.parse_links()
        representation_actions = self.parse_actions()
        representation_title = self.parse_title()

        try:
            representation = EmbeddedRepresentation(
                relations=representation_relations,
                classes=representation_classes,
                properties=representation_properties,
                entities=representation_entities,
                links=representation_links,
                actions=representation_actions,
                title=representation_title,
            )
        except Exception as error:
            logger.error(
                "Failed to create an embedded representation with provided data"
            )
            raise ValueError(
                "Failed to create an embedded representation with provided data",
            ) from error
        else:
            logger.info("Successfully parsed an embedded representation")

        return representation
        ]

    with pytest.raises(ValueError) as error_info:
        EmbeddedRepresentation(relations=DEFAULT_RELATIONS, actions=actions)

    assert error_info.value.args[0] == "Some of the actions have the same name", "Wrong error"


@pytest.mark.parametrize(
    argnames="entities",
    argvalues=[
        [],
        [EmbeddedLink(relations=["self"], target="/self")],
        [
            EmbeddedRepresentation(
                relations=["self"],
                entities=[EmbeddedRepresentation(relations=["self"])],
            ),
        ],
        [
            EmbeddedRepresentation(relations=["first"]),
            EmbeddedLink(relations=["second"], target="/second"),
            EmbeddedRepresentation(relations=["third"]),
            EmbeddedLink(relations=["forth"], target="/forth"),
        ],
    ],
    ids=[
        "Without entities",
        "Single embedded link",
        "Single embedded representation with subentities",
        "Several enitities of different types",
    ],
    marshaler = RepresentationMarshaler(
        marshaler=JSONMarshaler(),
        embedded_representation=SubEntitiesRepresentation(entities=None),
    )
    with pytest.raises(ValueError) as error_info:
        marshaler.marshal_entities()

    expected_message = "Failed to iterate over sub-entities of the embedded representation"
    assert error_info.value.args[0] == expected_message, "Wrong error"


@pytest.mark.parametrize(
    argnames="sub_entity",
    argvalues=[
        EmbeddedLink(target="/embedded/link", relations=["relation"]),
        EmbeddedRepresentation(relations=["relation"]),
    ],
    ids=[
        "Link",
        "Representation",
    ],
)
def test_non_marshalable_sub_entities(sub_entity):
    # pylint: disable=line-too-long
    """Test that ValueError is raised if one of sub-entities of the embedded representation is not marshallable.

    1. Create json marshaler that raises exception when either marshal_embedded_link or
       marshal_embedded_representation is called.
    2. Create an embedded representation marshaler.
    3. Try to call marshal_entities method.
    4. Check that ValueError is raised.
Esempio n. 30
0
               title="Second action with non-unique name"),
    ]

    with pytest.raises(ValueError) as error_info:
        Entity(actions=actions)

    assert error_info.value.args[
        0] == "Some of the actions have the same name", "Wrong error"


@pytest.mark.parametrize(
    argnames="entities",
    argvalues=[
        [],
        [EmbeddedLink(relations=["self"], target="/self")],
        [EmbeddedRepresentation(relations=["self"])],
        [
            EmbeddedLink(relations=["first"], target="/first"),
            EmbeddedRepresentation(relations=["second"]),
            EmbeddedLink(relations=["third"], target="/third"),
            EmbeddedRepresentation(relations=["forth"]),
        ],
    ],
    ids=[
        "Without entities",
        "Single embedded link",
        "Single embedded representation",
        "Several enitities of different types",
    ],
)
def test_subentities(entities):