⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 associationproxy.py

📁 SQLAlchemy. 经典的Python ORM框架。学习必看。
💻 PY
📖 第 1 页 / 共 2 页
字号:
        self.assert_(p1.children == set(['a','b','c']))        try:            p1.children.remove('d')            self.fail()        except KeyError:            pass        self.assert_(len(p1.children) == 3)        p1.children.discard('d')        self.assert_(len(p1.children) == 3)        p1 = self.roundtrip(p1)        self.assert_(len(p1.children) == 3)        popped = p1.children.pop()        self.assert_(len(p1.children) == 2)        self.assert_(popped not in p1.children)        p1 = self.roundtrip(p1)        self.assert_(len(p1.children) == 2)        self.assert_(popped not in p1.children)        p1.children = ['a','b','c']        p1 = self.roundtrip(p1)        self.assert_(p1.children == set(['a','b','c']))        p1.children.discard('b')        p1 = self.roundtrip(p1)        self.assert_(p1.children == set(['a', 'c']))        p1.children.remove('a')        p1 = self.roundtrip(p1)        self.assert_(p1.children == set(['c']))        p1._children = set()        self.assert_(len(p1.children) == 0)        try:            p1._children = []            self.assert_(False)        except TypeError:            self.assert_(True)        try:            p1._children = None            self.assert_(False)        except TypeError:            self.assert_(True)        self.assertRaises(TypeError, set, [p1.children])    def test_set_comparisons(self):        Parent, Child = self.Parent, self.Child        p1 = Parent('P1')        p1.children = ['a','b','c']        control = set(['a','b','c'])        for other in (set(['a','b','c']), set(['a','b','c','d']),                      set(['a']), set(['a','b']),                      set(['c','d']), set(['e', 'f', 'g']),                      set()):            self.assertEqual(p1.children.union(other),                             control.union(other))            self.assertEqual(p1.children.difference(other),                             control.difference(other))            self.assertEqual((p1.children - other),                             (control - other))            self.assertEqual(p1.children.intersection(other),                             control.intersection(other))            self.assertEqual(p1.children.symmetric_difference(other),                             control.symmetric_difference(other))            self.assertEqual(p1.children.issubset(other),                             control.issubset(other))            self.assertEqual(p1.children.issuperset(other),                             control.issuperset(other))            self.assert_((p1.children == other)  ==  (control == other))            self.assert_((p1.children != other)  ==  (control != other))            self.assert_((p1.children < other)   ==  (control < other))            self.assert_((p1.children <= other)  ==  (control <= other))            self.assert_((p1.children > other)   ==  (control > other))            self.assert_((p1.children >= other)  ==  (control >= other))    def test_set_mutation(self):        Parent, Child = self.Parent, self.Child        # mutations        for op in ('update', 'intersection_update',                   'difference_update', 'symmetric_difference_update'):            for base in (['a', 'b', 'c'], []):                for other in (set(['a','b','c']), set(['a','b','c','d']),                              set(['a']), set(['a','b']),                              set(['c','d']), set(['e', 'f', 'g']),                              set()):                    p = Parent('p')                    p.children = base[:]                    control = set(base[:])                    getattr(p.children, op)(other)                    getattr(control, op)(other)                    try:                        self.assert_(p.children == control)                    except:                        print 'Test %s.%s(%s):' % (set(base), op, other)                        print 'want', repr(control)                        print 'got', repr(p.children)                        raise                    p = self.roundtrip(p)                    try:                        self.assert_(p.children == control)                    except:                        print 'Test %s.%s(%s):' % (base, op, other)                        print 'want', repr(control)                        print 'got', repr(p.children)                        raise        # in-place mutations        for op in ('|=', '-=', '&=', '^='):            for base in (['a', 'b', 'c'], []):                for other in (set(['a','b','c']), set(['a','b','c','d']),                              set(['a']), set(['a','b']),                              set(['c','d']), set(['e', 'f', 'g']),                              set()):                    p = Parent('p')                    p.children = base[:]                    control = set(base[:])                    exec "p.children %s other" % op                    exec "control %s other" % op                    try:                        self.assert_(p.children == control)                    except:                        print 'Test %s %s %s:' % (set(base), op, other)                        print 'want', repr(control)                        print 'got', repr(p.children)                        raise                    p = self.roundtrip(p)                    try:                        self.assert_(p.children == control)                    except:                        print 'Test %s %s %s:' % (base, op, other)                        print 'want', repr(control)                        print 'got', repr(p.children)                        raiseclass CustomSetTest(SetTest):    def __init__(self, *args, **kw):        super(CustomSetTest, self).__init__(*args, **kw)        self.collection_class = SetCollectionclass CustomObjectTest(_CollectionOperations):    def __init__(self, *args, **kw):        super(CustomObjectTest, self).__init__(*args, **kw)        self.collection_class = ObjectCollection    def test_basic(self):        Parent, Child = self.Parent, self.Child        p = Parent('p1')        self.assert_(len(list(p.children)) == 0)        p.children.append('child')        self.assert_(len(list(p.children)) == 1)        p = self.roundtrip(p)        self.assert_(len(list(p.children)) == 1)        # We didn't provide an alternate _AssociationList implementation for        # our ObjectCollection, so indexing will fail.        try:            v = p.children[1]            self.fail()        except TypeError:            passclass ScalarTest(TestBase):    def test_scalar_proxy(self):        metadata = MetaData(testing.db)        parents_table = Table('Parent', metadata,                              Column('id', Integer, primary_key=True),                              Column('name', String(128)))        children_table = Table('Children', metadata,                               Column('id', Integer, primary_key=True),                               Column('parent_id', Integer,                                      ForeignKey('Parent.id')),                               Column('foo', String(128)),                               Column('bar', String(128)),                               Column('baz', String(128)))        class Parent(object):            foo = association_proxy('child', 'foo')            bar = association_proxy('child', 'bar',                                    creator=lambda v: Child(bar=v))            baz = association_proxy('child', 'baz',                                    creator=lambda v: Child(baz=v))            def __init__(self, name):                self.name = name        class Child(object):            def __init__(self, **kw):                for attr in kw:                    setattr(self, attr, kw[attr])        mapper(Parent, parents_table, properties={            'child': relation(Child, lazy=False,                              backref='parent', uselist=False)})        mapper(Child, children_table)        metadata.create_all()        session = create_session()        def roundtrip(obj):            if obj not in session:                session.save(obj)            session.flush()            id, type_ = obj.id, type(obj)            session.clear()            return session.query(type_).get(id)        p = Parent('p')        # No child        try:            v = p.foo            self.fail()        except:            pass        p.child = Child(foo='a', bar='b', baz='c')        self.assert_(p.foo == 'a')        self.assert_(p.bar == 'b')        self.assert_(p.baz == 'c')        p.bar = 'x'        self.assert_(p.foo == 'a')        self.assert_(p.bar == 'x')        self.assert_(p.baz == 'c')        p = roundtrip(p)        self.assert_(p.foo == 'a')        self.assert_(p.bar == 'x')        self.assert_(p.baz == 'c')        p.child = None        # No child again        try:            v = p.foo            self.fail()        except:            pass        # Bogus creator for this scalar type        try:            p.foo = 'zzz'            self.fail()        except TypeError:            pass        p.bar = 'yyy'        self.assert_(p.foo is None)        self.assert_(p.bar == 'yyy')        self.assert_(p.baz is None)        del p.child        p = roundtrip(p)        self.assert_(p.child is None)        p.baz = 'xxx'        self.assert_(p.foo is None)        self.assert_(p.bar is None)        self.assert_(p.baz == 'xxx')        p = roundtrip(p)        self.assert_(p.foo is None)        self.assert_(p.bar is None)        self.assert_(p.baz == 'xxx')        # Ensure an immediate __set__ works.        p2 = Parent('p2')        p2.bar = 'quux'class LazyLoadTest(TestBase):    def setUp(self):        metadata = MetaData(testing.db)        parents_table = Table('Parent', metadata,                              Column('id', Integer, primary_key=True),                              Column('name', String(128)))        children_table = Table('Children', metadata,                               Column('id', Integer, primary_key=True),                               Column('parent_id', Integer,                                      ForeignKey('Parent.id')),                               Column('foo', String(128)),                               Column('name', String(128)))        class Parent(object):            children = association_proxy('_children', 'name')            def __init__(self, name):                self.name = name        class Child(object):            def __init__(self, name):                self.name = name        mapper(Child, children_table)        metadata.create_all()        self.metadata = metadata        self.session = create_session()        self.Parent, self.Child = Parent, Child        self.table = parents_table    def tearDown(self):        self.metadata.drop_all()    def roundtrip(self, obj):        self.session.save(obj)        self.session.flush()        id, type_ = obj.id, type(obj)        self.session.clear()        return self.session.query(type_).get(id)    def test_lazy_list(self):        Parent, Child = self.Parent, self.Child        mapper(Parent, self.table, properties={            '_children': relation(Child, lazy=True,                                  collection_class=list)})        p = Parent('p')        p.children = ['a','b','c']        p = self.roundtrip(p)        # Is there a better way to ensure that the association_proxy        # didn't convert a lazy load to an eager load?  This does work though.        self.assert_('_children' not in p.__dict__)        self.assert_(len(p._children) == 3)        self.assert_('_children' in p.__dict__)    def test_eager_list(self):        Parent, Child = self.Parent, self.Child        mapper(Parent, self.table, properties={            '_children': relation(Child, lazy=False,                                  collection_class=list)})        p = Parent('p')        p.children = ['a','b','c']        p = self.roundtrip(p)        self.assert_('_children' in p.__dict__)        self.assert_(len(p._children) == 3)    def test_lazy_scalar(self):        Parent, Child = self.Parent, self.Child        mapper(Parent, self.table, properties={            '_children': relation(Child, lazy=True, uselist=False)})        p = Parent('p')        p.children = 'value'        p = self.roundtrip(p)        self.assert_('_children' not in p.__dict__)        self.assert_(p._children is not None)    def test_eager_scalar(self):        Parent, Child = self.Parent, self.Child        mapper(Parent, self.table, properties={            '_children': relation(Child, lazy=False, uselist=False)})        p = Parent('p')        p.children = 'value'        p = self.roundtrip(p)        self.assert_('_children' in p.__dict__)        self.assert_(p._children is not None)if __name__ == "__main__":    testenv.main()

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -