Exemplo n.º 1
0
    def add_prop(self, ent, prop=None):
        """Add a :class:`Property` to the model.

        :param Node|Edge ent: Attach ``prop`` to this entity
        :param Property prop: A :class:`Property` instance

        The model attribute of ``prop`` is set to `Model.handle`. Within a model,
        :class:`Property` entities are unique with respect to their
        handle (but can be reused). This method will look for an existing
        property within the model with the given handle, and add an item to
        Model.props pointing to it if found.
        """
        if not isinstance(ent, (Node, Edge)):
            raise ArgError("arg 1 must be Node or Edge")
        if not prop:
            raise ArgError("arg 2 must be Property, dict, or graph.Node")
        if isinstance(prop, (dict, neo4j.graph.Node)):
            handle = prop["handle"]
            pkeys = [x for x in self.props if handle in x]
            if pkeys:
                prop = self.props[pkeys.pop()]
            else:
                prop = Property(prop)
        if not prop.model:
            prop.model = self.handle
        key = [ent.handle] if isinstance(ent, Node) else list(ent.triplet)
        key.append(prop.handle)
        ent.props[getattr(prop, type(prop).mapspec()["key"])] = prop
        self.props[tuple(key)] = prop
        return prop
Exemplo n.º 2
0
def test_some_object_methods():
  p = Property({"handle":"complaint"})
  assert p
  t = Term({"value":"halitosis"})
  assert t
  u = Term({"value":"ptomaine"})
  assert u
  vs = ValueSet({"_id":"1"})
  assert vs
  p.value_set = vs
  vs.terms['ptomaine'] = u
  assert p.terms['ptomaine'].value == 'ptomaine'
  p.terms['halitosis'] = t
  assert vs.terms['halitosis'].value == 'halitosis'
  vals = p.values
  assert isinstance(vals,list)
  assert 'ptomaine' in vals
  assert 'halitosis' in vals
  s = Node({'handle':"case"})
  assert s
  d = Node({'handle':"cohort"})
  assert d
  e = Edge({'handle':"member_of",'src':s,'dst':d})
  assert e
  assert e.triplet == ('member_of','case','cohort')
Exemplo n.º 3
0
def test_tags_on_objects():
  nodeTag = Tag({"key":"name","value":"Neddy"})
  relnTag = Tag({"key":"name","value":"Robby"})
  conceptTag = Tag({"key":"name","value":"Catty"})
  conceptTag2 = Tag({"key":"aka","value":"Jehoshaphat"})
  termTag = Tag({"key":"name","value":"Termy"})
  propTag = Tag({"key":"name","value":"Puppy"})
  
  case = Node({"model":"test","handle":"case"})
  of_sample = Edge({"model":"test","handle":"of_sample"})
  sample = Node({"model":"test","handle":"sample"})  
  of_sample.src = sample
  of_sample.dst = case
  term = Term({"value":"sample"})
  concept = Concept();
  term.concept = concept
  concept.terms["sample"]=term
  sample.concept = concept
  sample.props['this'] = Property({"that":"this"})

  case.tags[nodeTag.key] = nodeTag
  of_sample.tags[relnTag.key] = relnTag
  term.tags[termTag.key] = termTag
  concept.tags[conceptTag.key] = conceptTag
  concept.tags[conceptTag2.key] = conceptTag2
  sample.props['this'].tags['name'] = propTag

  names = [x.tags['name'].value for x in [case,of_sample,term,concept,sample.props['this']]];
Exemplo n.º 4
0
def test_valuesets_are_different__f():
    '''test using sets as input'''
    p_1 = Property({"handle": "States"})
    p_2 = Property({"handle": "Estados"})
    vs_1 = ValueSet({"_id": "1"})
    vs_2 = ValueSet({"_id": "2"})

    term_a = Term({"value": "Merida"})
    term_b = Term({"value": "Cumana"})
    term_c = Term({"value": "Maracaibo"})
    term_d = Term({"value": "Ciudad Bolivar"})
    term_e = Term({"value": "Barcelona"})
    term_f = Term({"value": "Barquisimeto"})

    vs_1.terms['Merida'] = term_a
    vs_1.terms['Cumana'] = term_b
    vs_1.terms['Maracaibo'] = term_c
    vs_1.terms['Ciudad Bolivar'] = term_d

    vs_2.terms['Merida'] = term_a
    vs_2.terms['Cumana'] = term_b
    vs_2.terms['Maracaibo'] = term_c
    vs_2.terms['Ciudad Bolivar'] = term_d

    p_1.value_set = vs_1
    p_2.value_set = vs_2

    actual = diff.valuesets_are_different(p_1.value_set, p_2.value_set)
    expected = False
    assert actual == expected
Exemplo n.º 5
0
def test_create_model():
    model = Model('test')
    case = Node({"handle": "case"})
    #  set_trace()
    case.props['days_to_enrollment'] = Property(
        {"handle": 'days_to_enrollment'})
    model.add_node(case)
    assert isinstance(model.nodes['case'], Node)
    assert model.props[('case', 'days_to_enrollment')]
    model.add_node({"handle": "sample"})
    assert model.nodes["sample"]
    assert isinstance(model.nodes["sample"], Node)
    assert model.nodes["sample"].model == 'test'
    case_id = Property({"handle": "case_id", "value_domain": "string"})
    model.add_prop(case, case_id)
    assert model.props[("case", "case_id")]
    assert model.props[("case", "case_id")].value_domain == 'string'
    assert 'case_id' in model.nodes['case'].props
    sample = model.nodes["sample"]
    of_case = Edge({"handle": "of_case", "src": sample, "dst": case})
    of_case.props['operator'] = Property({
        "handle": "operator",
        "value_domain": "boolean"
    })
    model.add_edge(of_case)
    assert model.edges[('of_case', 'sample', 'case')]
    assert model.contains(of_case.props['operator'])
    assert of_case.props['operator'].model == 'test'
    assert model.props[('of_case', 'sample', 'case', 'operator')]
    assert model.props[('of_case', 'sample', 'case',
                        'operator')].value_domain == 'boolean'
    dx = Property({"handle": "diagnosis", "value_domain": "value_set"})
    tm = Term({"value": "CRS"})
    model.add_prop(case, dx)
    model.add_terms(dx, tm, 'rockin_pneumonia', 'fungusamongus')
    assert {x.value
            for x in dx.terms.values()
            } == {'CRS', 'rockin_pneumonia', 'fungusamongus'}
Exemplo n.º 6
0
def test_rm_queries():
    m = ObjectMap(cls=FakeNode)
    n = FakeNode({"handle": "test", "model": "test_model", "category": 1})
    assert FakeNode.mapspec()["relationship"]["concept"]["end_cls"] == {
        "Concept", "Term"
    }
    with pytest.raises(ArgError, match="object must be mapped"):
        m.rm_q(n)
    n.neoid = 1
    qry = m.rm_q(n)
    assert qry == 'MATCH (n:node) WHERE id(n)=1 DELETE n'
    qry = m.rm_q(n, detach=True)
    assert qry == 'MATCH (n:node) WHERE id(n)=1 DETACH DELETE n'
    c = Concept({"_id": "blerf"})
    qry = m.rm_attr_q(n, 'model')
    assert qry == 'MATCH (n:node) WHERE id(n)=1 REMOVE n.model RETURN id(n)'
    qry = m.rm_attr_q(n, 'props', [':all'])
    assert qry == 'MATCH (n:node)-[r:has_property]->(a:property) WHERE id(n)=1 DELETE r RETURN id(n),id(a)'
    qry = m.rm_attr_q(n, 'concept', [':all'])
    assert re.match(
        "MATCH \\(n:node\\)-\\[r:has_concept\\]->\\(a\\) WHERE id\\(n\\)=1 AND \\('[a-z]+' IN labels\\(a\\) OR '[a-z]+' IN labels\\(a\\)\\) DELETE r",
        qry)
    prps = [
        Property(x) for x in ({
            "model": "test",
            "handle": "prop1"
        }, {
            "model": "test",
            "handle": "prop2"
        }, {
            "model": "test",
            "handle": "prop3"
        })
    ]
    i = 5
    for p in prps:
        p.neoid = i
        i += 1
    stmts = m.rm_attr_q(n, 'props', prps)
    assert stmts[
        0] == "MATCH (n:node)-[r:has_property]->(a:property) WHERE id(n)=1 AND id(a)=5 DELETE r RETURN id(n),id(a)"
    assert len(stmts) == 3
Exemplo n.º 7
0
    def dget(self, refresh=False):
        """Pull model from MDB into this Model instance, based on its handle

        Note: is a noop if `Model.drv` is unset.
        """
        if not self.drv:
            return
        if refresh:
            ObjectMap.clear_cache()
        with self.drv.session() as session:
            result = session.run(
                "match p = (s:node)<-[:has_src]-(r:relationship)-[:has_dst]->(d:node) "
                "where s.model=$hndl and r.model=$hndl and d.model=$hndl return p",
                {"hndl": self.handle},
            )
            for rec in result:
                (ns, nr, nd) = rec["p"].nodes
                ns = Node(ns)
                nr = Edge(nr)
                nd = Node(nd)
                ObjectMap.cache[ns.neoid] = ns
                ObjectMap.cache[nr.neoid] = nr
                ObjectMap.cache[nd.neoid] = nd
                nr.src = ns
                nr.dst = nd
                self.nodes[ns.handle] = ns
                self.nodes[nd.handle] = nd
                self.edges[nr.triplet] = nr

        with self.drv.session() as session:
            result = session.run(
                "match (n:node)-[:has_property]->(p:property) where n.model=$hndl and p.model=$hndl return id(n), p",
                {"hndl": self.handle},
            )
            for rec in result:
                n = ObjectMap.cache.get(rec["id(n)"])
                if n is None:
                    warn("node with id {nid} not yet retrieved".format(
                        nid=rec["id(n)"]))
                    continue
                p = Property(rec["p"])
                ObjectMap.cache[p.neoid] = p
                self.props[(n.handle, p.handle)] = p
                n.props[p.handle] = p
                p.dirty = -1
        with self.drv.session() as session:
            result = session.run(
                "match (r:relationship)-[:has_property]->(p:property) "
                "where r.model=$hndl and p.model=$hndl return id(r), p",
                {"hndl": self.handle},
            )
            for rec in result:
                e = ObjectMap.cache.get(rec["id(r)"])
                if e is None:
                    warn("relationship with id {rid} not yet retrieved".format(
                        rid=rec["id(r)"]))
                    continue
                p = Property(rec["p"])
                ObjectMap.cache[p.neoid] = p
                k = list(e.triplet)
                k.append(p.handle)
                self.props[tuple(k)] = p
                e.props[p.handle] = p
                p.dirty = -1
        return self
Exemplo n.º 8
0
def test_put_queries():
    m = ObjectMap(cls=Node)
    n = Node({"handle": "test", "model": "test_model", "_commit": 1})
    qry = m.put_q(n)
    assert qry == [
        'CREATE (n:node {_commit:1,handle:"test",model:"test_model"}) RETURN n,id(n)'
    ]
    n.neoid = 2
    stmts = m.put_q(n)
    assert stmts[
        0] == 'MATCH (n:node) WHERE id(n)=2 SET n._commit=1,n.handle="test",n.model="test_model" RETURN n,id(n)'
    assert len(stmts[1:]) == len(
        [x for x in Node.attspec if Node.attspec[x] == 'simple']) - 3
    for s in stmts[1:]:
        assert re.match(
            '^MATCH \\(n:node\\) WHERE id\\(n\\)=2 REMOVE n.[a-z_]+ RETURN n,id\\(n\\)$',
            s)
    n.neoid = None
    with pytest.raises(ArgError, match='object must be mapped'):
        m.put_attr_q(n, '_commit', 2)
    n.neoid = 1
    c = Concept({"_id": "blarf"})
    with pytest.raises(
            ArgError,
            match="'values' must be a list of mapped Entity objects"):
        m.put_attr_q(n, 'concept', c)
    with pytest.raises(
            ArgError,
            match="'values' must be a list of mapped Entity objects"):
        m.put_attr_q(n, 'concept', [c])
    qry = m.put_attr_q(n, '_commit', [3])
    assert qry == "MATCH (n:node) WHERE id(n)=1 SET _commit=3 RETURN id(n)"
    c.neoid = 2
    stmts = m.put_attr_q(n, 'concept', [c])
    assert stmts[
        0] == "MATCH (n:node),(a:concept) WHERE id(n)=1 AND id(a)=2 MERGE (n)-[:has_concept]->(a) RETURN id(a)"
    assert len(stmts) == 1
    prps = [
        Property(x) for x in ({
            "model": "test",
            "handle": "prop1"
        }, {
            "model": "test",
            "handle": "prop2"
        }, {
            "model": "test",
            "handle": "prop3"
        })
    ]
    i = 5
    for p in prps:
        p.neoid = i
        i += 1
    stmts = m.put_attr_q(n, 'props', prps)
    assert stmts[
        0] == "MATCH (n:node),(a:property) WHERE id(n)=1 AND id(a)=5 MERGE (n)-[:has_property]->(a) RETURN id(a)"
    assert len(stmts) == 3
    m = ObjectMap(cls=FakeNode)
    n = FakeNode({"handle": "test", "model": "test_model", "category": 1})
    n.neoid = 1
    t = Term({"value": "boog"})
    t.neoid = 6
    stmts = m.put_attr_q(n, "concept", [t])
    assert re.match(
        "MATCH \\(n:node\\),\\(a\\) WHERE id\\(n\\)=1 AND id\\(a\\)=6 AND \\('[a-z]+' IN labels\\(a\\) OR '[a-z]+' IN labels\\(a\\)\\) MERGE \\(n\\)-\\[:has_concept\\]->\\(a\\) RETURN id\\(a\\)",
        stmts[0])
    qry = m.get_attr_q(n, "concept")
    assert re.match(
        "MATCH \\(n:node\\)-\\[:has_concept\\]->\\(a\\) WHERE id\\(n\\)=1 AND \\('[a-z]+' IN labels\\(a\\) OR '[a-z]+' IN labels\\(a\\)\\) RETURN a",
        qry)
    pass
Exemplo n.º 9
0
def test_put_then_rm_queries():
    """test adding then removing attr"""
    m = ObjectMap(cls=Node)
    n = Node({"handle": "test_", "model": "test_model_", "_commit": 1})
    qry = m.put_q(n)
    assert qry == [
        'CREATE (n:node {_commit:1,handle:"test_",model:"test_model_"}) RETURN n,id(n)'
    ]

    # manually set neoid
    n.neoid = 2
    stmts = m.put_q(n)
    assert stmts[
        0] == 'MATCH (n:node) WHERE id(n)=2 SET n._commit=1,n.handle="test_",n.model="test_model_" RETURN n,id(n)'
    assert len(stmts[1:]) == len(
        [x for x in Node.attspec if Node.attspec[x] == 'simple']) - 3
    for s in stmts[1:]:
        assert re.match(
            '^MATCH \\(n:node\\) WHERE id\\(n\\)=2 REMOVE n.[a-z_]+ RETURN n,id\\(n\\)$',
            s)

    n.neoid = None
    with pytest.raises(ArgError, match='object must be mapped'):
        m.put_attr_q(n, '_commit', 2)

    n.neoid = 1
    c = Concept({"_id": "blarfblark"})
    with pytest.raises(
            ArgError,
            match="'values' must be a list of mapped Entity objects"):
        m.put_attr_q(n, 'concept', c)
    with pytest.raises(
            ArgError,
            match="'values' must be a list of mapped Entity objects"):
        m.put_attr_q(n, 'concept', [c])

    qry = m.put_attr_q(n, '_commit', [3])
    assert qry == "MATCH (n:node) WHERE id(n)=1 SET _commit=3 RETURN id(n)"

    c.neoid = 2
    stmts = m.put_attr_q(n, 'concept', [c])
    #assert stmts[0] == "MATCH (n:node),(a:concept) WHERE id(n)=1 AND id(a)=2 MERGE (n)-[:has_concept]->(a) RETURN id(a)"
    assert len(stmts) == 1

    prps = [
        Property(x) for x in ({
            "model": "test_",
            "handle": "prop1"
        }, {
            "model": "test_",
            "handle": "prop2"
        }, {
            "model": "test_",
            "handle": "prop3"
        })
    ]
    i = 5
    for p in prps:
        p.neoid = i
        i += 1
    stmts = m.put_attr_q(n, 'props', prps)
    assert stmts[
        0] == "MATCH (n:node),(a:property) WHERE id(n)=1 AND id(a)=5 MERGE (n)-[:has_property]->(a) RETURN id(a)"
    assert len(stmts) == 3
    Node.mapspec_ = {
        "label": "node",
        "property": {
            "handle": "handle",
            "model": "model"
        },
        "relationship": {
            "concept": {
                "rel": ":has_concept>",
                "end_cls": {"Concept", "Term"}
            },
            "props": {
                "rel": ":has_property>",
                "end_cls": "Property"
            }
        }
    }
    (Node.attspec, Node._mapspec) = mergespec('Node', Node.attspec,
                                              Node.mapspec_)
    assert Node.mapspec()["relationship"]["concept"]["end_cls"] == {
        "Concept", "Term"
    }
    t = Term({"value": "boogblark"})
    t.neoid = 6
    stmts = m.put_attr_q(n, "concept", [t])
    assert re.match(
        "MATCH \\(n:node\\),\\(a\\) WHERE id\\(n\\)=1 AND id\\(a\\)=6 AND \\('[a-z]+' IN labels\\(a\\) OR '[a-z]+' IN labels\\(a\\)\\) MERGE \\(n\\)-\\[:has_concept\\]->\\(a\\) RETURN id\\(a\\)",
        stmts[0])
    qry = m.get_attr_q(n, "concept")
    assert re.match(
        "MATCH \\(n:node\\)-\\[:has_concept\\]->\\(a\\) WHERE id\\(n\\)=1 AND \\('[a-z]+' IN labels\\(a\\) OR '[a-z]+' IN labels\\(a\\)\\) RETURN a",
        qry)

    # now delete the attr I just added....
    qry2 = m.rm_attr_q(n, "concept", [t])
    assert re.match(
        "MATCH \\(n:node\\)-\\[r:has_concept\\]->\\(a\\) WHERE id\\(n\\)=1 AND id\\(a\\)=6 AND \\('[a-z]+' IN labels\\(a\\) OR '[a-z]+' IN labels\\(a\\)\\) DELETE r RETURN id\\(n\\),id\\(a\\)",
        qry2[0])