~justin-fathomdb/nova/justinsb-openstack-api-volumes

« back to all changes in this revision

Viewing changes to vendor/Twisted-10.0.0/twisted/test/test_persisted.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
 
3
# See LICENSE for details.
 
4
 
 
5
 
 
6
# System Imports
 
7
import sys
 
8
 
 
9
from twisted.trial import unittest
 
10
 
 
11
try:
 
12
    import cPickle as pickle
 
13
except ImportError:
 
14
    import pickle
 
15
 
 
16
try:
 
17
    import cStringIO as StringIO
 
18
except ImportError:
 
19
    import StringIO
 
20
 
 
21
# Twisted Imports
 
22
from twisted.persisted import styles, aot, crefutil
 
23
 
 
24
 
 
25
class VersionTestCase(unittest.TestCase):
 
26
    def testNullVersionUpgrade(self):
 
27
        global NullVersioned
 
28
        class NullVersioned:
 
29
            ok = 0
 
30
        pkcl = pickle.dumps(NullVersioned())
 
31
        class NullVersioned(styles.Versioned):
 
32
            persistenceVersion = 1
 
33
            def upgradeToVersion1(self):
 
34
                self.ok = 1
 
35
        mnv = pickle.loads(pkcl)
 
36
        styles.doUpgrade()
 
37
        assert mnv.ok, "initial upgrade not run!"
 
38
 
 
39
    def testVersionUpgrade(self):
 
40
        global MyVersioned
 
41
        class MyVersioned(styles.Versioned):
 
42
            persistenceVersion = 2
 
43
            persistenceForgets = ['garbagedata']
 
44
            v3 = 0
 
45
            v4 = 0
 
46
 
 
47
            def __init__(self):
 
48
                self.somedata = 'xxx'
 
49
                self.garbagedata = lambda q: 'cant persist'
 
50
 
 
51
            def upgradeToVersion3(self):
 
52
                self.v3 += 1
 
53
 
 
54
            def upgradeToVersion4(self):
 
55
                self.v4 += 1
 
56
        mv = MyVersioned()
 
57
        assert not (mv.v3 or mv.v4), "hasn't been upgraded yet"
 
58
        pickl = pickle.dumps(mv)
 
59
        MyVersioned.persistenceVersion = 4
 
60
        obj = pickle.loads(pickl)
 
61
        styles.doUpgrade()
 
62
        assert obj.v3, "didn't do version 3 upgrade"
 
63
        assert obj.v4, "didn't do version 4 upgrade"
 
64
        pickl = pickle.dumps(obj)
 
65
        obj = pickle.loads(pickl)
 
66
        styles.doUpgrade()
 
67
        assert obj.v3 == 1, "upgraded unnecessarily"
 
68
        assert obj.v4 == 1, "upgraded unnecessarily"
 
69
    
 
70
    def testNonIdentityHash(self):
 
71
        global ClassWithCustomHash
 
72
        class ClassWithCustomHash(styles.Versioned):
 
73
            def __init__(self, unique, hash):
 
74
                self.unique = unique
 
75
                self.hash = hash
 
76
            def __hash__(self):
 
77
                return self.hash
 
78
        
 
79
        v1 = ClassWithCustomHash('v1', 0)
 
80
        v2 = ClassWithCustomHash('v2', 0)
 
81
 
 
82
        pkl = pickle.dumps((v1, v2))
 
83
        del v1, v2
 
84
        ClassWithCustomHash.persistenceVersion = 1
 
85
        ClassWithCustomHash.upgradeToVersion1 = lambda self: setattr(self, 'upgraded', True)
 
86
        v1, v2 = pickle.loads(pkl)
 
87
        styles.doUpgrade()
 
88
        self.assertEquals(v1.unique, 'v1')
 
89
        self.assertEquals(v2.unique, 'v2')
 
90
        self.failUnless(v1.upgraded)
 
91
        self.failUnless(v2.upgraded)
 
92
    
 
93
    def testUpgradeDeserializesObjectsRequiringUpgrade(self):
 
94
        global ToyClassA, ToyClassB
 
95
        class ToyClassA(styles.Versioned):
 
96
            pass
 
97
        class ToyClassB(styles.Versioned):
 
98
            pass
 
99
        x = ToyClassA()
 
100
        y = ToyClassB()
 
101
        pklA, pklB = pickle.dumps(x), pickle.dumps(y)
 
102
        del x, y
 
103
        ToyClassA.persistenceVersion = 1
 
104
        def upgradeToVersion1(self):
 
105
            self.y = pickle.loads(pklB)
 
106
            styles.doUpgrade()
 
107
        ToyClassA.upgradeToVersion1 = upgradeToVersion1
 
108
        ToyClassB.persistenceVersion = 1
 
109
        ToyClassB.upgradeToVersion1 = lambda self: setattr(self, 'upgraded', True)
 
110
 
 
111
        x = pickle.loads(pklA)
 
112
        styles.doUpgrade()
 
113
        self.failUnless(x.y.upgraded)
 
114
 
 
115
class MyEphemeral(styles.Ephemeral):
 
116
 
 
117
    def __init__(self, x):
 
118
        self.x = x
 
119
 
 
120
 
 
121
class EphemeralTestCase(unittest.TestCase):
 
122
 
 
123
    def testEphemeral(self):
 
124
        o = MyEphemeral(3)
 
125
        self.assertEquals(o.__class__, MyEphemeral)
 
126
        self.assertEquals(o.x, 3)
 
127
        
 
128
        pickl = pickle.dumps(o)
 
129
        o = pickle.loads(pickl)
 
130
        
 
131
        self.assertEquals(o.__class__, styles.Ephemeral)
 
132
        self.assert_(not hasattr(o, 'x'))
 
133
 
 
134
 
 
135
class Pickleable:
 
136
 
 
137
    def __init__(self, x):
 
138
        self.x = x
 
139
    
 
140
    def getX(self):
 
141
        return self.x
 
142
 
 
143
class A:
 
144
    """
 
145
    dummy class
 
146
    """
 
147
    def amethod(self):
 
148
        pass
 
149
 
 
150
class B:
 
151
    """
 
152
    dummy class
 
153
    """
 
154
    def bmethod(self):
 
155
        pass
 
156
 
 
157
def funktion():
 
158
    pass
 
159
 
 
160
class PicklingTestCase(unittest.TestCase):
 
161
    """Test pickling of extra object types."""
 
162
    
 
163
    def testModule(self):
 
164
        pickl = pickle.dumps(styles)
 
165
        o = pickle.loads(pickl)
 
166
        self.assertEquals(o, styles)
 
167
    
 
168
    def testClassMethod(self):
 
169
        pickl = pickle.dumps(Pickleable.getX)
 
170
        o = pickle.loads(pickl)
 
171
        self.assertEquals(o, Pickleable.getX)
 
172
    
 
173
    def testInstanceMethod(self):
 
174
        obj = Pickleable(4)
 
175
        pickl = pickle.dumps(obj.getX)
 
176
        o = pickle.loads(pickl)
 
177
        self.assertEquals(o(), 4)
 
178
        self.assertEquals(type(o), type(obj.getX))
 
179
    
 
180
    def testStringIO(self):
 
181
        f = StringIO.StringIO()
 
182
        f.write("abc")
 
183
        pickl = pickle.dumps(f)
 
184
        o = pickle.loads(pickl)
 
185
        self.assertEquals(type(o), type(f))
 
186
        self.assertEquals(f.getvalue(), "abc")
 
187
 
 
188
 
 
189
class EvilSourceror:
 
190
    def __init__(self, x):
 
191
        self.a = self
 
192
        self.a.b = self
 
193
        self.a.b.c = x
 
194
 
 
195
class NonDictState:
 
196
    def __getstate__(self):
 
197
        return self.state
 
198
    def __setstate__(self, state):
 
199
        self.state = state
 
200
 
 
201
class AOTTestCase(unittest.TestCase):
 
202
    def testSimpleTypes(self):
 
203
        obj = (1, 2.0, 3j, True, slice(1, 2, 3), 'hello', u'world', sys.maxint + 1, None, Ellipsis)
 
204
        rtObj = aot.unjellyFromSource(aot.jellyToSource(obj))
 
205
        self.assertEquals(obj, rtObj)
 
206
 
 
207
    def testMethodSelfIdentity(self):
 
208
        a = A()
 
209
        b = B()
 
210
        a.bmethod = b.bmethod
 
211
        b.a = a
 
212
        im_ = aot.unjellyFromSource(aot.jellyToSource(b)).a.bmethod
 
213
        self.assertEquals(im_.im_class, im_.im_self.__class__)
 
214
 
 
215
 
 
216
    def test_methodNotSelfIdentity(self):
 
217
        """
 
218
        If a class change after an instance has been created,
 
219
        L{aot.unjellyFromSource} shoud raise a C{TypeError} when trying to
 
220
        unjelly the instance.
 
221
        """
 
222
        a = A()
 
223
        b = B()
 
224
        a.bmethod = b.bmethod
 
225
        b.a = a
 
226
        savedbmethod = B.bmethod
 
227
        del B.bmethod
 
228
        try:
 
229
            self.assertRaises(TypeError, aot.unjellyFromSource,
 
230
                              aot.jellyToSource(b))
 
231
        finally:
 
232
            B.bmethod = savedbmethod
 
233
 
 
234
 
 
235
    def test_unsupportedType(self):
 
236
        """
 
237
        L{aot.jellyToSource} should raise a C{TypeError} when trying to jelly
 
238
        an unknown type.
 
239
        """
 
240
        try:
 
241
            set
 
242
        except:
 
243
            from sets import Set as set
 
244
        self.assertRaises(TypeError, aot.jellyToSource, set())
 
245
 
 
246
 
 
247
    def testBasicIdentity(self):
 
248
        # Anyone wanting to make this datastructure more complex, and thus this
 
249
        # test more comprehensive, is welcome to do so.
 
250
        aj = aot.AOTJellier().jellyToAO
 
251
        d = {'hello': 'world', "method": aj}
 
252
        l = [1, 2, 3,
 
253
             "he\tllo\n\n\"x world!",
 
254
             u"goodbye \n\t\u1010 world!",
 
255
             1, 1.0, 100 ** 100l, unittest, aot.AOTJellier, d,
 
256
             funktion
 
257
             ]
 
258
        t = tuple(l)
 
259
        l.append(l)
 
260
        l.append(t)
 
261
        l.append(t)
 
262
        uj = aot.unjellyFromSource(aot.jellyToSource([l, l]))
 
263
        assert uj[0] is uj[1]
 
264
        assert uj[1][0:5] == l[0:5]
 
265
 
 
266
 
 
267
    def testNonDictState(self):
 
268
        a = NonDictState()
 
269
        a.state = "meringue!"
 
270
        assert aot.unjellyFromSource(aot.jellyToSource(a)).state == a.state
 
271
 
 
272
    def testCopyReg(self):
 
273
        s = "foo_bar"
 
274
        sio = StringIO.StringIO()
 
275
        sio.write(s)
 
276
        uj = aot.unjellyFromSource(aot.jellyToSource(sio))
 
277
        # print repr(uj.__dict__)
 
278
        assert uj.getvalue() == s
 
279
 
 
280
    def testFunkyReferences(self):
 
281
        o = EvilSourceror(EvilSourceror([]))
 
282
        j1 = aot.jellyToAOT(o)
 
283
        oj = aot.unjellyFromAOT(j1)
 
284
 
 
285
        assert oj.a is oj
 
286
        assert oj.a.b is oj.b
 
287
        assert oj.c is not oj.c.c
 
288
 
 
289
 
 
290
class CrefUtilTestCase(unittest.TestCase):
 
291
    """
 
292
    Tests for L{crefutil}.
 
293
    """
 
294
 
 
295
    def test_dictUnknownKey(self):
 
296
        """
 
297
        L{crefutil._DictKeyAndValue} only support keys C{0} and C{1}.
 
298
        """
 
299
        d = crefutil._DictKeyAndValue({})
 
300
        self.assertRaises(RuntimeError, d.__setitem__, 2, 3)
 
301
 
 
302
 
 
303
    def test_deferSetMultipleTimes(self):
 
304
        """
 
305
        L{crefutil._Defer} can be assigned a key only one time.
 
306
        """
 
307
        d = crefutil._Defer()
 
308
        d[0] = 1
 
309
        self.assertRaises(RuntimeError, d.__setitem__, 0, 1)
 
310
 
 
311
 
 
312
 
 
313
testCases = [VersionTestCase, EphemeralTestCase, PicklingTestCase]
 
314