Ticket #4935: test_jelly.py

File test_jelly.py, 2.1 KB (added by speth, 3 years ago)

Test case demonstrating the failure

Line 
1#!/usr/bin/python
2
3from twisted.spread import jelly
4import types
5from new import instance
6
7_NO_STATE = jelly._NO_STATE
8
9def monkeyPatchedNewInstance(cls, state=_NO_STATE):
10    """
11    Make a new instance of a class without calling its __init__ method.
12    Supports both new- and old-style classes.
13
14    @param state: A C{dict} used to update C{inst.__dict__} or C{_NO_STATE}
15        to skip this part of initialization.
16
17    @return: A new instance of C{cls}.
18    """
19    if not isinstance(cls, types.ClassType):
20        # new-style
21        inst = cls.__new__(cls)
22
23        if state is not _NO_STATE:
24            for k,v in inst.__dict__.iteritems():
25                if k not in state:
26                    state[k] = v
27            inst.__dict__ = state
28
29    else:
30        if state is not _NO_STATE:
31            inst = instance(cls, state)
32        else:
33            inst = instance(cls)
34    return inst
35
36## Uncomment the following line to demonstrate the patch
37#jelly._newInstance = monkeyPatchedNewInstance
38
39class Foo(object): pass
40class Bar(object): pass
41class Baz: pass
42class Qux: pass
43
44def test0():
45    # dict / dict
46    x = {}
47    x['bar'] = {}
48    x['bar']['foo'] = x
49
50    J = jelly.jelly(x)
51    y = jelly.unjelly(J)
52
53    return y['bar']['foo'] == y
54
55def test1():
56    # Object / Object
57    x = Foo()
58    x.bar = Bar()
59    x.bar.foo = x
60
61    J = jelly.jelly(x)
62    y = jelly.unjelly(J)
63    return y.bar.foo == y
64
65def test2():
66    # Object / dict
67    x = Foo()
68    x.dict = {}
69    x.dict['foo'] = x
70
71    J = jelly.jelly(x)
72    y = jelly.unjelly(J)
73    return y.dict['foo'] == y
74
75def test3():
76    # dict / object
77    x = {}
78    x['foo'] = Foo()
79    x['foo'].dict = x
80
81    J = jelly.jelly(x)
82    y = jelly.unjelly(J)
83    return y['foo'].dict == y
84
85def test4():
86    # old-style class / old-style class
87
88    x = Baz()
89    x.qux = Qux()
90    x.qux.baz = x
91
92    J = jelly.jelly(x)
93    y = jelly.unjelly(J)
94
95    return y.qux.baz == y
96
97if __name__ == '__main__':
98    # All of these tests should return True
99    print test0()
100    print test1() # Fails
101    print test2()
102    print test3() # Fails
103    print test4()