Beispiel #1
0
class TestHooks(TestCase):
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        self.hooks_called = defaultdict(list)
        tc = self

        class Basic(MappedClass):
            class __mongometa__:
                name = 'hook'
                session = self.session

                def before_save(instance):
                    tc.hooks_called['before_save'].append(instance)

            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)

        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)

    def test_hook_base(self):
        doc = self.Basic()
        doc.a = 5
        self.session.flush()
        self.assertEqual(self.hooks_called['before_save'], [{
            '_id': doc._id,
            'a': doc.a
        }])
Beispiel #2
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     self.session = ODMSession(bind=self.datastore)
     class Parent(MappedClass):
         class __mongometa__:
             name='parent'
             session = self.session
         _id = FieldProperty(S.ObjectId)
         children = ForeignIdProperty('Child', uselist=True)
         field_with_default_id = ForeignIdProperty(
             'Child',
             uselist=True,
             if_missing=lambda:[bson.ObjectId('deadbeefdeadbeefdeadbeef')])
         field_with_default = RelationProperty('Child', 'field_with_default_id')
     class Child(MappedClass):
         class __mongometa__:
             name='child'
             session = self.session
         _id = FieldProperty(S.ObjectId)
         parent_id = ForeignIdProperty(Parent)
         field_with_default_id = ForeignIdProperty(
             Parent,
             if_missing=lambda:bson.ObjectId('deadbeefdeadbeefdeadbeef'))
         field_with_default = RelationProperty('Parent', 'field_with_default_id')
     Mapper.compile_all()
     self.Parent = Parent
     self.Child = Child
Beispiel #3
0
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        base = collection('test_doc',
                          session,
                          Field('_id', S.ObjectId),
                          Field('type', str, if_missing='base'),
                          Field('a', int),
                          polymorphic_on='type',
                          polymorphic_identity='base')
        derived = collection(base,
                             Field('type', str, if_missing='derived'),
                             Field('b', int),
                             polymorphic_identity='derived')

        class Base(object):
            pass

        class Derived(Base):
            pass

        mapper(Base, base, self.session)
        mapper(Derived, derived, self.session)
        self.Base = Base
        self.Derived = Derived
Beispiel #4
0
class TestReplacingSession(TestCase):
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class Basic(MappedClass):
            class __mongometa__:
                name = 'hook'
                session = self.session

            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)

        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)

    def test_hook_base(self):
        assert id(self.Basic.query.session) == id(self.session)
        session2 = MagicMock()
        new_session = ODMSession(bind=session2)
        Mapper.replace_session(new_session)
        assert id(self.Basic.query.session) == id(new_session)
        assert id(self.session) != id(new_session)
Beispiel #5
0
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.doc_session = Session(self.datastore)
        self.odm_session = ODMSession(self.doc_session)

        class Base(MappedClass):
            class __mongometa__:
                name = 'test_doc'
                session = self.odm_session
                polymorphic_on = 'type'
                polymorphic_identity = 'base'

            _id = FieldProperty(S.ObjectId)
            type = FieldProperty(str, if_missing='base')
            a = FieldProperty(int)

        class Derived(Base):
            class __mongometa__:
                polymorphic_identity = 'derived'

            type = FieldProperty(str, if_missing='derived')
            b = FieldProperty(int)

        Mapper.compile_all()
        self.Base = Base
        self.Derived = Derived
Beispiel #6
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     self.session = ODMSession(bind=self.datastore)
     class BasicMapperExtension(MapperExtension):
         def after_insert(self, instance, state, session):
             assert 'clean'==state.status
         def before_insert(self, instance, state, session):
             assert 'new'==state.status
         def before_update(self, instance, state, session):
             assert 'dirty'==state.status
         def after_update(self, instance, state, session):
             assert 'clean'==state.status
     class Basic(MappedClass):
         class __mongometa__:
             name='basic'
             session = self.session
             extensions = [BasicMapperExtension, MapperExtension]
         _id = FieldProperty(S.ObjectId)
         a = FieldProperty(int)
         b = FieldProperty([int])
         c = FieldProperty(dict(
                 d=int, e=int))
     Mapper.compile_all()
     self.Basic = Basic
     self.session.remove(self.Basic)
Beispiel #7
0
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class Parent(MappedClass):
            class __mongometa__:
                name = 'parent'
                session = self.session

            _id = FieldProperty(int)
            children = RelationProperty('Child')

        class Child(MappedClass):
            class __mongometa__:
                name = 'child'
                session = self.session

            _id = FieldProperty(int)
            parents = RelationProperty('Parent')
            _parents = ForeignIdProperty('Parent', uselist=True)

        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child
Beispiel #8
0
class TestPolymorphic(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        base = collection(
            'test_doc', session,
            Field('_id', S.ObjectId),
            Field('type', str, if_missing='base'),
            Field('a', int),
            polymorphic_on='type',
            polymorphic_identity='base')
        derived = collection(
            base, 
            Field('type', str, if_missing='derived'),
            Field('b', int),
            polymorphic_identity='derived')
        class Base(object): pass
        class Derived(Base): pass
        mapper(Base, base, self.session)
        mapper(Derived, derived, self.session)
        self.Base = Base
        self.Derived = Derived

    def test_polymorphic(self):
        self.Base(a=1)
        self.Derived(a=2,b=2)
        self.session.flush()
        self.session.clear()
        q = self.Base.query.find()
        r = sorted(q.all())
        assert r[0].__class__ is self.Base
        assert r[1].__class__ is self.Derived
Beispiel #9
0
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)

        class Parent(object):
            pass

        class Child(object):
            pass

        parent = collection('parent', session, Field('_id', int))
        child = collection('child', session, Field('_id', int),
                           Field('parent_id', int))
        mapper(Parent,
               parent,
               self.session,
               properties=dict(children=RelationProperty(Child)))
        mapper(Child,
               child,
               self.session,
               properties=dict(parent_id=ForeignIdProperty(Parent),
                               parent=RelationProperty(Parent)))
        self.Parent = Parent
        self.Child = Child
Beispiel #10
0
class TestPolymorphic(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        base = collection(
            'test_doc', session,
            Field('_id', S.ObjectId),
            Field('type', str, if_missing='base'),
            Field('a', int),
            polymorphic_on='type',
            polymorphic_identity='base')
        derived = collection(
            base,
            Field('type', str, if_missing='derived'),
            Field('b', int),
            polymorphic_identity='derived')
        class Base(object): pass
        class Derived(Base): pass
        mapper(Base, base, self.session)
        mapper(Derived, derived, self.session)
        self.Base = Base
        self.Derived = Derived

    def test_polymorphic(self):
        self.Base(a=1)
        self.Derived(a=2,b=2)
        self.session.flush()
        self.session.clear()
        q = self.Base.query.find()
        r = [x.__class__ for x in q]
        self.assertEqual(2, len(r))
        self.assertTrue(self.Base in r)
        self.assertTrue(self.Derived in r)
Beispiel #11
0
class TestBeforeSave(TestCase):
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class Basic(MappedClass):
            class __mongometa__:
                name = 'hook'
                session = self.session

                def before_save(instance):
                    instance.a = 9

            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)

        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)

    def test_hook_base(self):
        doc = self.Basic()
        doc.a = 5
        self.session.flush()  # first insert
        self.session.close()
        doc = self.Basic.query.get(doc._id)
        assert doc.a == 9, doc.a
        doc.a = 6
        self.session.flush()  # then save
        self.session.close()
        doc = self.Basic.query.get(doc._id)
        assert doc.a == 9, doc.a
Beispiel #12
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     self.session = ODMSession(bind=self.datastore)
     class GrandParent(MappedClass):
         class __mongometa__:
             name='grand_parent'
             session=self.session
         _id = FieldProperty(int)
     class Parent(MappedClass):
         class __mongometa__:
             name='parent'
             session = self.session
         _id = FieldProperty(int)
         grandparent_id = ForeignIdProperty('GrandParent')
         grandparent = RelationProperty('GrandParent')
         children = RelationProperty('Child')
     class Child(MappedClass):
         class __mongometa__:
             name='child'
             session = self.session
         _id = FieldProperty(int)
         parent_id = ForeignIdProperty('Parent', allow_none=True)
         parent = RelationProperty('Parent')
     Mapper.compile_all()
     self.GrandParent = GrandParent
     self.Parent = Parent
     self.Child = Child
Beispiel #13
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     session = Session(bind=self.datastore)
     self.session = ODMSession(session)
     basic = collection('basic', session)
     class Basic(object):
         pass
     self.session.mapper(Basic, basic)
     self.basic = basic
     self.Basic = Basic
Beispiel #14
0
class TestRelation(TestCase):
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)

        class Parent(object):
            pass

        class Child(object):
            pass

        parent = collection('parent', session, Field('_id', int))
        child = collection('child', session, Field('_id', int),
                           Field('parent_id', int))
        mapper(Parent,
               parent,
               self.session,
               properties=dict(children=RelationProperty(Child)))
        mapper(Child,
               child,
               self.session,
               properties=dict(parent_id=ForeignIdProperty(Parent),
                               parent=RelationProperty(Parent)))
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_parent(self):
        parent = self.Parent(_id=1)
        children = [self.Child(_id=i, parent_id=1) for i in range(5)]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)

    def test_readonly(self):
        parent = self.Parent(_id=1)
        children = [self.Child(_id=i, parent_id=1) for i in range(5)]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)

        def clearchildren():
            parent.children = []

        def setchild():
            parent.children[0] = children[0]

        self.assertRaises(TypeError, clearchildren)
        self.assertRaises(TypeError, parent.children.append, children[0])
        self.assertRaises(TypeError, setchild)
Beispiel #15
0
class TestRelation(TestCase):
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class Parent(MappedClass):
            class __mongometa__:
                name = 'parent'
                session = self.session

            _id = FieldProperty(int)
            children = RelationProperty('Child')

        class Child(MappedClass):
            class __mongometa__:
                name = 'child'
                session = self.session

            _id = FieldProperty(int)
            parent_id = ForeignIdProperty('Parent')
            parent = RelationProperty('Parent')

        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_parent(self):
        parent = self.Parent(_id=1)
        children = [self.Child(_id=i, parent_id=1) for i in range(5)]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)

    def test_readonly(self):
        parent = self.Parent(_id=1)
        children = [self.Child(_id=i, parent_id=1) for i in range(5)]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)

        def clearchildren():
            parent.children = []

        def setchild():
            parent.children[0] = children[0]

        self.assertRaises(TypeError, clearchildren)
        self.assertRaises(TypeError, parent.children.append, children[0])
        self.assertRaises(TypeError, setchild)
Beispiel #16
0
class ObjectIdRelationship(TestCase):
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        class Parent(MappedClass):
            class __mongometa__:
                name='parent'
                session = self.session
            _id = FieldProperty(S.ObjectId)
            children = ForeignIdProperty('Child', uselist=True)
            field_with_default_id = ForeignIdProperty(
                'Child',
                uselist=True,
                if_missing=lambda:[bson.ObjectId('deadbeefdeadbeefdeadbeef')])
            field_with_default = RelationProperty('Child', 'field_with_default_id')
        class Child(MappedClass):
            class __mongometa__:
                name='child'
                session = self.session
            _id = FieldProperty(S.ObjectId)
            parent_id = ForeignIdProperty(Parent)
            field_with_default_id = ForeignIdProperty(
                Parent,
                if_missing=lambda:bson.ObjectId('deadbeefdeadbeefdeadbeef'))
            field_with_default = RelationProperty('Parent', 'field_with_default_id')
        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_empty_relationship(self):
        child = self.Child()
        self.session.flush()
        self.assertIsNone(child.parent_id)

    def test_empty_list_relationship(self):
        parent = self.Parent()
        self.session.flush()
        self.assertEqual(parent.children, [])

    def test_default_relationship(self):
        parent = self.Parent(_id=bson.ObjectId('deadbeefdeadbeefdeadbeef'))
        child = self.Child()
        self.session.flush()
        self.assertEqual(child.field_with_default, parent)

    def test_default_list_relationship(self):
        child = self.Child(_id=bson.ObjectId('deadbeefdeadbeefdeadbeef'))
        parent = self.Parent()
        self.session.flush()
        self.assertEqual(parent.field_with_default, [child])
Beispiel #17
0
class TestMapping(TestCase):
    DATASTORE = 'mim:///test_db'

    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore(self.DATASTORE)
        self.session = ODMSession(bind=self.datastore)

    def tearDown(self):
        self.session.clear()
        try:
            self.datastore.conn.drop_all()
        except TypeError:
            self.datastore.conn.drop_database(self.datastore.db)
        Mapper._mapper_by_classname.clear()

    def test_with_mixins(self):
        class Mixin1(object):
            def __init__(self):
                pass

            def dosomething(self):
                pass

        class Mixin2(object):
            def domore(self):
                pass

        class User(MappedClass, Mixin1, Mixin2):
            class __mongometa__:
                name = "userswithmixin"
                session = self.session

            _id = FieldProperty(S.ObjectId)
            username = FieldProperty(str)

        u = User(_id=None, username="******")
        self.session.flush()

        u2 = User.query.find({"username": "******"}).first()
        assert u._id == u2._id

    def test_delete_super(self):
        class User(MappedClass):
            class __mongometa__:
                name = "user_with_custom_delete"
                session = self.session

            _id = FieldProperty(S.ObjectId)
            username = FieldProperty(str)

            def delete(self):
                super(User, self).delete()

        u = User(_id=None, username="******")
        self.session.flush()
        u.delete()
        self.session.flush()

        assert not User.query.find({"username": "******"}).count()
Beispiel #18
0
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection('basic', session, Field('_id', S.ObjectId),
                           Field('a', int), Field('b', [int]),
                           Field('c', dict(d=int, e=int)))

        class Basic(object):
            pass

        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic
Beispiel #19
0
class TestRelation(TestCase):
    def setUp(self):
        self.datastore = DS.DataStore(
            'mim:///', database='test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        class Parent(object): pass
        class Child(object): pass
        parent = collection(
            'parent', session,
            Field('_id', int))
        child = collection(
            'child', session,
            Field('_id', int),
            Field('parent_id', int))
        mapper(Parent, parent, self.session, properties=dict(
                children=RelationProperty(Child)))
        mapper(Child, child, self.session, properties=dict(
                parent_id=ForeignIdProperty(Parent),
                parent = RelationProperty(Parent)))
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_parent(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)

    def test_readonly(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        def clearchildren():
            parent.children = []
        def setchild():
            parent.children[0] = children[0]
        self.assertRaises(TypeError, clearchildren)
        self.assertRaises(TypeError, parent.children.append, children[0])
        self.assertRaises(TypeError, setchild)
Beispiel #20
0
class TestRelation(TestCase):

    def setUp(self):
        self.datastore = DS.DataStore(
            'mim:///', database='test_db')
        self.session = ODMSession(bind=self.datastore)
        class Parent(MappedClass):
            class __mongometa__:
                name='parent'
                session = self.session
            _id = FieldProperty(int)
            children = RelationProperty('Child')
        class Child(MappedClass):
            class __mongometa__:
                name='child'
                session = self.session
            _id = FieldProperty(int)
            parent_id = ForeignIdProperty('Parent')
            parent = RelationProperty('Parent')
        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_parent(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)

    def test_readonly(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        def clearchildren():
            parent.children = []
        def setchild():
            parent.children[0] = children[0]
        self.assertRaises(TypeError, clearchildren)
        self.assertRaises(TypeError, parent.children.append, children[0])
        self.assertRaises(TypeError, setchild)
Beispiel #21
0
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class TestCollection(MappedClass):
            class __mongometa__:
                name='test_collection'
                session = self.session
            _id = FieldProperty(int)

            children = RelationProperty('TestCollection')
            _children = ForeignIdProperty('TestCollection', uselist=True)
            parents = RelationProperty('TestCollection', via=('_children', False))

        Mapper.compile_all()
        self.TestCollection = TestCollection
Beispiel #22
0
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class Basic(MappedClass):
            class __mongometa__:
                name = 'hook'
                session = self.session

            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)

        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)
Beispiel #23
0
 def test_hook_base(self):
     assert id(self.Basic.query.session) == id(self.session)
     session2 = MagicMock()
     new_session = ODMSession(bind=session2)
     Mapper.replace_session(new_session)
     assert id(self.Basic.query.session) == id(new_session)
     assert id(self.session) != id(new_session)
Beispiel #24
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     self.session = ODMSession(bind=self.datastore)
     class Basic(MappedClass):
         class __mongometa__:
             name='basic'
             session = self.session
         _id = FieldProperty(S.ObjectId)
         a = FieldProperty(int)
         b = FieldProperty([int])
         c = FieldProperty(dict(
                 d=int, e=int))
         d = FieldPropertyWithMissingNone(str, if_missing=S.Missing)
         e = FieldProperty(str, if_missing=S.Missing)
     Mapper.compile_all()
     self.Basic = Basic
     self.session.remove(self.Basic)
Beispiel #25
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     session = Session(bind=self.datastore)
     self.session = ODMSession(session)
     basic = collection('basic', session)
     class Basic(object):
         pass                    
     self.session.mapper(Basic, basic)
     self.basic = basic
     self.Basic = Basic
Beispiel #26
0
class TestWithNoFields(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection('basic', session)
        class Basic(object):
            pass                    
        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_query(self):
        self.basic(dict(a=1)).m.insert()
        doc = self.Basic.query.get(a=1)
Beispiel #27
0
class TestWithNoFields(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection('basic', session)
        class Basic(object):
            pass
        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_query(self):
        self.basic(dict(a=1)).m.insert()
        doc = self.Basic.query.get(a=1)
Beispiel #28
0
class TestManyToManyListReverseRelation(TestCase):
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class Parent(MappedClass):
            class __mongometa__:
                name = 'parent'
                session = self.session

            _id = FieldProperty(int)
            children = RelationProperty('Child')

        class Child(MappedClass):
            class __mongometa__:
                name = 'child'
                session = self.session

            _id = FieldProperty(int)
            parents = RelationProperty('Parent')
            _parents = ForeignIdProperty('Parent', uselist=True)

        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_compiled_field(self):
        self.assertEqual(self.Child._parents.field.type,
                         [self.Parent._id.field.type])

    def test_parent(self):
        parent = self.Parent(_id=1)
        other_parent = self.Parent(_id=2)

        children = [self.Child(_id=i, _parents=[parent._id]) for i in range(5)]
        for c in children[:2]:
            c._parents.append(other_parent._id)
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)
        self.session.clear()

        child = self.Child.query.get(_id=0)
        self.assertEqual(len(child.parents), 2)
Beispiel #29
0
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        self.hooks_called = defaultdict(list)
        tc = self

        class Basic(MappedClass):
            class __mongometa__:
                name = 'hook'
                session = self.session

                def before_save(instance):
                    tc.hooks_called['before_save'].append(instance)

            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)

        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)
Beispiel #30
0
class TestPolymorphic(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.doc_session = Session(self.datastore)
        self.odm_session = ODMSession(self.doc_session)
        class Base(MappedClass):
            class __mongometa__:
                name='test_doc'
                session = self.odm_session
                polymorphic_on='type'
                polymorphic_identity='base'
            _id = FieldProperty(S.ObjectId)
            type=FieldProperty(str, if_missing='base')
            a=FieldProperty(int)
        class Derived(Base):
            class __mongometa__:
                polymorphic_identity='derived'
            type=FieldProperty(str, if_missing='derived')
            b=FieldProperty(int)
        Mapper.compile_all()
        self.Base = Base
        self.Derived = Derived

    def test_polymorphic(self):
        self.Base(a=1)
        self.odm_session.flush()
        self.Derived(a=2,b=2)
        self.odm_session.flush()
        self.odm_session.clear()
        q = self.Base.query.find()
        r = [x.__class__ for x in q]
        self.assertEqual(2, len(r))
        self.assertTrue(self.Base in r)
        self.assertTrue(self.Derived in r)
Beispiel #31
0
class TestPolymorphic(TestCase):

    def setUp(self):
        self.bind = DS.DataStore(master='mim:///', database='test_db')
        self.doc_session = Session(self.bind)
        self.odm_session = ODMSession(self.doc_session)
        class Base(MappedClass):
            class __mongometa__:
                name='test_doc'
                session = self.odm_session
                polymorphic_on='type'
                polymorphic_identity='base'
            _id = FieldProperty(S.ObjectId)
            type=FieldProperty(str, if_missing='base')
            a=FieldProperty(int)
        class Derived(Base):
            class __mongometa__:
                polymorphic_identity='derived'
            type=FieldProperty(str, if_missing='derived')
            b=FieldProperty(int)
        Mapper.compile_all()
        self.Base = Base
        self.Derived = Derived

    def test_polymorphic(self):
        self.Base(a=1)
        self.odm_session.flush()
        self.Derived(a=2,b=2)
        self.odm_session.flush()
        self.odm_session.clear()
        q = self.Base.query.find()
        r = sorted(q.all())
        assert r[0].__class__ is self.Base
        assert r[1].__class__ is self.Derived
class TestManyToManyListReverseRelation(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        class Parent(MappedClass):
            class __mongometa__:
                name='parent'
                session = self.session
            _id = FieldProperty(int)
            children = RelationProperty('Child')
        class Child(MappedClass):
            class __mongometa__:
                name='child'
                session = self.session
            _id = FieldProperty(int)
            parents = RelationProperty('Parent')
            _parents = ForeignIdProperty('Parent', uselist=True)
        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_compiled_field(self):
        self.assertEqual(self.Child._parents.field.type, [self.Parent._id.field.type])

    def test_parent(self):
        parent = self.Parent(_id=1)
        other_parent = self.Parent(_id=2)

        children = [ self.Child(_id=i, _parents=[parent._id]) for i in range(5) ]
        for c in children[:2]:
            c._parents.append(other_parent._id)
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)
        self.session.clear()

        child = self.Child.query.get(_id=0)
        self.assertEqual(len(child.parents), 2)
Beispiel #33
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     session = Session(bind=self.datastore)
     self.session = ODMSession(session)
     basic = collection(
         'basic', session,
         Field('_id', S.ObjectId),
         Field('a', int),
         Field('b', [int]),
         Field('c', dict(
                 d=int, e=int)))
     class Basic(object):
         pass                    
     self.session.mapper(Basic, basic)
     self.basic = basic
     self.Basic = Basic
Beispiel #34
0
class TestManyToManyListCyclic(TestCase):
    def setUp(self):
        Mapper._mapper_by_classname.clear()
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class TestCollection(MappedClass):
            class __mongometa__:
                name = 'test_collection'
                session = self.session

            _id = FieldProperty(int)

            children = RelationProperty('TestCollection')
            _children = ForeignIdProperty('TestCollection', uselist=True)
            parents = RelationProperty('TestCollection',
                                       via=('_children', False))

        Mapper.compile_all()
        self.TestCollection = TestCollection

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_compiled_field(self):
        self.assertEqual(self.TestCollection._children.field.type,
                         [self.TestCollection._id.field.type])

    def test_cyclic(self):
        children = [self.TestCollection(_id=i) for i in range(10, 15)]
        parent = self.TestCollection(_id=1)
        parent._children = [c._id for c in children]
        other_parent = self.TestCollection(_id=2)
        other_parent._children = [c._id for c in children[:2]]
        self.session.flush()
        self.session.clear()

        parent = self.TestCollection.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)
        self.session.clear()

        child = self.TestCollection.query.get(_id=10)
        self.assertEqual(len(child.parents), 2)
class TestManyToManyListCyclic(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)

        class TestCollection(MappedClass):
            class __mongometa__:
                name='test_collection'
                session = self.session
            _id = FieldProperty(int)

            children = RelationProperty('TestCollection')
            _children = ForeignIdProperty('TestCollection', uselist=True)
            parents = RelationProperty('TestCollection', via=('_children', False))

        Mapper.compile_all()
        self.TestCollection = TestCollection

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_compiled_field(self):
        self.assertEqual(self.TestCollection._children.field.type, [self.TestCollection._id.field.type])

    def test_cyclic(self):
        children = [ self.TestCollection(_id=i) for i in range(10, 15) ]
        parent = self.TestCollection(_id=1)
        parent._children = [c._id for c in children]
        other_parent = self.TestCollection(_id=2)
        other_parent._children = [c._id for c in children[:2]]
        self.session.flush()
        self.session.clear()

        parent = self.TestCollection.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)
        self.session.clear()

        child = self.TestCollection.query.get(_id=10)
        self.assertEqual(len(child.parents), 2)
Beispiel #36
0
 def setUp(self):
     self.datastore = DS.DataStore(
         'mim:///', database='test_db')
     self.session = ODMSession(bind=self.datastore)
     class Parent(MappedClass):
         class __mongometa__:
             name='parent'
             session = self.session
         _id = FieldProperty(int)
         children = RelationProperty('Child')
     class Child(MappedClass):
         class __mongometa__:
             name='child'
             session = self.session
         _id = FieldProperty(int)
         parent_id = ForeignIdProperty('Parent')
         parent = RelationProperty('Parent')
     Mapper.compile_all()
     self.Parent = Parent
     self.Child = Child
Beispiel #37
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     session = Session(bind=self.datastore)
     self.session = ODMSession(session)
     class Parent(object): pass
     class Child(object): pass
     parent = collection(
         'parent', session,
         Field('_id', int))
     child = collection(
         'child', session,
         Field('_id', int),
         Field('parent_id', int))
     mapper(Parent, parent, self.session, properties=dict(
             children=RelationProperty(Child)))
     mapper(Child, child, self.session, properties=dict(
             parent_id=ForeignIdProperty(Parent),
             parent = RelationProperty(Parent)))
     self.Parent = Parent
     self.Child = Child
Beispiel #38
0
class TestBasicMapperExtension(TestCase):
    def setUp(self):
        self.datastore = DS.DataStore(
            'mim:///', database='test_db')
        self.session = ODMSession(bind=self.datastore)
        class BasicMapperExtension(MapperExtension):
            def after_insert(self, instance, state, session):
                assert 'clean'==state.status
            def before_insert(self, instance, state, session):
                assert 'new'==state.status
            def before_update(self, instance, state, session):
                assert 'dirty'==state.status
            def after_update(self, instance, state, session):
                assert 'clean'==state.status
        class Basic(MappedClass):
            class __mongometa__:
                name='basic'
                session = self.session
                extensions = [BasicMapperExtension, MapperExtension]
            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)
            b = FieldProperty([int])
            c = FieldProperty(dict(
                    d=int, e=int))
        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_mapper_extension(self):
        doc = self.Basic()
        doc.a = 5
        self.session.flush()
        doc.a = 6
        self.session.flush()
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     self.doc_session = Session(self.datastore)
     self.odm_session = ODMSession(self.doc_session)
     class Base(MappedClass):
         class __mongometa__:
             name='test_doc'
             session = self.odm_session
             polymorphic_on='type'
             polymorphic_identity='base'
         _id = FieldProperty(S.ObjectId)
         type=FieldProperty(str, if_missing='base')
         a=FieldProperty(int)
     class Derived(Base):
         class __mongometa__:
             polymorphic_identity='derived'
         type=FieldProperty(str, if_missing='derived')
         b=FieldProperty(int)
     Mapper.compile_all()
     self.Base = Base
     self.Derived = Derived
Beispiel #40
0
    def setupClass(cls):
        if ming is None:
            raise SkipTest('Ming not available...')

        cls.basic_session = Session(create_datastore('mim:///'))
        cls.s = ODMSession(cls.basic_session)

        class Author(MappedClass):
            class __mongometa__:
                session = cls.s
                name = 'wiki_author'

            _id = FieldProperty(schema.ObjectId)
            name = FieldProperty(str)
            pages = RelationProperty('WikiPage')

        class WikiPage(MappedClass):
            class __mongometa__:
                session = cls.s
                name = 'wiki_page'

            _id = FieldProperty(schema.ObjectId)
            title = FieldProperty(str)
            text = FieldProperty(str)
            order = FieldProperty(int)
            author_id = ForeignIdProperty(Author)
            author = RelationProperty(Author)

        cls.Author = Author
        cls.WikiPage = WikiPage
        Mapper.compile_all()

        cls.author = Author(name='author1')
        author2 = Author(name='author2')

        WikiPage(title='Hello', text='Text', order=1, author=cls.author)
        WikiPage(title='Another', text='Text', order=2, author=cls.author)
        WikiPage(title='ThirdOne', text='Text', order=3, author=author2)
        cls.s.flush()
        cls.s.clear()
Beispiel #41
0
 def setUp(self):
     self.datastore = create_datastore('mim:///test_db')
     session = Session(bind=self.datastore)
     self.session = ODMSession(session)
     base = collection(
         'test_doc', session,
         Field('_id', S.ObjectId),
         Field('type', str, if_missing='base'),
         Field('a', int),
         polymorphic_on='type',
         polymorphic_identity='base')
     derived = collection(
         base, 
         Field('type', str, if_missing='derived'),
         Field('b', int),
         polymorphic_identity='derived')
     class Base(object): pass
     class Derived(Base): pass
     mapper(Base, base, self.session)
     mapper(Derived, derived, self.session)
     self.Base = Base
     self.Derived = Derived
Beispiel #42
0
def run_migration(datastore, target_versions, dry_run):
    '''Attempt to migrate the database to a specific set of required
    modules  & versions.'''
    # Get the migration status of the db
    session = MigrationInfo.__mongometa__.session
    session.bind = datastore
    odmsession = ODMSession(session)
    info = MigrationInfo.m.get()
    if info is None:
        info = MigrationInfo.make({})
    latest_versions = Migration.latest_versions()
    for k, v in target_versions.iteritems():
        cur = info.versions.get(k, -1)
        islatest = ' (LATEST)' if v == latest_versions[k] else ''
        log.info('Target %s=%s%s (current=%s)', k, v, islatest, cur)
    # Create a migration plan
    plan = list(plan_migration(session, odmsession, info, target_versions))
    # Execute (or print) the plan
    for step in plan:
        log.info('Migrate %r', step)
        if dry_run: continue
        step.apply(info.versions)
        info.m.save()
Beispiel #43
0
class TestOrphanObjects(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection('basic', session)
        class Basic(object):
            pass                    
        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_orphan_object(self):
        obj = self.Basic()
        assert session(obj) is self.session
        self.session.clear()
        assert session(obj) is None
Beispiel #44
0
class TestOrphanObjects(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection('basic', session)
        class Basic(object):
            pass
        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.clear_all()
        self.datastore.conn.drop_all()

    def test_orphan_object(self):
        obj = self.Basic()
        assert session(obj) is self.session
        self.session.clear()
        assert session(obj) is None
class TestRelationWithNone(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        class GrandParent(MappedClass):
            class __mongometa__:
                name='grand_parent'
                session=self.session
            _id = FieldProperty(int)
        class Parent(MappedClass):
            class __mongometa__:
                name='parent'
                session = self.session
            _id = FieldProperty(int)
            grandparent_id = ForeignIdProperty('GrandParent')
            grandparent = RelationProperty('GrandParent')
            children = RelationProperty('Child')
        class Child(MappedClass):
            class __mongometa__:
                name='child'
                session = self.session
            _id = FieldProperty(int)
            parent_id = ForeignIdProperty('Parent', allow_none=True)
            parent = RelationProperty('Parent')
        Mapper.compile_all()
        self.GrandParent = GrandParent
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_none_allowed(self):
        parent = self.Parent(_id=1)
        child = self.Child(_id=1, parent_id=parent._id)
        none_parent = self.Parent(_id=None)
        none_child = self.Child(_id=2, parent_id=None)
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=1)
        parent = child.parent
        self.assertEqual(parent._id, 1)

        none_child = self.Child.query.get(_id=2)
        none_parent = none_child.parent
        self.assertNotEqual(none_parent, None)
        self.assertEqual(none_parent._id, None)

    def test_none_not_allowed(self):
        grandparent = self.GrandParent(_id=1)
        parent = self.Parent(_id=1, grandparent_id=grandparent._id)
        none_grandparent = self.GrandParent(_id=None)
        none_parent = self.Parent(_id=2, grandparent_id=None)
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        grandparent = parent.grandparent
        self.assertEqual(grandparent._id, 1)

        none_parent = self.Parent.query.get(_id=2)
        none_grandparent = none_parent.grandparent
        self.assertEqual(none_grandparent, None)
class TestManyToManyListRelation(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        class Parent(MappedClass):
            class __mongometa__:
                name='parent'
                session = self.session
            _id = FieldProperty(int)
            children = RelationProperty('Child')
            _children = ForeignIdProperty('Child', uselist=True)
        class Child(MappedClass):
            class __mongometa__:
                name='child'
                session = self.session
            _id = FieldProperty(int)
            parents = RelationProperty('Parent')
        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_compiled_field(self):
        self.assertEqual(self.Parent._children.field.type, [self.Child._id.field.type])

    def test_parent(self):
        children = [ self.Child(_id=i) for i in range(5) ]
        parent = self.Parent(_id=1)
        parent._children = [c._id for c in children]
        other_parent = self.Parent(_id=2)
        other_parent._children = [c._id for c in children[:2]]
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)
        self.session.clear()

        child = self.Child.query.get(_id=0)
        self.assertEqual(len(child.parents), 2)

    def test_instrumented_readonly(self):
        children = [ self.Child(_id=i) for i in range(5) ]
        parent = self.Parent(_id=1)
        parent._children = [c._id for c in children]
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertRaises(TypeError, parent.children.append, children[0])

    def test_writable(self):
        children = [ self.Child(_id=i) for i in range(5) ]
        parent = self.Parent(_id=1)
        parent._children = [c._id for c in children]
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        parent.children = parent.children + [self.Child(_id=5)]
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 6)
        self.session.clear()

        child = self.Child.query.get(_id=5)
        self.assertEqual(len(child.parents), 1)

        parent = self.Parent.query.get(_id=1)
        parent.children = []
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 0)
        self.session.clear()

    def test_writable_backref(self):
        children = [ self.Child(_id=i) for i in range(5) ]
        parent = self.Parent(_id=1)
        parent._children = [c._id for c in children]
        other_parent = self.Parent(_id=2)
        other_parent._children = [c._id for c in children[:2]]
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=4)
        self.assertEqual(len(child.parents), 1)
        child.parents = child.parents + [other_parent]
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=4)
        self.assertEqual(len(child.parents), 2)
        self.session.clear()

        child = self.Child.query.get(_id=4)
        child.parents = [parent]
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=4)
        self.assertEqual(len(child.parents), 1)
        self.session.clear()
Beispiel #47
0
class TestBasicMapping(TestCase):
    
    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection(
            'basic', session,
            Field('_id', S.ObjectId),
            Field('a', int),
            Field('b', [int]),
            Field('c', dict(
                    d=int, e=int)))
        class Basic(object):
            pass                    
        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_set_to_same(self):
        obj = self.Basic(a=1)
        assert state(obj).status == 'new'
        self.session.flush()
        assert state(obj).status == 'clean'
        obj.a = 1
        assert state(obj).status == 'clean'

    def test_disable_instrument(self):
        # Put a doc in the DB
        self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        # Load back with instrumentation
        self.session.clear()
        obj = self.Basic.query.find().options(instrument=True).first()
        self.assertEqual(type(obj.b), InstrumentedList)
        self.assertEqual(type(obj.c), InstrumentedObj)
        # Load back without instrumentation
        self.session.clear()
        obj = self.Basic.query.find().options(instrument=False).first()
        self.assertEqual(type(obj.b), list)
        self.assertEqual(type(obj.c), Object)

    def test_enable_instrument(self):
        session = Session(bind=self.datastore)
        basic1 = collection(
            'basic1', session,
            Field('_id', S.ObjectId),
            Field('a', int),
            Field('b', [int]),
            Field('c', dict(
                    d=int, e=int)))
        class Basic1(object):
            pass                    
        self.session.mapper(Basic1, basic1, options=dict(instrument=False))
        # Put a doc in the DB
        Basic1(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        # Load back with instrumentation
        self.session.clear()
        obj = Basic1.query.find().options(instrument=True).first()
        self.assertEqual(type(obj.b), InstrumentedList)
        self.assertEqual(type(obj.c), InstrumentedObj)
        # Load back without instrumentation
        self.session.clear()
        obj = Basic1.query.find().options(instrument=False).first()
        self.assertEqual(type(obj.b), list)
        self.assertEqual(type(obj.c), Object)

    def test_repr(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4,e=5))
        sdoc = repr(doc)
        assert 'a=1' in sdoc, sdoc
        assert 'b=I[2, 3]' in sdoc, sdoc
        assert "c=I{'e': 5, 'd': 4}" in sdoc, sdoc

    def test_create(self):
        doc = self.Basic()
        assert state(doc).status == 'new'
        self.session.flush()
        assert state(doc).status == 'clean'
        doc.a = 5
        assert state(doc).status == 'dirty'
        self.session.flush()
        assert state(doc).status == 'clean'
        c = doc.c
        c.e = 5
        assert state(doc).status == 'dirty', state(doc).status
        assert repr(state(doc)).startswith('<ObjectState')

    def test_mapped_object(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.assertEqual(doc.a, doc['a'])
        self.assertRaises(AttributeError, getattr, doc, 'foo')
        self.assertRaises(KeyError, doc.__getitem__, 'foo')
        doc['a'] = 5
        self.assertEqual(doc.a, doc['a'])
        self.assertEqual(doc.a, 5)
        self.assert_('a' in doc)
        doc.delete()

    def test_mapper(self):
        m = mapper(self.Basic)
        assert repr(m) == '<Mapper Basic:basic>'
        self.datastore.db.basic.insert(dict(
                a=1, b=[2,3], c=dict(d=4, e=5), f='unknown'))
        print list(self.datastore.db.basic.find())
        obj = self.Basic.query.find().options(instrument=False).first()
        print obj
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        self.session.remove(self.Basic, {})
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 0)

    def test_query(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 1)
        doc.a = 5
        self.session.flush()
        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 0)
        self.assertEqual(doc.query.find(dict(a=1)).count(), 0)
        self.assertEqual(doc.query.find(dict(b=doc.b)).count(), 1)
        doc = self.Basic.query.get(a=5)
        self.assert_(doc is not None)
        self.Basic.query.remove({})
        self.assertEqual(self.Basic.query.find().count(), 0)

    def test_delete(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        doc.delete()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 0)
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        
    def test_imap(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        doc1 = self.Basic.query.get(_id=doc._id)
        self.assert_(doc is doc1)
        self.session.expunge(doc)
        doc1 = self.Basic.query.get(_id=doc._id)
        self.assert_(doc is not doc1)
        self.session.expunge(doc)
        self.session.expunge(doc)
        self.session.expunge(doc)
Beispiel #48
0
class TestBasicMapping(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        session = Session(bind=self.datastore)
        self.session = ODMSession(session)
        basic = collection(
            'basic', session,
            Field('_id', S.ObjectId),
            Field('a', int),
            Field('b', [int]),
            Field('c', dict(
                    d=int, e=int)))
        class Basic(object):
            pass
        self.session.mapper(Basic, basic)
        self.basic = basic
        self.Basic = Basic

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_set_to_same(self):
        obj = self.Basic(a=1)
        assert state(obj).status == 'new'
        self.session.flush()
        assert state(obj).status == 'clean'
        obj.a = 1
        assert state(obj).status == 'clean'

    def test_disable_instrument(self):
        # Put a doc in the DB
        self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        # Load back with instrumentation
        self.session.clear()
        obj = self.Basic.query.find().options(instrument=True).first()
        self.assertEqual(type(obj.b), InstrumentedList)
        self.assertEqual(type(obj.c), InstrumentedObj)
        # Load back without instrumentation
        self.session.clear()
        obj = self.Basic.query.find().options(instrument=False).first()
        self.assertEqual(type(obj.b), list)
        self.assertEqual(type(obj.c), Object)

    def test_enable_instrument(self):
        session = Session(bind=self.datastore)
        basic1 = collection(
            'basic1', session,
            Field('_id', S.ObjectId),
            Field('a', int),
            Field('b', [int]),
            Field('c', dict(
                    d=int, e=int)))
        class Basic1(object):
            pass
        self.session.mapper(Basic1, basic1, options=dict(instrument=False))
        # Put a doc in the DB
        Basic1(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        # Load back with instrumentation
        self.session.clear()
        obj = Basic1.query.find().options(instrument=True).first()
        self.assertEqual(type(obj.b), InstrumentedList)
        self.assertEqual(type(obj.c), InstrumentedObj)
        # Load back without instrumentation
        self.session.clear()
        obj = Basic1.query.find().options(instrument=False).first()
        self.assertEqual(type(obj.b), list)
        self.assertEqual(type(obj.c), Object)

    def test_repr(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        sdoc = repr(doc)
        # sometimes there's a line break in the repr
        sdoc_cleaned = sdoc.replace('\n ', '')
        assert 'a=1' in sdoc_cleaned, sdoc_cleaned
        assert 'b=I[2, 3]' in sdoc_cleaned, sdoc_cleaned
        # order is not guaranteed with dictionaries
        assert "c=I{'d': 4, 'e': 5}" in sdoc_cleaned or \
            "c=I{'e': 5, 'd': 4}" in sdoc_cleaned, sdoc_cleaned

    def test_create(self):
        doc = self.Basic()
        assert state(doc).status == 'new'
        self.session.flush()
        assert state(doc).status == 'clean'
        doc.a = 5
        assert state(doc).status == 'dirty'
        self.session.flush()
        assert state(doc).status == 'clean'
        c = doc.c
        c.e = 5
        assert state(doc).status == 'dirty', state(doc).status
        assert repr(state(doc)).startswith('<ObjectState')

    def test_mapped_object(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.assertEqual(doc.a, doc['a'])
        self.assertRaises(AttributeError, getattr, doc, 'foo')
        self.assertRaises(KeyError, doc.__getitem__, 'foo')
        doc['a'] = 5
        self.assertEqual(doc.a, doc['a'])
        self.assertEqual(doc.a, 5)
        self.assert_('a' in doc)
        doc.delete()

    def test_mapper(self):
        m = mapper(self.Basic)
        assert repr(m) == '<Mapper Basic:basic>'
        self.datastore.db.basic.insert(dict(
                a=1, b=[2,3], c=dict(d=4, e=5), f='unknown'))
        obj = self.Basic.query.find().options(instrument=False).first()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        self.session.remove(self.Basic, {})
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 0)

    def test_query(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 1)
        doc.a = 5
        self.session.flush()
        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 0)
        self.assertEqual(doc.query.find(dict(a=1)).count(), 0)
        self.assertEqual(doc.query.find(dict(b=doc.b)).count(), 1)
        doc = self.Basic.query.get(a=5)
        self.assert_(doc is not None)
        self.Basic.query.remove({})
        self.assertEqual(self.Basic.query.find().count(), 0)

    def test_query_fields(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        self.session.clear()

        q = self.Basic.query.find(dict(a=1), fields=['b'])
        self.assertEqual(q.count(), 1)

        o = q.first()
        self.assertEqual(o.b, [2,3])
        self.assertEqual(o.a, None)
        o.b = [4,5]
        self.session.flush()
        self.session.clear()

        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 1)

        o = q.first()
        self.assertEqual(o.a, 1)
        self.assertEqual(o.b, [4, 5])
        self.assertEqual(o.c, dict(d=4, e=5))

        self.Basic.query.remove({})
        self.assertEqual(self.Basic.query.find().count(), 0)

    def test_delete(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        doc.delete()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 0)
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)

    def test_imap(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        doc1 = self.Basic.query.get(_id=doc._id)
        self.assert_(doc is doc1)
        self.session.expunge(doc)
        doc1 = self.Basic.query.get(_id=doc._id)
        self.assert_(doc is not doc1)
        self.session.expunge(doc)
        self.session.expunge(doc)
        self.session.expunge(doc)

    @patch('pymongo.collection.Collection.aggregate')
    def test_aggregate(self, pymongo_aggregate):
        self.Basic.query.aggregate([])
        assert pymongo_aggregate.called

    @patch('ming.mim.Collection.map_reduce')
    def test_map_reduce(self, mim_map_reduce):
        self.Basic.query.map_reduce('...', '...', {})
        assert mim_map_reduce.called

    @patch('ming.mim.Collection.distinct')
    def test_distinct(self, mim_distinct):
        self.Basic.query.distinct('field')
        assert mim_distinct.called

    @patch('pymongo.collection.Collection.inline_map_reduce')
    def test_inline_map_reduce(self, pymongo_inline_map_reduce):
        self.Basic.query.inline_map_reduce()
        assert pymongo_inline_map_reduce.called

    @patch('pymongo.collection.Collection.group')
    def test_group(self, pymongo_group):
        self.Basic.query.group()
        assert pymongo_group.called
class TestRelation(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        class Parent(MappedClass):
            class __mongometa__:
                name='parent'
                session = self.session
            _id = FieldProperty(int)
            children = RelationProperty('Child')
        class Child(MappedClass):
            class __mongometa__:
                name='child'
                session = self.session
            _id = FieldProperty(int)
            parent_id = ForeignIdProperty('Parent')
            parent = RelationProperty('Parent')
        Mapper.compile_all()
        self.Parent = Parent
        self.Child = Child

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_parent(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 5)

    def test_instrumented_readonly(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()
        parent = self.Parent.query.get(_id=1)
        self.assertRaises(TypeError, parent.children.append, children[0])

    def test_writable(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        other_parent = self.Parent(_id=2)
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=4)
        child.parent = other_parent
        self.session.flush()
        self.session.clear()

        parent1 = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent1.children), 4)

        parent2 = self.Parent.query.get(_id=2)
        self.assertEqual(len(parent2.children), 1)

    def test_writable_backref(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        parent.children = parent.children[:4]
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 4)

    def test_nullable_relationship(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=0)
        child.parent = None
        self.session.flush()
        self.session.clear()

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 4)

        child = self.Child.query.get(_id=0)
        self.assertEqual(child.parent, None)
        self.assertEqual(child.parent_id, None)

    def test_nullable_foreignid(self):
        parent = self.Parent(_id=1)
        children = [ self.Child(_id=i, parent_id=1) for i in range(5) ]
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=0)
        child.parent_id = None
        self.session.flush()
        self.session.clear()

        child = self.Child.query.get(_id=0)
        self.assertEqual(child.parent_id, None)
        self.assertEqual(child.parent, None)

        parent = self.Parent.query.get(_id=1)
        self.assertEqual(len(parent.children), 4)
class TestBasicMapping(TestCase):

    def setUp(self):
        self.datastore = create_datastore('mim:///test_db')
        self.session = ODMSession(bind=self.datastore)
        class Basic(MappedClass):
            class __mongometa__:
                name='basic'
                session = self.session
            _id = FieldProperty(S.ObjectId)
            a = FieldProperty(int)
            b = FieldProperty([int])
            c = FieldProperty(dict(
                    d=int, e=int))
            d = FieldPropertyWithMissingNone(str, if_missing=S.Missing)
            e = FieldProperty(str, if_missing=S.Missing)
        Mapper.compile_all()
        self.Basic = Basic
        self.session.remove(self.Basic)

    def tearDown(self):
        self.session.clear()
        self.datastore.conn.drop_all()

    def test_repr(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        repr(self.session)

    def test_create(self):
        doc = self.Basic()
        assert state(doc).status == 'new'
        self.session.flush()
        assert state(doc).status == 'clean'
        doc.a = 5
        assert state(doc).status == 'dirty'
        self.session.flush()
        assert state(doc).status == 'clean'
        c = doc.c
        c.e = 5
        assert state(doc).status == 'dirty'
        assert repr(state(doc)).startswith('<ObjectState')

    def test_mapped_object(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.assertEqual(doc.a, doc['a'])
        self.assertEqual(doc.d, None)
        self.assertRaises(AttributeError, getattr, doc, 'e')
        self.assertRaises(AttributeError, getattr, doc, 'foo')
        self.assertRaises(KeyError, doc.__getitem__, 'foo')

        doc['d'] = 'test'
        self.assertEqual(doc.d, doc['d'])
        doc['e'] = 'test'
        self.assertEqual(doc.e, doc['e'])
        del doc.d
        self.assertEqual(doc.d, None)
        del doc.e
        self.assertRaises(AttributeError, getattr, doc, 'e')

        doc['a'] = 5
        self.assertEqual(doc.a, doc['a'])
        self.assertEqual(doc.a, 5)
        self.assert_('a' in doc)
        doc.delete()

    def test_mapper(self):
        m = mapper(self.Basic)
        self.assertEqual(repr(m), '<Mapper Basic:basic>')
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        self.session.remove(self.Basic, {})
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 0)

    def test_query(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 1)
        doc.a = 5
        self.session.flush()
        q = self.Basic.query.find(dict(a=1))
        self.assertEqual(q.count(), 0)
        self.assertEqual(doc.query.find(dict(a=1)).count(), 0)
        doc = self.Basic.query.get(a=5)
        self.assert_(doc is not None)
        self.Basic.query.remove({})
        self.assertEqual(self.Basic.query.find().count(), 0)

    def test_delete(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        doc.delete()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 0)
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        q = self.Basic.query.find()
        self.assertEqual(q.count(), 1)

    def test_imap(self):
        doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
        self.session.flush()
        doc1 = self.Basic.query.get(_id=doc._id)
        self.assert_(doc is doc1)
        self.session.expunge(doc)
        doc1 = self.Basic.query.get(_id=doc._id)
        self.assert_(doc is not doc1)
        self.session.expunge(doc)
        self.session.expunge(doc)
        self.session.expunge(doc)