Exemple #1
0
def test_bundle(custom_bundle):
    from owmeta_core import bundle
    from owmeta_core.context import Context
    from owmeta_core.dataobject import DataObject
    from owmeta_core.bundle import Descriptor, Bundle

    desc = Descriptor.load('''
    id: example/bundleId
    version: 42
    includes:
        - http://example.org/test_bundle
    ''')

    ctx = Context('http://example.org/test_bundle')
    ctx(DataObject)(ident='http://example.org/entities#aDataObject')

    with custom_bundle(desc, graph=ctx.rdf_graph()) as bun:

        class CustomBundle(Bundle):
            def __init__(self, *args, **kwargs):
                super().__init__(*args,
                                 bundles_directory=bun.bundles_directory,
                                 **kwargs)

        [failure_count, return_count
         ] = doctest.testmod(bundle,
                             optionflags=(ALLOW_UNICODE | doctest.ELLIPSIS),
                             extraglobs=dict(Bundle=CustomBundle,
                                             DataObject=DataObject))
    assert failure_count == 0
Exemple #2
0
    def test_context_store(self):
        class A(DataObject):
            pass

        mapper = Mapper()
        mapper.add_class(A)
        ctx = Context(ident='http://example.com/context_1', mapper=mapper)
        ctx(A)(ident='anA')
        self.assertIn(URIRef('anA'),
                      tuple(x.identifier for x in ctx.mixed(A)().load()))
Exemple #3
0
 def test_contents_triples(self):
     res_wanted = []
     ident_uri = 'http://example.com/context_1'
     ctx = Context(ident=ident_uri)
     for i in range(5):
         stmt = create_mock_statement(ident_uri, i)
         ctx.add_statement(stmt)
         res_wanted.append(stmt.to_triple())
     for triples in ctx.contents_triples():
         self.assertTrue(triples in res_wanted)
    def test_adhoc_datatype_property_in_context(self):
        class A(DataObject):
            a = DatatypeProperty()

        class B(DataObject):
            pass

        ctx = Context(ident='http://example.org/geogia')
        b = ctx(B)(key='b')
        A.a(b)('square')
        self.assertIn((R.URIRef('http://data.openworm.org/B#b'),
                       R.URIRef('http://schema.openworm.org/2020/07/A/a'),
                       R.Literal('square')), list(ctx.contents_triples()))
Exemple #5
0
 def test_save_import(self):
     ctx0 = Context(ident='http://example.com/context_0')
     ctx = Context(ident='http://example.com/context_1')
     new_ctx = Context(ident='http://example.com/context_1')
     ctx.add_import(new_ctx)
     ctx.save_imports(ctx0)
     self.assertEqual(len(ctx0), 1)
    def test_adhoc_union_property_in_context(self):
        class A(DataObject):
            a = UnionProperty()

        class B(DataObject):
            pass

        ctx = Context(ident='http://example.org/wisconsin')
        b = ctx(B)(key='b')
        A.a(b)(A(key='a'))
        self.assertIn((R.URIRef('http://data.openworm.org/B#b'),
                       R.URIRef('http://schema.openworm.org/2020/07/A/a'),
                       R.URIRef('http://data.openworm.org/A#a')),
                      list(ctx.contents_triples()))
 def setUp(self):
     xfail_without_db()
     self.conn = owmeta_core.connect(
         configFile='tests/data_integrity_test.conf')
     self.g = self.conn.conf["rdf.graph"]
     self.context = Context()
     self.qctx = self.context.stored
Exemple #8
0
    def test_statements_staged(self):
        '''
        Statements have the Context included as a regular attribute, so we don't filter
        by the property's current context.

        The property's `rdf` attribute evals to the context's staged graph, so we get an
        "extra" entry from the context
        '''
        do = self.ctx.DataObject(ident=R.URIRef("http://example.org"))
        ctx = Context('http://example.org/ctx/')
        do.birds = DataObject.DatatypeProperty(multiple=True)
        ctx(do).birds(4)
        do.birds(5)
        stmts = list(do.birds.statements)
        for s in stmts:
            print(s.to_quad())
        # Split up into 3 asserts so you can actually read pytest' error print-out...
        assert stmts[0] == Statement(do, do.birds, PropertyValue(R.Literal(4)),
                                     ctx)
        assert stmts[1] == Statement(do, do.birds, PropertyValue(R.Literal(5)),
                                     self.context)

        # These statements are not actually equal because statements mints a new Context
        # for what it retrieves from the RDF graph (it has to)
        assert stmts[2].to_quad() == Statement(do, do.birds,
                                               PropertyValue(R.Literal(5)),
                                               self.context).to_quad()
Exemple #9
0
def evidence_for(qctx, ctx, evctx=None):
    """
    Returns an iterable of Evidence

    Parameters
    ----------
    qctx : object
        an object supported by evidence. If the object is a
        :class:`~owmeta.context.Context` with no identifier, then the query
        considers statements 'staged' (rather than stored) in the context
    ctx : Context
        Context that bounds where we look for statements about `qctx`. The
        contexts for statements found in this context are the actual targets of
        Evidence.supports statements.
    evctx : Context
        if the Evidence.supports statements should be looked for somewhere other
        than `ctx`, that can be specified in evctx. optional
    """
    if not evctx:
        evctx = ctx
    ctxs = query_context(ctx.rdf_graph(), qctx)
    ev_objs = []
    for c in ctxs:
        ev = evctx(Evidence)()
        ev.supports(Context(ident=c.identifier).rdf_object)
        for x in ev.load():
            ev_objs.append(x)
    return ev_objs
    def test_adding_data(self):
        # Setup a class imported by docs for demonstration purposes
        from owmeta_core.dataobject import DataObject, DatatypeProperty
        from owmeta_core.context import Context
        Load = lambda *args, **kwargs: [
            namedtuple('Record', ('pnum', 'flns', 'hrds'))(12, 1.0, 100)
        ]

        class Widget(DataObject):
            class_context = 'http://example.org/test_adding_data'
            rdf_type = 'http://example.org/BDW/schema/Widget'
            rdf_namespace = 'http://example.org/BDW/entities/Widget#'
            hardiness = DatatypeProperty()
            fullness = DatatypeProperty()
            part_number = DatatypeProperty()
            key_property = {'name': 'part_number', 'type': 'direct'}

        ctx = Context(
            ident='http://example.org/data/imports/BDW_Widgets_2018-2019')

        ctx.mapper.process_class(Widget)
        ctx(Widget)(part_number=15)
        ctx(Widget)(part_number=17)
        ctx(Widget)(part_number=20)

        self.execute('adding_data',
                     extraglobs={
                         'Load': Load,
                         'Widget': Widget,
                         'ctx18': ctx
                     })
Exemple #11
0
    def test_decontextualize(self):
        class A(DataObject):
            pass

        ctx = Context(ident='http://example.com/context_1')
        ctxda = ctx(A)(ident='anA')
        self.assertIsNone(ctxda.decontextualize().context)
Exemple #12
0
 def test_add_remove_statement(self):
     ident_uri = 'http://example.com/context_1'
     ctx = Context(ident=ident_uri)
     stmt_to_remove = create_mock_statement(ident_uri, 42)
     for i in range(5):
         ctx.add_statement(create_mock_statement(ident_uri, i))
     ctx.add_statement(stmt_to_remove)
     ctx.remove_statement(stmt_to_remove)
     self.assertEqual(len(ctx), 5)
    def test_query_context(self):
        class A(DataObject):
            pass

        ctx = Context(ident='http://example.org/texas')
        ctxd = ctx(A)
        qctxd = ctxd.query
        self.assertIs(ctxd.context, qctxd.context)
    def test_stored(self):
        '''
        Test resolving a class when the relevant data are "stored" in a RDFLib graph
        '''
        ctxid = 'http://example.org/test'
        ctx = Context(ident=ctxid, conf=self.TestConfig)

        cname = self.__class__.__name__
        mname = self.__class__.__module__
        trips = [(pcd, PythonClassDescription.name.link, R.Literal(cname),
                  ctxid), (pcd, PythonClassDescription.module.link, pm, ctxid),
                 (pm, PythonModule.name.link, R.Literal(mname), ctxid),
                 (pm, R.RDF.type, PythonModule.rdf_type, ctxid)]
        for t in trips:
            ctx.rdf.add(t)
        pcddo = ctx.stored(PythonClassDescription)(ident=pcd)
        self.assertEqual(self.__class__, pcddo.resolve_class())
Exemple #15
0
    def test_imports_no_imports_graph_in_stored(self):
        # create a Data config so all contexts use the same rdflib.Graph
        conf = Data()
        ctx = Context('http://example.org/ctx1', conf=conf)
        imported_ctx = Context('http://example.org/ctx2', conf=conf)
        other_ctx = Context('http://example.org/other_ctx', conf=conf)
        ctx.add_import(imported_ctx)
        ctx.save_imports(other_ctx)

        assert list(ctx.stored.imports) == []
Exemple #16
0
    def test_statements_query_empty(self):
        '''
        Statements have the Context included as a regular attribute, so we don't filter
        by the property's current context.

        The property's `rdf` attribute evals to the context's staged graph, so we get an
        "extra" entry from the context
        '''
        do = self.ctx.DataObject(ident=R.URIRef("http://example.org"))
        ctx = Context('http://example.org/ctx/')
        do.birds = DataObject.DatatypeProperty(multiple=True)
        ctx(do).birds(4)
        do.birds(5)
        stmts = list(Context('http://example.org/ctx/')(do).birds.statements)
        assert stmts == [
            Statement(do, do.birds, PropertyValue(R.Literal(4)), ctx),
            Statement(do, do.birds, PropertyValue(R.Literal(5)), self.context)
        ]
 def setUp(self):
     # Make the statements and evidence we will query for in the test
     super(EvidenceForTest, self).setUp()
     self.process_class(Evidence)
     c1 = Context(ident='http://example.org/statements', conf=self.conf)
     c1(Neuron)('AVAL').innexin('UNC-7')
     evc = Context(ident='http://example.org/metadata', conf=self.conf)
     ev1 = evc(Evidence)(key='js2019')
     ev1.supports(c1.rdf_object)
     # Save them
     c1.save_context()
     evc.save_context()
Exemple #18
0
    def test_imports_with_imports_graph_in_stored(self):
        # create a Data config so all contexts use the same rdflib.Graph
        conf = Data()
        conf.init()
        conf[IMPORTS_CONTEXT_KEY] = 'http://example.org/imports'
        ctx = Context('http://example.org/ctx1', conf=conf)
        imported_ctx = Context('http://example.org/ctx2', conf=conf)
        imports_ctx = Context('http://example.org/imports', conf=conf)
        ctx.add_import(imported_ctx)
        ctx.save_imports(imports_ctx)

        assert [c.identifier
                for c in ctx.stored.imports] == [imported_ctx.identifier]
Exemple #19
0
            def f(ns):
                ctx = ns.context
                stmt = MagicMock(name='stmt')
                new_ctx = Context(ident=k)
                stmt.to_triple.return_value = (s, s, s)
                stmt.object.context.identifier = k
                stmt.property.context.identifier = URIRef(a)
                stmt.subject.context.identifier = URIRef(a)
                stmt.context.identifier = URIRef(a)

                ctx.add_statement(stmt)
                ctx.add_import(new_ctx)
Exemple #20
0
 def test_clear(self):
     ident_uri = 'http://example.com/context_1'
     ctx = Context(ident=ident_uri)
     for i in range(5):
         ctx.add_statement(create_mock_statement(ident_uri, i))
     ctx.clear()
     self.assertEqual(len(ctx), 0)
Exemple #21
0
def test_save_imports(owm_project):
    modpath = owm_project.make_module('test_module')
    owm_project.writefile(p(modpath, 'monkey.py'),
                          'tests/test_modules/owmclitest04_monkey_giraffe.py')

    print(owm_project.sh('owm save test_module.monkey'))
    with OWM(owmdir=p(owm_project.testdir, '.owm')).connect() as conn:
        ctx = Context(ident=conn.conf[IMPORTS_CONTEXT_KEY], conf=conn.conf)
        trips = set(ctx.stored.rdf_graph().triples((None, None, None)))
        assert (URIRef(conn.conf[DEFAULT_CONTEXT_KEY]), CONTEXT_IMPORTS,
                URIRef('http://example.org/primate/monkey')) in trips
        assert (URIRef(conn.conf[DEFAULT_CONTEXT_KEY]), CONTEXT_IMPORTS,
                URIRef('http://example.org/ungulate/giraffe')) in trips
Exemple #22
0
 def test_save_context(self):
     graph = set()
     ident_uri = 'http://example.com/context_1'
     ctx = Context(ident=ident_uri)
     for i in range(5):
         ctx.add_statement(create_mock_statement(ident_uri, i))
     ctx.save_context(graph)
     self.assertEqual(len(graph), 5)
 def context_for(self, ident=None, **kwargs):
     key = "&".join(k + "=" +
                    getattr(kwargs[k], 'identifier', str(kwargs[k]))
                    for k in sorted(kwargs.keys()))
     res = self.__ad_hoc_contexts.get(key)
     if res is None:
         if ident:
             ctxid = ident
         else:
             ctxid = self.identifier + '/context_for?' + key
         self.__ad_hoc_contexts[key] = Context.contextualize(
             self.context)(ident=ctxid)
         res = self.__ad_hoc_contexts[key]
     return res
Exemple #24
0
    def test_inverse_property_context(self):
        class A(DataObject):
            unmapped = True

            def __init__(self, **kwargs):
                super(A, self).__init__(**kwargs)
                self.a = A.ObjectProperty(value_type=B)

        class B(DataObject):
            unmapped = True

            def __init__(self, **kwargs):
                super(B, self).__init__(**kwargs)
                self.b = B.ObjectProperty(value_type=A)

        InverseProperty(B, 'b', A, 'a')
        ctx1 = Context(ident='http://example.org/context_1')
        ctx2 = Context(ident='http://example.org/context_2')
        a = ctx1(A)(ident='a')
        b = ctx2(B)(ident='b')
        a.a(b)
        expected = (URIRef('b'), B.schema_namespace['b'], URIRef('a'))
        self.assertIn(expected, list(ctx1.contents_triples()))
Exemple #25
0
def test_resolve_property_class_stored():
    conf = Data()
    conf.init()
    ctxid = 'http://example.org/ctx'
    ctx0 = Context(ctxid, conf=conf)
    modname = ModelDBPropertyClassDescription.__module__
    mod = ctx0(PythonModule)(name=modname)
    cd = ctx0(ModelDBPropertyClassDescription)(name='ModelDB_test_property',
                                               local_id='test_property',
                                               display_name='Test Property',
                                               module=mod)
    ctx0.save()

    ctx1 = Context(ctxid, conf=conf)
    ctx1.stored(ModelDBPropertyClassDescription)(ident=cd.identifier)
    assert issubclass(cd.resolve_class(), Property)
Exemple #26
0
    def test_defined(self):
        class A(DataObject):
            def __init__(self, **kwargs):
                super(A, self).__init__(**kwargs)
                self.a = A.ObjectProperty(value_type=B)

            def defined_augment(self):
                return self.a.has_defined_value()

            def identifier_augment(self):
                return self.make_identifier(self.a.onedef().identifier.n3())

        class B(DataObject):
            def __init__(self, **kwargs):
                super(B, self).__init__(**kwargs)
                self.b = B.ObjectProperty(value_type=A)

        InverseProperty(B, 'b', A, 'a')
        ctx1 = Context(ident='http://example.org/context_1')
        ctx2 = Context(ident='http://example.org/context_2')
        a = ctx1(A)()
        b = ctx2(B)(ident='b')
        a.a(b)
        self.assertTrue(a.defined)
Exemple #27
0
 def test_defined_statements_across_contexts_datatype_property(self):
     '''
     Statements have the Context included as a regular attribute, so we don't filter
     by the property's current context
     '''
     do = self.ctx.DataObject(ident=R.URIRef("http://example.org"))
     ctx = Context('http://example.org/ctx/')
     do.birds = DataObject.DatatypeProperty(multiple=True)
     ctx(do).birds(4)
     do.birds(5)
     stmts = list(ctx(do).birds.defined_statements)
     assert stmts == [
         Statement(do, do.birds, PropertyValue(R.Literal(4)), ctx),
         Statement(do, do.birds, PropertyValue(R.Literal(5)), self.context)
     ]
    def test_statements_with_no_evidence(self):
        # Make the context that holds the statements.
        # These statements were not made in the setUp
        qctx = Context()
        qctx(Neuron)('AVAR').innexin('UNC-7')

        # Make the context we query statements from. This could be a 'staged'
        # context, but in this case we use what we've written to the IOMemory
        # store provided by _DataTest in self.conf['rdf.graph']
        ctx = self.connection(Context)().stored

        # Actually do the query
        ev_iterable = evidence_for(qctx, ctx)

        self.assertEqual(len(ev_iterable), 0)
Exemple #29
0
 def test_triples_saved_noundef_triples_counted(self):
     graph = set()
     ident_uri = 'http://example.com/context_1'
     ctx = Context(ident=ident_uri)
     statement = MagicMock()
     statement.context.identifier = rdflib.term.URIRef(ident_uri)
     statement.to_triple.return_value = (Variable('var'), 1, 2)
     ctx.add_statement(statement)
     ctx.save_context(graph)
     self.assertEqual(ctx.triples_saved, 0)
    def test_staged_context(self):
        '''
        Test resolving a class when the relevant data are staged in a context
        '''
        ctxid = 'http://example.org/test'
        ctx = Context(ident=ctxid, conf=self.TestConfig)
        cname = self.__class__.__name__
        mname = self.__class__.__module__

        pmo = ctx(PythonModule)(ident=pm)
        pmo.name(mname)
        pcddo = ctx(PythonClassDescription)(ident=pcd)
        pcddo.name(cname)
        pcddo.module(pmo)
        pcddo1 = ctx(PythonClassDescription)(ident=pcd)
        self.assertEqual(self.__class__, pcddo1.resolve_class())