Debian Codegraph @

Lib/test/picklecommon.py

raw
1 # Classes used for pickle testing.
2 # They are moved to separate file, so they can be loaded
3 # in other Python version for test_xpickle.
4
5 import sys
6
7 class C:
8 def __eq__(self, other):
9 return self.__dict__ == other.__dict__
10
11 # For test_load_classic_instance
12 class D(C):
13 def __init__(self, arg):
14 pass
15
16 class E(C):
17 def __getinitargs__(self):
18 return ()
19
20 import __main__
21 __main__.C = C
22 C.__module__ = "__main__"
23 __main__.D = D
24 D.__module__ = "__main__"
25 __main__.E = E
26 E.__module__ = "__main__"
27
28 # Simple mutable object.
29 class Object(object):
30 pass
31
32 # Hashable immutable key object containing unheshable mutable data.
33 class K:
34 def __init__(self, value):
35 self.value = value
36
37 def __reduce__(self):
38 # Shouldn't support the recursion itself
39 return K, (self.value,)
40
41 class WithSlots(object):
42 __slots__ = ('a', 'b')
43
44 class WithSlotsSubclass(WithSlots):
45 __slots__ = ('c',)
46
47 class WithSlotsAndDict(object):
48 __slots__ = ('a', '__dict__')
49
50 class WithPrivateAttrs(object):
51 def __init__(self, a):
52 self.__private = a
53 def get(self):
54 return self.__private
55
56 class WithPrivateAttrsSubclass(WithPrivateAttrs):
57 def __init__(self, a, b):
58 super().__init__(a)
59 self.__private = b
60 def get2(self):
61 return self.__private
62
63 class WithPrivateSlots(object):
64 __slots__ = ('__private',)
65 def __init__(self, a):
66 self.__private = a
67 def get(self):
68 return self.__private
69
70 class WithPrivateSlotsSubclass(WithPrivateSlots):
71 __slots__ = ('__private',)
72 def __init__(self, a, b):
73 super().__init__(a)
74 self.__private = b
75 def get2(self):
76 return self.__private
77
78 # For test_misc
79 class myint(int):
80 def __init__(self, x):
81 self.str = str(x)
82
83 # For test_misc and test_getinitargs
84 class initarg(C):
85
86 def __init__(self, a, b):
87 self.a = a
88 self.b = b
89
90 def __getinitargs__(self):
91 return self.a, self.b
92
93 # For test_metaclass
94 class metaclass(type):
95 pass
96
97 if sys.version_info >= (3,):
98 # Syntax not compatible with Python 2
99 exec('''
100 class use_metaclass(object, metaclass=metaclass):
101 pass
102 ''')
103 else:
104 class use_metaclass(object):
105 __metaclass__ = metaclass
106
107
108 # Test classes for reduce_ex
109
110 class R:
111 def __init__(self, reduce=None):
112 self.reduce = reduce
113 def __reduce__(self, proto):
114 return self.reduce
115
116 class REX:
117 def __init__(self, reduce_ex=None):
118 self.reduce_ex = reduce_ex
119 def __reduce_ex__(self, proto):
120 return self.reduce_ex
121
122 class REX_one(object):
123 """No __reduce_ex__ here, but inheriting it from object"""
124 _reduce_called = 0
125 def __reduce__(self):
126 self._reduce_called = 1
127 return REX_one, ()
128
129 class REX_two(object):
130 """No __reduce__ here, but inheriting it from object"""
131 _proto = None
132 def __reduce_ex__(self, proto):
133 self._proto = proto
134 return REX_two, ()
135
136 class REX_three(object):
137 _proto = None
138 def __reduce_ex__(self, proto):
139 self._proto = proto
140 return REX_two, ()
141 def __reduce__(self):
142 raise AssertionError("This __reduce__ shouldn't be called")
143
144 class REX_four(object):
145 """Calling base class method should succeed"""
146 _proto = None
147 def __reduce_ex__(self, proto):
148 self._proto = proto
149 return object.__reduce_ex__(self, proto)
150
151 class REX_five(object):
152 """This one used to fail with infinite recursion"""
153 _reduce_called = 0
154 def __reduce__(self):
155 self._reduce_called = 1
156 return object.__reduce__(self)
157
158 class REX_six(object):
159 """This class is used to check the 4th argument (list iterator) of
160 the reduce protocol.
161 """
162 def __init__(self, items=None):
163 self.items = items if items is not None else []
164 def __eq__(self, other):
165 return type(self) is type(other) and self.items == other.items
166 def append(self, item):
167 self.items.append(item)
168 def __reduce__(self):
169 return type(self), (), None, iter(self.items), None
170
171 class REX_seven(object):
172 """This class is used to check the 5th argument (dict iterator) of
173 the reduce protocol.
174 """
175 def __init__(self, table=None):
176 self.table = table if table is not None else {}
177 def __eq__(self, other):
178 return type(self) is type(other) and self.table == other.table
179 def __setitem__(self, key, value):
180 self.table[key] = value
181 def __reduce__(self):
182 return type(self), (), None, None, iter(self.table.items())
183
184 class REX_state(object):
185 """This class is used to check the 3th argument (state) of
186 the reduce protocol.
187 """
188 def __init__(self, state=None):
189 self.state = state
190 def __eq__(self, other):
191 return type(self) is type(other) and self.state == other.state
192 def __setstate__(self, state):
193 self.state = state
194 def __reduce__(self):
195 return type(self), (), self.state
196
197 # For test_reduce_ex_None
198 class REX_None:
199 """ Setting __reduce_ex__ to None should fail """
200 __reduce_ex__ = None
201
202 # For test_reduce_None
203 class R_None:
204 """ Setting __reduce__ to None should fail """
205 __reduce__ = None
206
207 # For test_pickle_setstate_None
208 class C_None_setstate:
209 """ Setting __setstate__ to None should fail """
210 def __getstate__(self):
211 return 1
212
213 __setstate__ = None
214
215
216 # Test classes for newobj
217
218 # For test_newobj_generic and test_newobj_proxies
219
220 class MyInt(int):
221 sample = 1
222
223 if sys.version_info >= (3,):
224 class MyLong(int):
225 sample = 1
226 else:
227 class MyLong(long):
228 sample = long(1)
229
230 class MyFloat(float):
231 sample = 1.0
232
233 class MyComplex(complex):
234 sample = 1.0 + 0.0j
235
236 class MyStr(str):
237 sample = "hello"
238
239 if sys.version_info >= (3,):
240 class MyUnicode(str):
241 sample = "hello \u1234"
242 else:
243 class MyUnicode(unicode):
244 sample = unicode(r"hello \u1234", "raw-unicode-escape")
245
246 class MyTuple(tuple):
247 sample = (1, 2, 3)
248
249 class MyList(list):
250 sample = [1, 2, 3]
251
252 class MyDict(dict):
253 sample = {"a": 1, "b": 2}
254
255 class MySet(set):
256 sample = {"a", "b"}
257
258 class MyFrozenSet(frozenset):
259 sample = frozenset({"a", "b"})
260
261 myclasses = [MyInt, MyLong, MyFloat,
262 MyComplex,
263 MyStr, MyUnicode,
264 MyTuple, MyList, MyDict, MySet, MyFrozenSet]
265
266 # For test_newobj_overridden_new
267 class MyIntWithNew(int):
268 def __new__(cls, value):
269 raise AssertionError
270
271 class MyIntWithNew2(MyIntWithNew):
272 __new__ = int.__new__
273
274
275 # For test_newobj_list_slots
276 class SlotList(MyList):
277 __slots__ = ["foo"]
278
279 # Ruff "redefined while unused" false positive here due to `global` variables
280 # being assigned (and then restored) from within test methods earlier in the file
281 class SimpleNewObj(int): # noqa: F811
282 def __init__(self, *args, **kwargs):
283 # raise an error, to make sure this isn't called
284 raise TypeError("SimpleNewObj.__init__() didn't expect to get called")
285 def __eq__(self, other):
286 return int(self) == int(other) and self.__dict__ == other.__dict__
287
288 class ComplexNewObj(SimpleNewObj):
289 def __getnewargs__(self):
290 return ('%X' % self, 16)
291
292 class ComplexNewObjEx(SimpleNewObj):
293 def __getnewargs_ex__(self):
294 return ('%X' % self,), {'base': 16}
295
296
297 class ZeroCopyBytes(bytes):
298 readonly = True
299 c_contiguous = True
300 f_contiguous = True
301 zero_copy_reconstruct = True
302
303 def __reduce_ex__(self, protocol):
304 if protocol >= 5:
305 import pickle
306 return type(self)._reconstruct, (pickle.PickleBuffer(self),), None
307 else:
308 return type(self)._reconstruct, (bytes(self),)
309
310 def __repr__(self):
311 return "{}({!r})".format(self.__class__.__name__, bytes(self))
312
313 __str__ = __repr__
314
315 @classmethod
316 def _reconstruct(cls, obj):
317 with memoryview(obj) as m:
318 obj = m.obj
319 if type(obj) is cls:
320 # Zero-copy
321 return obj
322 else:
323 return cls(obj)
324
325
326 class ZeroCopyBytearray(bytearray):
327 readonly = False
328 c_contiguous = True
329 f_contiguous = True
330 zero_copy_reconstruct = True
331
332 def __reduce_ex__(self, protocol):
333 if protocol >= 5:
334 import pickle
335 return type(self)._reconstruct, (pickle.PickleBuffer(self),), None
336 else:
337 return type(self)._reconstruct, (bytes(self),)
338
339 def __repr__(self):
340 return "{}({!r})".format(self.__class__.__name__, bytes(self))
341
342 __str__ = __repr__
343
344 @classmethod
345 def _reconstruct(cls, obj):
346 with memoryview(obj) as m:
347 obj = m.obj
348 if type(obj) is cls:
349 # Zero-copy
350 return obj
351 else:
352 return cls(obj)
353
354
355 # For test_nested_names
356 class Nested:
357 class A:
358 class B:
359 class C:
360 pass
361
362 # For test_py_methods
363 class PyMethodsTest:
364 @staticmethod
365 def cheese():
366 return "cheese"
367 @classmethod
368 def wine(cls):
369 assert cls is PyMethodsTest
370 return "wine"
371 def biscuits(self):
372 assert isinstance(self, PyMethodsTest)
373 return "biscuits"
374 class Nested:
375 "Nested class"
376 @staticmethod
377 def ketchup():
378 return "ketchup"
379 @classmethod
380 def maple(cls):
381 assert cls is PyMethodsTest.Nested
382 return "maple"
383 def pie(self):
384 assert isinstance(self, PyMethodsTest.Nested)
385 return "pie"
386
387 # For test_c_methods
388 class Subclass(tuple):
389 class Nested(str):
390 pass