def test_graph_dict_get_graph_type():
    d = GraphDict({OGIT__GRAPH_TYPE: 'vertex'})
    v = d[OGIT__GRAPH_TYPE]
    assert isinstance(v, GraphType)
    d = GraphDict({OGIT__GRAPH_TYPE: 'foo'})
    with pytest.raises(ValueError):
        v = d[OGIT__GRAPH_TYPE]
    d = GraphDict({OGIT__GRAPH_TYPE: GraphType.VERTEX})
    v = d[OGIT__GRAPH_TYPE]
    assert isinstance(v, GraphType)
def test_graph_dict_get_id():
    d = GraphDict({
        OGIT__GRAPH_TYPE: GraphType.VERTEX.value,
        OgitAttribute.OGIT__ID: 'foobar',
        OGIT__TYPE: OgitEntity.OGIT_ATTACHMENT,
    })
    vertex_id = d[OgitAttribute.OGIT__ID.value]
    assert vertex_id is not None
    print(type(vertex_id))
    assert isinstance(vertex_id, BlobId)
Beispiel #3
0
 def test_graph_dict(self):
     for a, b in itertools.permutations((
             FinalAttribute.OGIT__ID, FinalAttribute.OGIT__ID.value,
             ReadOnlyAttribute.OGIT__ID, ReadOnlyAttribute.OGIT__ID.value,
             SystemAttribute.OGIT__ID, SystemAttribute.OGIT__ID.value,
             OgitAttribute.OGIT__ID, OgitAttribute.OGIT__ID.value,
             'ogit/_id', 'ogit:_id',
     ), 2):
         d = GraphDict({a: 'foo'})
         assert b in d
         assert 'foo' == d[b]
Beispiel #4
0
def to_vertex(data: Mapping[str, Any],
              client: HIRO_BASE_CLIENT_T_co) -> VERTEX_T_co:
    vertex_type = GraphDict(data).get(OgitAttribute.OGIT__TYPE)
    e_vertex_type = to_vertex_type(vertex_type)

    if e_vertex_type is OgitEntity.OGIT_ATTACHMENT:
        return BlobVertex(data, client=client, draft=False)
    elif e_vertex_type is OgitEntity.OGIT_DATA_LOG:
        raise NotImplementedError()
    elif e_vertex_type is OgitEntity.OGIT_TIME_SERIES:
        return TimeSeriesVertex(data, client=client, draft=False)
    else:
        return Vertex(data, client=client, draft=False)
def test_graph_dict_onto():
    d = GraphDict({OgitAttribute.OGIT__CONTENT.value: 'foobar'})
    assert isinstance(d, UserDict)
    assert isinstance(d, GraphDict)
    assert d['ogit/_content'] == 'foobar'
    assert d[OgitAttribute.OGIT__CONTENT] == 'foobar'
    assert d[OgitAttribute.OGIT__CONTENT.value] == 'foobar'
    with pytest.raises(KeyError):
        assert d[OGIT__TYPE.value.name.uri] == 'foobar'
    with pytest.raises(KeyError):
        assert d[OGIT__TYPE] == 'foobar'
    with pytest.raises(KeyError):
        assert d[OGIT__TYPE.value] == 'foobar'
Beispiel #6
0
def to_vertex(data: Mapping[ATTRIBUTE_T, Any],
              client: Optional[HIRO_BASE_CLIENT_T_co] = None) -> VERTEX_T_co:
    vertex_type = GraphDict(data).get(OgitAttribute.OGIT__TYPE)

    if vertex_type is OgitEntity.OGIT_CONTRACT:
        return OgitContract(data, client, False)
    if vertex_type is OgitEntity.OGIT_LICENSE:
        return OgitLicense(data, client, False)
    if vertex_type is OgitEntity.OGIT_AUTH_ORGANIZATION:
        return OgitAuthOrganization(data, client, False)
    if vertex_type is OgitEntity.OGIT_AUTH_ACCOUNT:
        return OgitAuthAccount(data, client, False)
    return cast_to_vertex(data, client)
Beispiel #7
0
    def update(self, *args, **kwargs) -> Vertex:
        if not args and not kwargs:
            raise RuntimeError('Missing args and or kwargs')
        vertex: Optional[VERTEX_T] = None
        vertex_id: Optional[Union[VERTEX_ID_T, VERTEX_XID_T_co]] = None
        source_vertex: Optional[VERTEX_T] = None
        if len(args) == 1:
            v = args[0]
            if isinstance(v, Vertex):
                vertex = v
                if v.id:
                    vertex_id = v.id
                elif v.xid:
                    vertex_id = v.xid
            elif isinstance(v, Mapping):
                vertex = GraphDict(v)
                if OgitAttribute.OGIT__ID in vertex:
                    vertex_id = vertex[OgitAttribute.OGIT__ID]
                elif OgitAttribute.OGIT__XID in vertex:
                    vertex_id = vertex[OgitAttribute.OGIT__XID]
                else:
                    raise KeyError(
                        f'Missing {OgitAttribute.OGIT__ID} or {OgitAttribute.OGIT__XID} key in mapping'
                    )
            else:
                raise TypeError(type(v))
            del v
        elif len(args) == 2:
            for i, v in enumerate(args):
                if i == 0:
                    if isinstance(v, (VertexId, ExternalVertexId, str)):
                        vertex_id = v
                    elif isinstance(v, (Vertex, Mapping)):
                        vertex_id = resolve_vertex_id(v, None)
                    else:
                        raise TypeError(type(v))
                elif i == 1:
                    if isinstance(v, (Vertex, Mapping)):
                        vertex = v
                    else:
                        raise TypeError(type(v))
                else:
                    raise RuntimeError('Unreachable')
            del i, v
        else:
            raise TypeError('Too much args; max 2')
        if kwargs:
            for k, v in kwargs.items():
                if k == 'vertex_id':
                    if isinstance(v, (VertexId, ExternalVertexId, str)):
                        vertex_id = v
                    else:
                        raise TypeError(type(v))
                elif k in ('vertex', 'source_vertex'):
                    if isinstance(v, (Vertex, Mapping)):
                        if k == 'vertex':
                            vertex = v
                        elif k == 'source_vertex':
                            source_vertex = v
                        else:
                            raise TypeError(type(v))
                    else:
                        raise TypeError(type(v))
                else:
                    raise KeyError(k)
            del k, v

        e_vertex_id = resolve_vertex_id(vertex, vertex_id)

        if isinstance(e_vertex_id, ExternalVertexId):
            e_vertex_id = self.get(e_vertex_id, (OgitAttribute.OGIT__ID, )).id

        if isinstance(source_vertex, Vertex):
            req_data = source_vertex.to_dict()
        elif isinstance(vertex, Vertex):
            req_data = vertex.to_dict()
        elif isinstance(source_vertex, Mapping):
            req_data = GraphDict(source_vertex).to_dict()
        elif isinstance(vertex, Mapping):
            req_data = GraphDict(vertex).to_dict()
        else:
            raise RuntimeError('unreachable')  # has to be caught earlier

        m: ReadOnlyAttribute
        for m in tuple(ReadOnlyAttribute):
            k = m.value.name.uri
            if k in req_data:
                del req_data[k]

        m: FinalAttribute
        for m in tuple(FinalAttribute):
            k = m.value.name.uri
            if k is SystemAttribute.OGIT__XID.value:
                if isinstance(vertex, Vertex) \
                        and not vertex._draft \
                        and vertex._orig_xid is None:
                    # only update(set) xid if xid was not set before
                    continue
                else:
                    # we have a map and don't know about the graph state
                    continue
            if k in req_data:
                del req_data[k]
        del m, k

        res_data = self.__data_client.update(e_vertex_id, req_data)
        vertex = to_vertex(res_data, self.__base_client)
        return vertex
Beispiel #8
0
    def create(self, *args, **kwargs) -> VERTEX_T_co:
        if not args and not kwargs:
            raise RuntimeError('Missing args and or kwargs')
        vertex: Optional[VERTEX_T] = None
        vertex_type: Optional[VERTEX_TYPE_T] = None
        if len(args) == 1:
            v = args[0]
            if isinstance(v, Vertex):
                vertex = v
                vertex_type = v.type
            elif isinstance(v, Mapping):
                vertex = GraphDict(v)
                if OgitAttribute.OGIT__TYPE in vertex:
                    vertex_type = vertex[OgitAttribute.OGIT__TYPE]
                else:
                    raise KeyError(
                        f'Missing {OgitAttribute.OGIT__TYPE} key in mapping')
            elif isinstance(v, OgitEntity):
                vertex_type = v.value.name.uri
                vertex = None
            elif isinstance(v, OntologyEntity):
                vertex_type = v.name.uri
                vertex = None
            elif isinstance(v, str):
                vertex_type = v
                vertex = None
            else:
                raise TypeError(
                    f'type(args[0]): {type(v)}; expected: Union[str, Entity, Vertex, Mapping[Union[str, Attribute], Any]]'
                )
            del v
        elif len(args) == 2:
            for i, v in enumerate(args):
                if i == 0:
                    if isinstance(v, OgitEntity):
                        vertex_type = v.value.name.uri
                    elif isinstance(v, OntologyEntity):
                        vertex_type = v.name.uri
                    elif isinstance(v, str):
                        vertex_type = v
                    else:
                        raise TypeError(
                            f'args[0]: expected: Union[str, Entity]; got: {type(v)}'
                        )
                elif i == 1:
                    if isinstance(v, (Vertex, Mapping)):
                        vertex = v
                    else:
                        raise TypeError(
                            f'args[1]: expected: Union[Vertex, Mapping[Union[str, Attribute], Any]]; got: {type(v)}'
                        )
                else:
                    raise RuntimeError('Unreachable')
            del i, v
        else:
            raise RuntimeError('Too much args; max 2')
        if kwargs:
            for k, v in kwargs.items():
                if k == 'vertex_type':
                    if isinstance(v, OgitEntity):
                        vertex_type = v.value.name.uri
                    elif isinstance(v, OntologyEntity):
                        vertex_type = v.name.uri
                    elif isinstance(v, str):
                        vertex_type = v
                    else:
                        raise TypeError(
                            f'kwargs[\'{k}\']: expected: Union[str, Entity]; got: {type(v)}'
                        )
                elif k == 'vertex':
                    if isinstance(v, (Vertex, Mapping)):
                        vertex = v
                    else:
                        raise TypeError(
                            f'kwargs[\'{k}\']: expected: Union[Vertex, Mapping[Union[str, Attribute], Any]]; got: {type(v)}'
                        )
                else:
                    raise KeyError(f'''Unexpected key '{k}' found''')
            del k, v

        e_vertex_type = resolve_vertex_type(vertex, vertex_type)

        if vertex is None:
            req_data = {}
        elif isinstance(vertex, Vertex):
            req_data = vertex.to_dict()
        elif isinstance(vertex, Mapping):
            req_data = GraphDict(vertex).to_dict()
        else:
            raise RuntimeError('unreachable')  # has to be caught earlier

        for k, v in req_data.items():
            if isinstance(v, OgitEntity):
                req_data[k] = v.value.name.uri
            elif isinstance(v, OntologyEntity):
                req_data[k] = v.name.uri

        # TODO if 'ogit/_owner' not in vertex:  logging.warn() HIRO 6

        res_data = self.__data_client.create(e_vertex_type.name.uri, req_data)
        vertex = to_vertex(res_data, self.__base_client)
        return vertex
Beispiel #9
0
    def __init__(
            self,
            data: Optional[Mapping[Union[str, OntologyAttribute, OgitAttribute], Any]],
            client: Optional['HiroClient'] = None,
            draft: bool = True
    ) -> None:
        super().__init__()
        self.client = client
        self._draft = draft

        m = GraphDict(data)

        k = VirtualAttribute.OGIT__GRAPH_TYPE
        if k in m:
            graph_type = GraphType(m[k])
            if graph_type is not GraphType.EDGE:
                raise RuntimeError()
        else:
            graph_type = None

        k = OgitAttribute.OGIT__ID
        if k in m:
            self.id = EdgeId(m[k])
            del m[k]
        k = OgitAttribute.OGIT__TYPE
        if k in m:
            verb: OgitVerb = OgitVerb[m[k]]
            self.type = verb.value
            del m[k]

        k = VirtualAttribute.OGIT__OUT_TYPE
        if k in m:
            entity: OgitEntity = OgitEntity[m[k]]
            self.out_type = entity.value
            del m[k]
        k = VirtualAttribute.OGIT__OUT_ID
        if k in m:
            self.out_id = VertexId(m[k])
            del m[k]
        k = OgitAttribute.OGIT__EDGE_ID
        if k in m:
            self.edge_id = EdgeId(m[k])
            del m[k]
        k = VirtualAttribute.OGIT__IN_TYPE
        if k in m:
            entity: OgitEntity = OgitEntity[m[k]]
            self.in_type = entity.value
            del m[k]
        k = VirtualAttribute.OGIT__IN_ID
        if k in m:
            self.in_id = VertexId(m[k])
            del m[k]

        k = OgitAttribute.OGIT__CREATOR_APP
        if k in m:
            self.created_by_app = VertexId(m[k])
            del m[k]
        k = OgitAttribute.OGIT__CREATOR
        if k in m:
            self.created_by = m[k]
            del m[k]
        k = OgitAttribute.OGIT__CREATED_ON
        if k in m:
            self.created_on = timestamp_ms_to_datetime(m[k])
            del m[k]

        k = OgitAttribute.OGIT__DELETED_BY_APP
        if k in m:
            self.deleted_by_app = VertexId(m[k])
            del m[k]
        k = OgitAttribute.OGIT__DELETED_BY
        if k in m:
            self.deleted_by = m[k]
            del m[k]
        k = OgitAttribute.OGIT__DELETED_ON
        if k in m:
            self.deleted_on = timestamp_ms_to_datetime(m[k])
            del m[k]
        k = OgitAttribute.OGIT__IS_DELETED
        if k in m:
            self.is_deleted = to_bool(m[k])
            del m[k]

        if graph_type:
            k = VirtualAttribute.OGIT__GRAPH_TYPE
            del m[k]

        for k in m:
            if isinstance(k, (OgitAttribute, OntologyAttribute)):
                raise KeyError(f'Unexpected {k!r} found')
            if not isinstance(k, str):
                raise TypeError(f'Unexpected type of key found: {type(k)}')
            if k.startswith('ogit/_'):
                raise KeyError(f'Unexpected system attribute found: {k!r}')
            elif k.startswith('ogit/'):
                raise KeyError(f'Unexpected OGIT attribute found: {k!r}')
            elif k.startswith('/'):
                raise KeyError(f'Unexpected free attribute found: {k!r}')
            else:
                raise KeyError(f'Unexpected key found: {k!r}')
def test_graph_dict_get_type():
    d = GraphDict({
        OGIT__GRAPH_TYPE: GraphType.VERTEX,
        OGIT__TYPE: 'ogit/Note'
    })
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyEntity)
    d = GraphDict({
        OGIT__GRAPH_TYPE: GraphType.VERTEX,
        OGIT__TYPE: OgitEntity.OGIT_NOTE
    })
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyEntity)
    d = GraphDict({
        OGIT__GRAPH_TYPE: GraphType.VERTEX,
        OGIT__TYPE: OgitEntity.OGIT_NOTE.value
    })
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyEntity)
    d = GraphDict({OGIT__GRAPH_TYPE: GraphType.VERTEX, OGIT__TYPE: 123})
    with pytest.raises(TypeError):
        v = d[OGIT__TYPE]
    d = GraphDict({OGIT__GRAPH_TYPE: GraphType.VERTEX, OGIT__TYPE: 'foo'})
    with pytest.raises(ValueError):
        v = d[OGIT__TYPE]

    d = GraphDict({OGIT__TYPE: 'ogit/Note'})
    v = d[OGIT__TYPE]
    assert isinstance(v, str)
    assert v == 'ogit/Note'
    d = GraphDict({OGIT__TYPE: OgitEntity.OGIT_NOTE})
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyEntity)
    d = GraphDict({OGIT__TYPE: OgitEntity.OGIT_NOTE.value})
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyEntity)
    d = GraphDict({OGIT__TYPE: OgitVerb.OGIT_HAS})
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyVerb)
    d = GraphDict({OGIT__TYPE: OgitVerb.OGIT_HAS.value})
    v = d[OGIT__TYPE]
    assert isinstance(v, OntologyVerb)
    d = GraphDict({OGIT__TYPE: 123})
    v = d[OGIT__TYPE]
    assert isinstance(v, int)
    d = GraphDict({OGIT__TYPE: 'foo'})
    v = d[OGIT__TYPE]
    assert isinstance(v, str)
    d = GraphDict({OGIT__TYPE: GraphType.VERTEX})
    v = d[OGIT__TYPE]
    assert isinstance(v, GraphType)