summaryrefslogtreecommitdiff
path: root/test/ext/test_mutable.py
blob: 3e7a23b8db053374d5d4ed0d7b40f7214bf7009b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
from sqlalchemy import Integer
from sqlalchemy.types import PickleType, TypeDecorator, VARCHAR
from sqlalchemy.orm import mapper, Session, composite
from sqlalchemy.orm.mapper import Mapper
from sqlalchemy.orm.instrumentation import ClassManager
from test.lib.schema import Table, Column
from test.lib.testing import eq_
from test.lib import testing
from test.orm import _base
import sys

class _MutableDictTestBase(object):
    @classmethod
    def _type_fixture(cls):
        from sqlalchemy.ext.mutable import Mutable
        
        # needed for pickle support
        global MutationDict
        
        class MutationDict(Mutable, dict):
            @classmethod
            def coerce(cls, key, value):
                if not isinstance(value, MutationDict):
                    if isinstance(value, dict):
                        return MutationDict(value)
                    return Mutable.coerce(key, value)
                else:
                    return value
        
            def __getstate__(self):
                return dict(self)
        
            def __setstate__(self, dict):
                self.update(dict)
            
            def __setitem__(self, key, value):
                dict.__setitem__(self, key, value)
                self.change()
    
            def __delitem__(self, key):
                dict.__delitem__(self, key)
                self.change()
        return MutationDict
    
    @testing.resolve_artifact_names
    def setup_mappers(cls):
        class Foo(_base.BasicEntity):
            pass
        
        mapper(Foo, foo)

    def teardown(self):
        # clear out mapper events
        Mapper.dispatch._clear()
        ClassManager.dispatch._clear()
        super(_MutableDictTestBase, self).teardown()
        
    @testing.resolve_artifact_names
    def test_in_place_mutation(self):
        sess = Session()

        f1 = Foo(data={'a':'b'})
        sess.add(f1)
        sess.commit()

        f1.data['a'] = 'c'
        sess.commit()

        eq_(f1.data, {'a':'c'})

    @testing.resolve_artifact_names
    def _test_non_mutable(self):
        sess = Session()

        f1 = Foo(non_mutable_data={'a':'b'})
        sess.add(f1)
        sess.commit()

        f1.non_mutable_data['a'] = 'c'
        sess.commit()

        eq_(f1.non_mutable_data, {'a':'b'})

class MutableWithScalarPickleTest(_MutableDictTestBase, _base.MappedTest):
    @classmethod
    def define_tables(cls, metadata):
        MutationDict = cls._type_fixture()
        
        Table('foo', metadata,
            Column('id', Integer, primary_key=True, test_needs_pk=True),
            Column('data', MutationDict.as_mutable(PickleType)),
            Column('non_mutable_data', PickleType)
        )
    
    def test_non_mutable(self):
        self._test_non_mutable()
        
class MutableWithScalarJSONTest(_MutableDictTestBase, _base.MappedTest):
    # json introduced in 2.6
    __skip_if__ = lambda : sys.version_info < (2, 6),

    @classmethod
    def define_tables(cls, metadata):
        import json

        class JSONEncodedDict(TypeDecorator):
            impl = VARCHAR

            def process_bind_param(self, value, dialect):
                if value is not None:
                    value = json.dumps(value)

                return value

            def process_result_value(self, value, dialect):
                if value is not None:
                    value = json.loads(value)
                return value
        
        MutationDict = cls._type_fixture()

        Table('foo', metadata,
            Column('id', Integer, primary_key=True, test_needs_pk=True),
            Column('data', MutationDict.as_mutable(JSONEncodedDict)),
            Column('non_mutable_data', JSONEncodedDict)
        )

    def test_non_mutable(self):
        self._test_non_mutable()

class MutableAssociationScalarPickleTest(_MutableDictTestBase, _base.MappedTest):
    @classmethod
    def define_tables(cls, metadata):
        MutationDict = cls._type_fixture()
        MutationDict.associate_with(PickleType)
        
        Table('foo', metadata,
            Column('id', Integer, primary_key=True, test_needs_pk=True),
            Column('data', PickleType)
        )

class MutableAssociationScalarJSONTest(_MutableDictTestBase, _base.MappedTest):
    # json introduced in 2.6
    __skip_if__ = lambda : sys.version_info < (2, 6),

    @classmethod
    def define_tables(cls, metadata):
        import json

        class JSONEncodedDict(TypeDecorator):
            impl = VARCHAR

            def process_bind_param(self, value, dialect):
                if value is not None:
                    value = json.dumps(value)

                return value

            def process_result_value(self, value, dialect):
                if value is not None:
                    value = json.loads(value)
                return value

        MutationDict = cls._type_fixture()
        MutationDict.associate_with(JSONEncodedDict)
        
        Table('foo', metadata,
            Column('id', Integer, primary_key=True, test_needs_pk=True),
            Column('data', JSONEncodedDict)
        )
        
class MutableCompositesTest(_base.MappedTest):
    @classmethod
    def define_tables(cls, metadata):
        Table('foo', metadata,
            Column('id', Integer, primary_key=True, test_needs_pk=True),
            Column('x', Integer),
            Column('y', Integer)
        )

    def teardown(self):
        # clear out mapper events
        Mapper.dispatch._clear()
        ClassManager.dispatch._clear()
        super(MutableCompositesTest, self).teardown()

    @classmethod
    def _type_fixture(cls):
        
        from sqlalchemy.ext.mutable import Mutable
        from sqlalchemy.ext.mutable import MutableComposite
        
        global Point
        
        class Point(MutableComposite):
            def __init__(self, x, y):
                self.x = x
                self.y = y

            def __setattr__(self, key, value):
                object.__setattr__(self, key, value)
                self.change()
        
            def __composite_values__(self):
                return self.x, self.y
            
            def __eq__(self, other):
                return isinstance(other, Point) and \
                    other.x == self.x and \
                    other.y == self.y
        return Point
        
    @classmethod
    @testing.resolve_artifact_names
    def setup_mappers(cls):
        Point = cls._type_fixture()
        
        class Foo(_base.BasicEntity):
            pass
            
        mapper(Foo, foo, properties={
            'data':composite(Point, foo.c.x, foo.c.y)
        })

    @testing.resolve_artifact_names
    def test_in_place_mutation(self):
        sess = Session()
        d = Point(3, 4)
        f1 = Foo(data=d)
        sess.add(f1)
        sess.commit()

        f1.data.y = 5
        sess.commit()

        eq_(f1.data, Point(3, 5))