pickletester.py 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999
  1. import builtins
  2. import collections
  3. import copyreg
  4. import dbm
  5. import io
  6. import functools
  7. import os
  8. import math
  9. import pickle
  10. import pickletools
  11. import shutil
  12. import struct
  13. import sys
  14. import threading
  15. import types
  16. import unittest
  17. import weakref
  18. from textwrap import dedent
  19. from http.cookies import SimpleCookie
  20. try:
  21. import _testbuffer
  22. except ImportError:
  23. _testbuffer = None
  24. from test import support
  25. from test.support import os_helper
  26. from test.support import (
  27. TestFailed, run_with_locale, no_tracing,
  28. _2G, _4G, bigmemtest
  29. )
  30. from test.support.import_helper import forget
  31. from test.support.os_helper import TESTFN
  32. from test.support import threading_helper
  33. from test.support.warnings_helper import save_restore_warnings_filters
  34. from pickle import bytes_types
  35. # bpo-41003: Save/restore warnings filters to leave them unchanged.
  36. # Ignore filters installed by numpy.
  37. try:
  38. with save_restore_warnings_filters():
  39. import numpy as np
  40. except ImportError:
  41. np = None
  42. requires_32b = unittest.skipUnless(sys.maxsize < 2**32,
  43. "test is only meaningful on 32-bit builds")
  44. # Tests that try a number of pickle protocols should have a
  45. # for proto in protocols:
  46. # kind of outer loop.
  47. protocols = range(pickle.HIGHEST_PROTOCOL + 1)
  48. # Return True if opcode code appears in the pickle, else False.
  49. def opcode_in_pickle(code, pickle):
  50. for op, dummy, dummy in pickletools.genops(pickle):
  51. if op.code == code.decode("latin-1"):
  52. return True
  53. return False
  54. # Return the number of times opcode code appears in pickle.
  55. def count_opcode(code, pickle):
  56. n = 0
  57. for op, dummy, dummy in pickletools.genops(pickle):
  58. if op.code == code.decode("latin-1"):
  59. n += 1
  60. return n
  61. def identity(x):
  62. return x
  63. class UnseekableIO(io.BytesIO):
  64. def peek(self, *args):
  65. raise NotImplementedError
  66. def seekable(self):
  67. return False
  68. def seek(self, *args):
  69. raise io.UnsupportedOperation
  70. def tell(self):
  71. raise io.UnsupportedOperation
  72. class MinimalIO(object):
  73. """
  74. A file-like object that doesn't support readinto().
  75. """
  76. def __init__(self, *args):
  77. self._bio = io.BytesIO(*args)
  78. self.getvalue = self._bio.getvalue
  79. self.read = self._bio.read
  80. self.readline = self._bio.readline
  81. self.write = self._bio.write
  82. # We can't very well test the extension registry without putting known stuff
  83. # in it, but we have to be careful to restore its original state. Code
  84. # should do this:
  85. #
  86. # e = ExtensionSaver(extension_code)
  87. # try:
  88. # fiddle w/ the extension registry's stuff for extension_code
  89. # finally:
  90. # e.restore()
  91. class ExtensionSaver:
  92. # Remember current registration for code (if any), and remove it (if
  93. # there is one).
  94. def __init__(self, code):
  95. self.code = code
  96. if code in copyreg._inverted_registry:
  97. self.pair = copyreg._inverted_registry[code]
  98. copyreg.remove_extension(self.pair[0], self.pair[1], code)
  99. else:
  100. self.pair = None
  101. # Restore previous registration for code.
  102. def restore(self):
  103. code = self.code
  104. curpair = copyreg._inverted_registry.get(code)
  105. if curpair is not None:
  106. copyreg.remove_extension(curpair[0], curpair[1], code)
  107. pair = self.pair
  108. if pair is not None:
  109. copyreg.add_extension(pair[0], pair[1], code)
  110. class C:
  111. def __eq__(self, other):
  112. return self.__dict__ == other.__dict__
  113. class D(C):
  114. def __init__(self, arg):
  115. pass
  116. class E(C):
  117. def __getinitargs__(self):
  118. return ()
  119. # Simple mutable object.
  120. class Object:
  121. pass
  122. # Hashable immutable key object containing unheshable mutable data.
  123. class K:
  124. def __init__(self, value):
  125. self.value = value
  126. def __reduce__(self):
  127. # Shouldn't support the recursion itself
  128. return K, (self.value,)
  129. import __main__
  130. __main__.C = C
  131. C.__module__ = "__main__"
  132. __main__.D = D
  133. D.__module__ = "__main__"
  134. __main__.E = E
  135. E.__module__ = "__main__"
  136. class myint(int):
  137. def __init__(self, x):
  138. self.str = str(x)
  139. class initarg(C):
  140. def __init__(self, a, b):
  141. self.a = a
  142. self.b = b
  143. def __getinitargs__(self):
  144. return self.a, self.b
  145. class metaclass(type):
  146. pass
  147. class use_metaclass(object, metaclass=metaclass):
  148. pass
  149. class pickling_metaclass(type):
  150. def __eq__(self, other):
  151. return (type(self) == type(other) and
  152. self.reduce_args == other.reduce_args)
  153. def __reduce__(self):
  154. return (create_dynamic_class, self.reduce_args)
  155. def create_dynamic_class(name, bases):
  156. result = pickling_metaclass(name, bases, dict())
  157. result.reduce_args = (name, bases)
  158. return result
  159. class ZeroCopyBytes(bytes):
  160. readonly = True
  161. c_contiguous = True
  162. f_contiguous = True
  163. zero_copy_reconstruct = True
  164. def __reduce_ex__(self, protocol):
  165. if protocol >= 5:
  166. return type(self)._reconstruct, (pickle.PickleBuffer(self),), None
  167. else:
  168. return type(self)._reconstruct, (bytes(self),)
  169. def __repr__(self):
  170. return "{}({!r})".format(self.__class__.__name__, bytes(self))
  171. __str__ = __repr__
  172. @classmethod
  173. def _reconstruct(cls, obj):
  174. with memoryview(obj) as m:
  175. obj = m.obj
  176. if type(obj) is cls:
  177. # Zero-copy
  178. return obj
  179. else:
  180. return cls(obj)
  181. class ZeroCopyBytearray(bytearray):
  182. readonly = False
  183. c_contiguous = True
  184. f_contiguous = True
  185. zero_copy_reconstruct = True
  186. def __reduce_ex__(self, protocol):
  187. if protocol >= 5:
  188. return type(self)._reconstruct, (pickle.PickleBuffer(self),), None
  189. else:
  190. return type(self)._reconstruct, (bytes(self),)
  191. def __repr__(self):
  192. return "{}({!r})".format(self.__class__.__name__, bytes(self))
  193. __str__ = __repr__
  194. @classmethod
  195. def _reconstruct(cls, obj):
  196. with memoryview(obj) as m:
  197. obj = m.obj
  198. if type(obj) is cls:
  199. # Zero-copy
  200. return obj
  201. else:
  202. return cls(obj)
  203. if _testbuffer is not None:
  204. class PicklableNDArray:
  205. # A not-really-zero-copy picklable ndarray, as the ndarray()
  206. # constructor doesn't allow for it
  207. zero_copy_reconstruct = False
  208. def __init__(self, *args, **kwargs):
  209. self.array = _testbuffer.ndarray(*args, **kwargs)
  210. def __getitem__(self, idx):
  211. cls = type(self)
  212. new = cls.__new__(cls)
  213. new.array = self.array[idx]
  214. return new
  215. @property
  216. def readonly(self):
  217. return self.array.readonly
  218. @property
  219. def c_contiguous(self):
  220. return self.array.c_contiguous
  221. @property
  222. def f_contiguous(self):
  223. return self.array.f_contiguous
  224. def __eq__(self, other):
  225. if not isinstance(other, PicklableNDArray):
  226. return NotImplemented
  227. return (other.array.format == self.array.format and
  228. other.array.shape == self.array.shape and
  229. other.array.strides == self.array.strides and
  230. other.array.readonly == self.array.readonly and
  231. other.array.tobytes() == self.array.tobytes())
  232. def __ne__(self, other):
  233. if not isinstance(other, PicklableNDArray):
  234. return NotImplemented
  235. return not (self == other)
  236. def __repr__(self):
  237. return (f"{type(self)}(shape={self.array.shape},"
  238. f"strides={self.array.strides}, "
  239. f"bytes={self.array.tobytes()})")
  240. def __reduce_ex__(self, protocol):
  241. if not self.array.contiguous:
  242. raise NotImplementedError("Reconstructing a non-contiguous "
  243. "ndarray does not seem possible")
  244. ndarray_kwargs = {"shape": self.array.shape,
  245. "strides": self.array.strides,
  246. "format": self.array.format,
  247. "flags": (0 if self.readonly
  248. else _testbuffer.ND_WRITABLE)}
  249. pb = pickle.PickleBuffer(self.array)
  250. if protocol >= 5:
  251. return (type(self)._reconstruct,
  252. (pb, ndarray_kwargs))
  253. else:
  254. # Need to serialize the bytes in physical order
  255. with pb.raw() as m:
  256. return (type(self)._reconstruct,
  257. (m.tobytes(), ndarray_kwargs))
  258. @classmethod
  259. def _reconstruct(cls, obj, kwargs):
  260. with memoryview(obj) as m:
  261. # For some reason, ndarray() wants a list of integers...
  262. # XXX This only works if format == 'B'
  263. items = list(m.tobytes())
  264. return cls(items, **kwargs)
  265. # DATA0 .. DATA4 are the pickles we expect under the various protocols, for
  266. # the object returned by create_data().
  267. DATA0 = (
  268. b'(lp0\nL0L\naL1L\naF2.0\n'
  269. b'ac__builtin__\ncomple'
  270. b'x\np1\n(F3.0\nF0.0\ntp2\n'
  271. b'Rp3\naL1L\naL-1L\naL255'
  272. b'L\naL-255L\naL-256L\naL'
  273. b'65535L\naL-65535L\naL-'
  274. b'65536L\naL2147483647L'
  275. b'\naL-2147483647L\naL-2'
  276. b'147483648L\na(Vabc\np4'
  277. b'\ng4\nccopy_reg\n_recon'
  278. b'structor\np5\n(c__main'
  279. b'__\nC\np6\nc__builtin__'
  280. b'\nobject\np7\nNtp8\nRp9\n'
  281. b'(dp10\nVfoo\np11\nL1L\ns'
  282. b'Vbar\np12\nL2L\nsbg9\ntp'
  283. b'13\nag13\naL5L\na.'
  284. )
  285. # Disassembly of DATA0
  286. DATA0_DIS = """\
  287. 0: ( MARK
  288. 1: l LIST (MARK at 0)
  289. 2: p PUT 0
  290. 5: L LONG 0
  291. 9: a APPEND
  292. 10: L LONG 1
  293. 14: a APPEND
  294. 15: F FLOAT 2.0
  295. 20: a APPEND
  296. 21: c GLOBAL '__builtin__ complex'
  297. 42: p PUT 1
  298. 45: ( MARK
  299. 46: F FLOAT 3.0
  300. 51: F FLOAT 0.0
  301. 56: t TUPLE (MARK at 45)
  302. 57: p PUT 2
  303. 60: R REDUCE
  304. 61: p PUT 3
  305. 64: a APPEND
  306. 65: L LONG 1
  307. 69: a APPEND
  308. 70: L LONG -1
  309. 75: a APPEND
  310. 76: L LONG 255
  311. 82: a APPEND
  312. 83: L LONG -255
  313. 90: a APPEND
  314. 91: L LONG -256
  315. 98: a APPEND
  316. 99: L LONG 65535
  317. 107: a APPEND
  318. 108: L LONG -65535
  319. 117: a APPEND
  320. 118: L LONG -65536
  321. 127: a APPEND
  322. 128: L LONG 2147483647
  323. 141: a APPEND
  324. 142: L LONG -2147483647
  325. 156: a APPEND
  326. 157: L LONG -2147483648
  327. 171: a APPEND
  328. 172: ( MARK
  329. 173: V UNICODE 'abc'
  330. 178: p PUT 4
  331. 181: g GET 4
  332. 184: c GLOBAL 'copy_reg _reconstructor'
  333. 209: p PUT 5
  334. 212: ( MARK
  335. 213: c GLOBAL '__main__ C'
  336. 225: p PUT 6
  337. 228: c GLOBAL '__builtin__ object'
  338. 248: p PUT 7
  339. 251: N NONE
  340. 252: t TUPLE (MARK at 212)
  341. 253: p PUT 8
  342. 256: R REDUCE
  343. 257: p PUT 9
  344. 260: ( MARK
  345. 261: d DICT (MARK at 260)
  346. 262: p PUT 10
  347. 266: V UNICODE 'foo'
  348. 271: p PUT 11
  349. 275: L LONG 1
  350. 279: s SETITEM
  351. 280: V UNICODE 'bar'
  352. 285: p PUT 12
  353. 289: L LONG 2
  354. 293: s SETITEM
  355. 294: b BUILD
  356. 295: g GET 9
  357. 298: t TUPLE (MARK at 172)
  358. 299: p PUT 13
  359. 303: a APPEND
  360. 304: g GET 13
  361. 308: a APPEND
  362. 309: L LONG 5
  363. 313: a APPEND
  364. 314: . STOP
  365. highest protocol among opcodes = 0
  366. """
  367. DATA1 = (
  368. b']q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c__'
  369. b'builtin__\ncomplex\nq\x01'
  370. b'(G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00t'
  371. b'q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ'
  372. b'\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff'
  373. b'\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00ab'
  374. b'cq\x04h\x04ccopy_reg\n_reco'
  375. b'nstructor\nq\x05(c__main'
  376. b'__\nC\nq\x06c__builtin__\n'
  377. b'object\nq\x07Ntq\x08Rq\t}q\n('
  378. b'X\x03\x00\x00\x00fooq\x0bK\x01X\x03\x00\x00\x00bar'
  379. b'q\x0cK\x02ubh\ttq\rh\rK\x05e.'
  380. )
  381. # Disassembly of DATA1
  382. DATA1_DIS = """\
  383. 0: ] EMPTY_LIST
  384. 1: q BINPUT 0
  385. 3: ( MARK
  386. 4: K BININT1 0
  387. 6: K BININT1 1
  388. 8: G BINFLOAT 2.0
  389. 17: c GLOBAL '__builtin__ complex'
  390. 38: q BINPUT 1
  391. 40: ( MARK
  392. 41: G BINFLOAT 3.0
  393. 50: G BINFLOAT 0.0
  394. 59: t TUPLE (MARK at 40)
  395. 60: q BINPUT 2
  396. 62: R REDUCE
  397. 63: q BINPUT 3
  398. 65: K BININT1 1
  399. 67: J BININT -1
  400. 72: K BININT1 255
  401. 74: J BININT -255
  402. 79: J BININT -256
  403. 84: M BININT2 65535
  404. 87: J BININT -65535
  405. 92: J BININT -65536
  406. 97: J BININT 2147483647
  407. 102: J BININT -2147483647
  408. 107: J BININT -2147483648
  409. 112: ( MARK
  410. 113: X BINUNICODE 'abc'
  411. 121: q BINPUT 4
  412. 123: h BINGET 4
  413. 125: c GLOBAL 'copy_reg _reconstructor'
  414. 150: q BINPUT 5
  415. 152: ( MARK
  416. 153: c GLOBAL '__main__ C'
  417. 165: q BINPUT 6
  418. 167: c GLOBAL '__builtin__ object'
  419. 187: q BINPUT 7
  420. 189: N NONE
  421. 190: t TUPLE (MARK at 152)
  422. 191: q BINPUT 8
  423. 193: R REDUCE
  424. 194: q BINPUT 9
  425. 196: } EMPTY_DICT
  426. 197: q BINPUT 10
  427. 199: ( MARK
  428. 200: X BINUNICODE 'foo'
  429. 208: q BINPUT 11
  430. 210: K BININT1 1
  431. 212: X BINUNICODE 'bar'
  432. 220: q BINPUT 12
  433. 222: K BININT1 2
  434. 224: u SETITEMS (MARK at 199)
  435. 225: b BUILD
  436. 226: h BINGET 9
  437. 228: t TUPLE (MARK at 112)
  438. 229: q BINPUT 13
  439. 231: h BINGET 13
  440. 233: K BININT1 5
  441. 235: e APPENDS (MARK at 3)
  442. 236: . STOP
  443. highest protocol among opcodes = 1
  444. """
  445. DATA2 = (
  446. b'\x80\x02]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c'
  447. b'__builtin__\ncomplex\n'
  448. b'q\x01G@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00'
  449. b'\x86q\x02Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xff'
  450. b'J\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff'
  451. b'\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00a'
  452. b'bcq\x04h\x04c__main__\nC\nq\x05'
  453. b')\x81q\x06}q\x07(X\x03\x00\x00\x00fooq\x08K\x01'
  454. b'X\x03\x00\x00\x00barq\tK\x02ubh\x06tq\nh'
  455. b'\nK\x05e.'
  456. )
  457. # Disassembly of DATA2
  458. DATA2_DIS = """\
  459. 0: \x80 PROTO 2
  460. 2: ] EMPTY_LIST
  461. 3: q BINPUT 0
  462. 5: ( MARK
  463. 6: K BININT1 0
  464. 8: K BININT1 1
  465. 10: G BINFLOAT 2.0
  466. 19: c GLOBAL '__builtin__ complex'
  467. 40: q BINPUT 1
  468. 42: G BINFLOAT 3.0
  469. 51: G BINFLOAT 0.0
  470. 60: \x86 TUPLE2
  471. 61: q BINPUT 2
  472. 63: R REDUCE
  473. 64: q BINPUT 3
  474. 66: K BININT1 1
  475. 68: J BININT -1
  476. 73: K BININT1 255
  477. 75: J BININT -255
  478. 80: J BININT -256
  479. 85: M BININT2 65535
  480. 88: J BININT -65535
  481. 93: J BININT -65536
  482. 98: J BININT 2147483647
  483. 103: J BININT -2147483647
  484. 108: J BININT -2147483648
  485. 113: ( MARK
  486. 114: X BINUNICODE 'abc'
  487. 122: q BINPUT 4
  488. 124: h BINGET 4
  489. 126: c GLOBAL '__main__ C'
  490. 138: q BINPUT 5
  491. 140: ) EMPTY_TUPLE
  492. 141: \x81 NEWOBJ
  493. 142: q BINPUT 6
  494. 144: } EMPTY_DICT
  495. 145: q BINPUT 7
  496. 147: ( MARK
  497. 148: X BINUNICODE 'foo'
  498. 156: q BINPUT 8
  499. 158: K BININT1 1
  500. 160: X BINUNICODE 'bar'
  501. 168: q BINPUT 9
  502. 170: K BININT1 2
  503. 172: u SETITEMS (MARK at 147)
  504. 173: b BUILD
  505. 174: h BINGET 6
  506. 176: t TUPLE (MARK at 113)
  507. 177: q BINPUT 10
  508. 179: h BINGET 10
  509. 181: K BININT1 5
  510. 183: e APPENDS (MARK at 5)
  511. 184: . STOP
  512. highest protocol among opcodes = 2
  513. """
  514. DATA3 = (
  515. b'\x80\x03]q\x00(K\x00K\x01G@\x00\x00\x00\x00\x00\x00\x00c'
  516. b'builtins\ncomplex\nq\x01G'
  517. b'@\x08\x00\x00\x00\x00\x00\x00G\x00\x00\x00\x00\x00\x00\x00\x00\x86q\x02'
  518. b'Rq\x03K\x01J\xff\xff\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff'
  519. b'\xff\xffM\xff\xffJ\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7f'
  520. b'J\x01\x00\x00\x80J\x00\x00\x00\x80(X\x03\x00\x00\x00abcq'
  521. b'\x04h\x04c__main__\nC\nq\x05)\x81q'
  522. b'\x06}q\x07(X\x03\x00\x00\x00barq\x08K\x02X\x03\x00'
  523. b'\x00\x00fooq\tK\x01ubh\x06tq\nh\nK\x05'
  524. b'e.'
  525. )
  526. # Disassembly of DATA3
  527. DATA3_DIS = """\
  528. 0: \x80 PROTO 3
  529. 2: ] EMPTY_LIST
  530. 3: q BINPUT 0
  531. 5: ( MARK
  532. 6: K BININT1 0
  533. 8: K BININT1 1
  534. 10: G BINFLOAT 2.0
  535. 19: c GLOBAL 'builtins complex'
  536. 37: q BINPUT 1
  537. 39: G BINFLOAT 3.0
  538. 48: G BINFLOAT 0.0
  539. 57: \x86 TUPLE2
  540. 58: q BINPUT 2
  541. 60: R REDUCE
  542. 61: q BINPUT 3
  543. 63: K BININT1 1
  544. 65: J BININT -1
  545. 70: K BININT1 255
  546. 72: J BININT -255
  547. 77: J BININT -256
  548. 82: M BININT2 65535
  549. 85: J BININT -65535
  550. 90: J BININT -65536
  551. 95: J BININT 2147483647
  552. 100: J BININT -2147483647
  553. 105: J BININT -2147483648
  554. 110: ( MARK
  555. 111: X BINUNICODE 'abc'
  556. 119: q BINPUT 4
  557. 121: h BINGET 4
  558. 123: c GLOBAL '__main__ C'
  559. 135: q BINPUT 5
  560. 137: ) EMPTY_TUPLE
  561. 138: \x81 NEWOBJ
  562. 139: q BINPUT 6
  563. 141: } EMPTY_DICT
  564. 142: q BINPUT 7
  565. 144: ( MARK
  566. 145: X BINUNICODE 'bar'
  567. 153: q BINPUT 8
  568. 155: K BININT1 2
  569. 157: X BINUNICODE 'foo'
  570. 165: q BINPUT 9
  571. 167: K BININT1 1
  572. 169: u SETITEMS (MARK at 144)
  573. 170: b BUILD
  574. 171: h BINGET 6
  575. 173: t TUPLE (MARK at 110)
  576. 174: q BINPUT 10
  577. 176: h BINGET 10
  578. 178: K BININT1 5
  579. 180: e APPENDS (MARK at 5)
  580. 181: . STOP
  581. highest protocol among opcodes = 2
  582. """
  583. DATA4 = (
  584. b'\x80\x04\x95\xa8\x00\x00\x00\x00\x00\x00\x00]\x94(K\x00K\x01G@'
  585. b'\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\x07'
  586. b'complex\x94\x93\x94G@\x08\x00\x00\x00\x00\x00\x00G'
  587. b'\x00\x00\x00\x00\x00\x00\x00\x00\x86\x94R\x94K\x01J\xff\xff\xff\xffK'
  588. b'\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xffJ'
  589. b'\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00\x80('
  590. b'\x8c\x03abc\x94h\x06\x8c\x08__main__\x94\x8c'
  591. b'\x01C\x94\x93\x94)\x81\x94}\x94(\x8c\x03bar\x94K\x02\x8c'
  592. b'\x03foo\x94K\x01ubh\nt\x94h\x0eK\x05e.'
  593. )
  594. # Disassembly of DATA4
  595. DATA4_DIS = """\
  596. 0: \x80 PROTO 4
  597. 2: \x95 FRAME 168
  598. 11: ] EMPTY_LIST
  599. 12: \x94 MEMOIZE
  600. 13: ( MARK
  601. 14: K BININT1 0
  602. 16: K BININT1 1
  603. 18: G BINFLOAT 2.0
  604. 27: \x8c SHORT_BINUNICODE 'builtins'
  605. 37: \x94 MEMOIZE
  606. 38: \x8c SHORT_BINUNICODE 'complex'
  607. 47: \x94 MEMOIZE
  608. 48: \x93 STACK_GLOBAL
  609. 49: \x94 MEMOIZE
  610. 50: G BINFLOAT 3.0
  611. 59: G BINFLOAT 0.0
  612. 68: \x86 TUPLE2
  613. 69: \x94 MEMOIZE
  614. 70: R REDUCE
  615. 71: \x94 MEMOIZE
  616. 72: K BININT1 1
  617. 74: J BININT -1
  618. 79: K BININT1 255
  619. 81: J BININT -255
  620. 86: J BININT -256
  621. 91: M BININT2 65535
  622. 94: J BININT -65535
  623. 99: J BININT -65536
  624. 104: J BININT 2147483647
  625. 109: J BININT -2147483647
  626. 114: J BININT -2147483648
  627. 119: ( MARK
  628. 120: \x8c SHORT_BINUNICODE 'abc'
  629. 125: \x94 MEMOIZE
  630. 126: h BINGET 6
  631. 128: \x8c SHORT_BINUNICODE '__main__'
  632. 138: \x94 MEMOIZE
  633. 139: \x8c SHORT_BINUNICODE 'C'
  634. 142: \x94 MEMOIZE
  635. 143: \x93 STACK_GLOBAL
  636. 144: \x94 MEMOIZE
  637. 145: ) EMPTY_TUPLE
  638. 146: \x81 NEWOBJ
  639. 147: \x94 MEMOIZE
  640. 148: } EMPTY_DICT
  641. 149: \x94 MEMOIZE
  642. 150: ( MARK
  643. 151: \x8c SHORT_BINUNICODE 'bar'
  644. 156: \x94 MEMOIZE
  645. 157: K BININT1 2
  646. 159: \x8c SHORT_BINUNICODE 'foo'
  647. 164: \x94 MEMOIZE
  648. 165: K BININT1 1
  649. 167: u SETITEMS (MARK at 150)
  650. 168: b BUILD
  651. 169: h BINGET 10
  652. 171: t TUPLE (MARK at 119)
  653. 172: \x94 MEMOIZE
  654. 173: h BINGET 14
  655. 175: K BININT1 5
  656. 177: e APPENDS (MARK at 13)
  657. 178: . STOP
  658. highest protocol among opcodes = 4
  659. """
  660. # set([1,2]) pickled from 2.x with protocol 2
  661. DATA_SET = b'\x80\x02c__builtin__\nset\nq\x00]q\x01(K\x01K\x02e\x85q\x02Rq\x03.'
  662. # xrange(5) pickled from 2.x with protocol 2
  663. DATA_XRANGE = b'\x80\x02c__builtin__\nxrange\nq\x00K\x00K\x05K\x01\x87q\x01Rq\x02.'
  664. # a SimpleCookie() object pickled from 2.x with protocol 2
  665. DATA_COOKIE = (b'\x80\x02cCookie\nSimpleCookie\nq\x00)\x81q\x01U\x03key'
  666. b'q\x02cCookie\nMorsel\nq\x03)\x81q\x04(U\x07commentq\x05U'
  667. b'\x00q\x06U\x06domainq\x07h\x06U\x06secureq\x08h\x06U\x07'
  668. b'expiresq\th\x06U\x07max-ageq\nh\x06U\x07versionq\x0bh\x06U'
  669. b'\x04pathq\x0ch\x06U\x08httponlyq\rh\x06u}q\x0e(U\x0b'
  670. b'coded_valueq\x0fU\x05valueq\x10h\x10h\x10h\x02h\x02ubs}q\x11b.')
  671. # set([3]) pickled from 2.x with protocol 2
  672. DATA_SET2 = b'\x80\x02c__builtin__\nset\nq\x00]q\x01K\x03a\x85q\x02Rq\x03.'
  673. python2_exceptions_without_args = (
  674. ArithmeticError,
  675. AssertionError,
  676. AttributeError,
  677. BaseException,
  678. BufferError,
  679. BytesWarning,
  680. DeprecationWarning,
  681. EOFError,
  682. EnvironmentError,
  683. Exception,
  684. FloatingPointError,
  685. FutureWarning,
  686. GeneratorExit,
  687. IOError,
  688. ImportError,
  689. ImportWarning,
  690. IndentationError,
  691. IndexError,
  692. KeyError,
  693. KeyboardInterrupt,
  694. LookupError,
  695. MemoryError,
  696. NameError,
  697. NotImplementedError,
  698. OSError,
  699. OverflowError,
  700. PendingDeprecationWarning,
  701. ReferenceError,
  702. RuntimeError,
  703. RuntimeWarning,
  704. # StandardError is gone in Python 3, we map it to Exception
  705. StopIteration,
  706. SyntaxError,
  707. SyntaxWarning,
  708. SystemError,
  709. SystemExit,
  710. TabError,
  711. TypeError,
  712. UnboundLocalError,
  713. UnicodeError,
  714. UnicodeWarning,
  715. UserWarning,
  716. ValueError,
  717. Warning,
  718. ZeroDivisionError,
  719. )
  720. exception_pickle = b'\x80\x02cexceptions\n?\nq\x00)Rq\x01.'
  721. # UnicodeEncodeError object pickled from 2.x with protocol 2
  722. DATA_UEERR = (b'\x80\x02cexceptions\nUnicodeEncodeError\n'
  723. b'q\x00(U\x05asciiq\x01X\x03\x00\x00\x00fooq\x02K\x00K\x01'
  724. b'U\x03badq\x03tq\x04Rq\x05.')
  725. def create_data():
  726. c = C()
  727. c.foo = 1
  728. c.bar = 2
  729. x = [0, 1, 2.0, 3.0+0j]
  730. # Append some integer test cases at cPickle.c's internal size
  731. # cutoffs.
  732. uint1max = 0xff
  733. uint2max = 0xffff
  734. int4max = 0x7fffffff
  735. x.extend([1, -1,
  736. uint1max, -uint1max, -uint1max-1,
  737. uint2max, -uint2max, -uint2max-1,
  738. int4max, -int4max, -int4max-1])
  739. y = ('abc', 'abc', c, c)
  740. x.append(y)
  741. x.append(y)
  742. x.append(5)
  743. return x
  744. class AbstractUnpickleTests:
  745. # Subclass must define self.loads.
  746. _testdata = create_data()
  747. def assert_is_copy(self, obj, objcopy, msg=None):
  748. """Utility method to verify if two objects are copies of each others.
  749. """
  750. if msg is None:
  751. msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
  752. self.assertEqual(obj, objcopy, msg=msg)
  753. self.assertIs(type(obj), type(objcopy), msg=msg)
  754. if hasattr(obj, '__dict__'):
  755. self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
  756. self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
  757. if hasattr(obj, '__slots__'):
  758. self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
  759. for slot in obj.__slots__:
  760. self.assertEqual(
  761. hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
  762. self.assertEqual(getattr(obj, slot, None),
  763. getattr(objcopy, slot, None), msg=msg)
  764. def check_unpickling_error(self, errors, data):
  765. with self.subTest(data=data), \
  766. self.assertRaises(errors):
  767. try:
  768. self.loads(data)
  769. except BaseException as exc:
  770. if support.verbose > 1:
  771. print('%-32r - %s: %s' %
  772. (data, exc.__class__.__name__, exc))
  773. raise
  774. def test_load_from_data0(self):
  775. self.assert_is_copy(self._testdata, self.loads(DATA0))
  776. def test_load_from_data1(self):
  777. self.assert_is_copy(self._testdata, self.loads(DATA1))
  778. def test_load_from_data2(self):
  779. self.assert_is_copy(self._testdata, self.loads(DATA2))
  780. def test_load_from_data3(self):
  781. self.assert_is_copy(self._testdata, self.loads(DATA3))
  782. def test_load_from_data4(self):
  783. self.assert_is_copy(self._testdata, self.loads(DATA4))
  784. def test_load_classic_instance(self):
  785. # See issue5180. Test loading 2.x pickles that
  786. # contain an instance of old style class.
  787. for X, args in [(C, ()), (D, ('x',)), (E, ())]:
  788. xname = X.__name__.encode('ascii')
  789. # Protocol 0 (text mode pickle):
  790. """
  791. 0: ( MARK
  792. 1: i INST '__main__ X' (MARK at 0)
  793. 13: p PUT 0
  794. 16: ( MARK
  795. 17: d DICT (MARK at 16)
  796. 18: p PUT 1
  797. 21: b BUILD
  798. 22: . STOP
  799. """
  800. pickle0 = (b"(i__main__\n"
  801. b"X\n"
  802. b"p0\n"
  803. b"(dp1\nb.").replace(b'X', xname)
  804. self.assert_is_copy(X(*args), self.loads(pickle0))
  805. # Protocol 1 (binary mode pickle)
  806. """
  807. 0: ( MARK
  808. 1: c GLOBAL '__main__ X'
  809. 13: q BINPUT 0
  810. 15: o OBJ (MARK at 0)
  811. 16: q BINPUT 1
  812. 18: } EMPTY_DICT
  813. 19: q BINPUT 2
  814. 21: b BUILD
  815. 22: . STOP
  816. """
  817. pickle1 = (b'(c__main__\n'
  818. b'X\n'
  819. b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
  820. self.assert_is_copy(X(*args), self.loads(pickle1))
  821. # Protocol 2 (pickle2 = b'\x80\x02' + pickle1)
  822. """
  823. 0: \x80 PROTO 2
  824. 2: ( MARK
  825. 3: c GLOBAL '__main__ X'
  826. 15: q BINPUT 0
  827. 17: o OBJ (MARK at 2)
  828. 18: q BINPUT 1
  829. 20: } EMPTY_DICT
  830. 21: q BINPUT 2
  831. 23: b BUILD
  832. 24: . STOP
  833. """
  834. pickle2 = (b'\x80\x02(c__main__\n'
  835. b'X\n'
  836. b'q\x00oq\x01}q\x02b.').replace(b'X', xname)
  837. self.assert_is_copy(X(*args), self.loads(pickle2))
  838. def test_maxint64(self):
  839. maxint64 = (1 << 63) - 1
  840. data = b'I' + str(maxint64).encode("ascii") + b'\n.'
  841. got = self.loads(data)
  842. self.assert_is_copy(maxint64, got)
  843. # Try too with a bogus literal.
  844. data = b'I' + str(maxint64).encode("ascii") + b'JUNK\n.'
  845. self.check_unpickling_error(ValueError, data)
  846. def test_unpickle_from_2x(self):
  847. # Unpickle non-trivial data from Python 2.x.
  848. loaded = self.loads(DATA_SET)
  849. self.assertEqual(loaded, set([1, 2]))
  850. loaded = self.loads(DATA_XRANGE)
  851. self.assertEqual(type(loaded), type(range(0)))
  852. self.assertEqual(list(loaded), list(range(5)))
  853. loaded = self.loads(DATA_COOKIE)
  854. self.assertEqual(type(loaded), SimpleCookie)
  855. self.assertEqual(list(loaded.keys()), ["key"])
  856. self.assertEqual(loaded["key"].value, "value")
  857. # Exception objects without arguments pickled from 2.x with protocol 2
  858. for exc in python2_exceptions_without_args:
  859. data = exception_pickle.replace(b'?', exc.__name__.encode("ascii"))
  860. loaded = self.loads(data)
  861. self.assertIs(type(loaded), exc)
  862. # StandardError is mapped to Exception, test that separately
  863. loaded = self.loads(exception_pickle.replace(b'?', b'StandardError'))
  864. self.assertIs(type(loaded), Exception)
  865. loaded = self.loads(DATA_UEERR)
  866. self.assertIs(type(loaded), UnicodeEncodeError)
  867. self.assertEqual(loaded.object, "foo")
  868. self.assertEqual(loaded.encoding, "ascii")
  869. self.assertEqual(loaded.start, 0)
  870. self.assertEqual(loaded.end, 1)
  871. self.assertEqual(loaded.reason, "bad")
  872. def test_load_python2_str_as_bytes(self):
  873. # From Python 2: pickle.dumps('a\x00\xa0', protocol=0)
  874. self.assertEqual(self.loads(b"S'a\\x00\\xa0'\n.",
  875. encoding="bytes"), b'a\x00\xa0')
  876. # From Python 2: pickle.dumps('a\x00\xa0', protocol=1)
  877. self.assertEqual(self.loads(b'U\x03a\x00\xa0.',
  878. encoding="bytes"), b'a\x00\xa0')
  879. # From Python 2: pickle.dumps('a\x00\xa0', protocol=2)
  880. self.assertEqual(self.loads(b'\x80\x02U\x03a\x00\xa0.',
  881. encoding="bytes"), b'a\x00\xa0')
  882. def test_load_python2_unicode_as_str(self):
  883. # From Python 2: pickle.dumps(u'π', protocol=0)
  884. self.assertEqual(self.loads(b'V\\u03c0\n.',
  885. encoding='bytes'), 'π')
  886. # From Python 2: pickle.dumps(u'π', protocol=1)
  887. self.assertEqual(self.loads(b'X\x02\x00\x00\x00\xcf\x80.',
  888. encoding="bytes"), 'π')
  889. # From Python 2: pickle.dumps(u'π', protocol=2)
  890. self.assertEqual(self.loads(b'\x80\x02X\x02\x00\x00\x00\xcf\x80.',
  891. encoding="bytes"), 'π')
  892. def test_load_long_python2_str_as_bytes(self):
  893. # From Python 2: pickle.dumps('x' * 300, protocol=1)
  894. self.assertEqual(self.loads(pickle.BINSTRING +
  895. struct.pack("<I", 300) +
  896. b'x' * 300 + pickle.STOP,
  897. encoding='bytes'), b'x' * 300)
  898. def test_constants(self):
  899. self.assertIsNone(self.loads(b'N.'))
  900. self.assertIs(self.loads(b'\x88.'), True)
  901. self.assertIs(self.loads(b'\x89.'), False)
  902. self.assertIs(self.loads(b'I01\n.'), True)
  903. self.assertIs(self.loads(b'I00\n.'), False)
  904. def test_empty_bytestring(self):
  905. # issue 11286
  906. empty = self.loads(b'\x80\x03U\x00q\x00.', encoding='koi8-r')
  907. self.assertEqual(empty, '')
  908. def test_short_binbytes(self):
  909. dumped = b'\x80\x03C\x04\xe2\x82\xac\x00.'
  910. self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00')
  911. def test_binbytes(self):
  912. dumped = b'\x80\x03B\x04\x00\x00\x00\xe2\x82\xac\x00.'
  913. self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00')
  914. @requires_32b
  915. def test_negative_32b_binbytes(self):
  916. # On 32-bit builds, a BINBYTES of 2**31 or more is refused
  917. dumped = b'\x80\x03B\xff\xff\xff\xffxyzq\x00.'
  918. self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
  919. dumped)
  920. @requires_32b
  921. def test_negative_32b_binunicode(self):
  922. # On 32-bit builds, a BINUNICODE of 2**31 or more is refused
  923. dumped = b'\x80\x03X\xff\xff\xff\xffxyzq\x00.'
  924. self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
  925. dumped)
  926. def test_short_binunicode(self):
  927. dumped = b'\x80\x04\x8c\x04\xe2\x82\xac\x00.'
  928. self.assertEqual(self.loads(dumped), '\u20ac\x00')
  929. def test_misc_get(self):
  930. self.check_unpickling_error(pickle.UnpicklingError, b'g0\np0')
  931. self.check_unpickling_error(pickle.UnpicklingError, b'jens:')
  932. self.check_unpickling_error(pickle.UnpicklingError, b'hens:')
  933. self.assert_is_copy([(100,), (100,)],
  934. self.loads(b'((Kdtp0\nh\x00l.))'))
  935. def test_binbytes8(self):
  936. dumped = b'\x80\x04\x8e\4\0\0\0\0\0\0\0\xe2\x82\xac\x00.'
  937. self.assertEqual(self.loads(dumped), b'\xe2\x82\xac\x00')
  938. def test_binunicode8(self):
  939. dumped = b'\x80\x04\x8d\4\0\0\0\0\0\0\0\xe2\x82\xac\x00.'
  940. self.assertEqual(self.loads(dumped), '\u20ac\x00')
  941. def test_bytearray8(self):
  942. dumped = b'\x80\x05\x96\x03\x00\x00\x00\x00\x00\x00\x00xxx.'
  943. self.assertEqual(self.loads(dumped), bytearray(b'xxx'))
  944. @requires_32b
  945. def test_large_32b_binbytes8(self):
  946. dumped = b'\x80\x04\x8e\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.'
  947. self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
  948. dumped)
  949. @requires_32b
  950. def test_large_32b_bytearray8(self):
  951. dumped = b'\x80\x05\x96\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.'
  952. self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
  953. dumped)
  954. @requires_32b
  955. def test_large_32b_binunicode8(self):
  956. dumped = b'\x80\x04\x8d\4\0\0\0\1\0\0\0\xe2\x82\xac\x00.'
  957. self.check_unpickling_error((pickle.UnpicklingError, OverflowError),
  958. dumped)
  959. def test_get(self):
  960. pickled = b'((lp100000\ng100000\nt.'
  961. unpickled = self.loads(pickled)
  962. self.assertEqual(unpickled, ([],)*2)
  963. self.assertIs(unpickled[0], unpickled[1])
  964. def test_binget(self):
  965. pickled = b'(]q\xffh\xfft.'
  966. unpickled = self.loads(pickled)
  967. self.assertEqual(unpickled, ([],)*2)
  968. self.assertIs(unpickled[0], unpickled[1])
  969. def test_long_binget(self):
  970. pickled = b'(]r\x00\x00\x01\x00j\x00\x00\x01\x00t.'
  971. unpickled = self.loads(pickled)
  972. self.assertEqual(unpickled, ([],)*2)
  973. self.assertIs(unpickled[0], unpickled[1])
  974. def test_dup(self):
  975. pickled = b'((l2t.'
  976. unpickled = self.loads(pickled)
  977. self.assertEqual(unpickled, ([],)*2)
  978. self.assertIs(unpickled[0], unpickled[1])
  979. def test_negative_put(self):
  980. # Issue #12847
  981. dumped = b'Va\np-1\n.'
  982. self.check_unpickling_error(ValueError, dumped)
  983. @requires_32b
  984. def test_negative_32b_binput(self):
  985. # Issue #12847
  986. dumped = b'\x80\x03X\x01\x00\x00\x00ar\xff\xff\xff\xff.'
  987. self.check_unpickling_error(ValueError, dumped)
  988. def test_badly_escaped_string(self):
  989. self.check_unpickling_error(ValueError, b"S'\\'\n.")
  990. def test_badly_quoted_string(self):
  991. # Issue #17710
  992. badpickles = [b"S'\n.",
  993. b'S"\n.',
  994. b'S\' \n.',
  995. b'S" \n.',
  996. b'S\'"\n.',
  997. b'S"\'\n.',
  998. b"S' ' \n.",
  999. b'S" " \n.',
  1000. b"S ''\n.",
  1001. b'S ""\n.',
  1002. b'S \n.',
  1003. b'S\n.',
  1004. b'S.']
  1005. for p in badpickles:
  1006. self.check_unpickling_error(pickle.UnpicklingError, p)
  1007. def test_correctly_quoted_string(self):
  1008. goodpickles = [(b"S''\n.", ''),
  1009. (b'S""\n.', ''),
  1010. (b'S"\\n"\n.', '\n'),
  1011. (b"S'\\n'\n.", '\n')]
  1012. for p, expected in goodpickles:
  1013. self.assertEqual(self.loads(p), expected)
  1014. def test_frame_readline(self):
  1015. pickled = b'\x80\x04\x95\x05\x00\x00\x00\x00\x00\x00\x00I42\n.'
  1016. # 0: \x80 PROTO 4
  1017. # 2: \x95 FRAME 5
  1018. # 11: I INT 42
  1019. # 15: . STOP
  1020. self.assertEqual(self.loads(pickled), 42)
  1021. def test_compat_unpickle(self):
  1022. # xrange(1, 7)
  1023. pickled = b'\x80\x02c__builtin__\nxrange\nK\x01K\x07K\x01\x87R.'
  1024. unpickled = self.loads(pickled)
  1025. self.assertIs(type(unpickled), range)
  1026. self.assertEqual(unpickled, range(1, 7))
  1027. self.assertEqual(list(unpickled), [1, 2, 3, 4, 5, 6])
  1028. # reduce
  1029. pickled = b'\x80\x02c__builtin__\nreduce\n.'
  1030. self.assertIs(self.loads(pickled), functools.reduce)
  1031. # whichdb.whichdb
  1032. pickled = b'\x80\x02cwhichdb\nwhichdb\n.'
  1033. self.assertIs(self.loads(pickled), dbm.whichdb)
  1034. # Exception(), StandardError()
  1035. for name in (b'Exception', b'StandardError'):
  1036. pickled = (b'\x80\x02cexceptions\n' + name + b'\nU\x03ugh\x85R.')
  1037. unpickled = self.loads(pickled)
  1038. self.assertIs(type(unpickled), Exception)
  1039. self.assertEqual(str(unpickled), 'ugh')
  1040. # UserDict.UserDict({1: 2}), UserDict.IterableUserDict({1: 2})
  1041. for name in (b'UserDict', b'IterableUserDict'):
  1042. pickled = (b'\x80\x02(cUserDict\n' + name +
  1043. b'\no}U\x04data}K\x01K\x02ssb.')
  1044. unpickled = self.loads(pickled)
  1045. self.assertIs(type(unpickled), collections.UserDict)
  1046. self.assertEqual(unpickled, collections.UserDict({1: 2}))
  1047. def test_bad_reduce(self):
  1048. self.assertEqual(self.loads(b'cbuiltins\nint\n)R.'), 0)
  1049. self.check_unpickling_error(TypeError, b'N)R.')
  1050. self.check_unpickling_error(TypeError, b'cbuiltins\nint\nNR.')
  1051. def test_bad_newobj(self):
  1052. error = (pickle.UnpicklingError, TypeError)
  1053. self.assertEqual(self.loads(b'cbuiltins\nint\n)\x81.'), 0)
  1054. self.check_unpickling_error(error, b'cbuiltins\nlen\n)\x81.')
  1055. self.check_unpickling_error(error, b'cbuiltins\nint\nN\x81.')
  1056. def test_bad_newobj_ex(self):
  1057. error = (pickle.UnpicklingError, TypeError)
  1058. self.assertEqual(self.loads(b'cbuiltins\nint\n)}\x92.'), 0)
  1059. self.check_unpickling_error(error, b'cbuiltins\nlen\n)}\x92.')
  1060. self.check_unpickling_error(error, b'cbuiltins\nint\nN}\x92.')
  1061. self.check_unpickling_error(error, b'cbuiltins\nint\n)N\x92.')
  1062. def test_bad_stack(self):
  1063. badpickles = [
  1064. b'.', # STOP
  1065. b'0', # POP
  1066. b'1', # POP_MARK
  1067. b'2', # DUP
  1068. b'(2',
  1069. b'R', # REDUCE
  1070. b')R',
  1071. b'a', # APPEND
  1072. b'Na',
  1073. b'b', # BUILD
  1074. b'Nb',
  1075. b'd', # DICT
  1076. b'e', # APPENDS
  1077. b'(e',
  1078. b'ibuiltins\nlist\n', # INST
  1079. b'l', # LIST
  1080. b'o', # OBJ
  1081. b'(o',
  1082. b'p1\n', # PUT
  1083. b'q\x00', # BINPUT
  1084. b'r\x00\x00\x00\x00', # LONG_BINPUT
  1085. b's', # SETITEM
  1086. b'Ns',
  1087. b'NNs',
  1088. b't', # TUPLE
  1089. b'u', # SETITEMS
  1090. b'(u',
  1091. b'}(Nu',
  1092. b'\x81', # NEWOBJ
  1093. b')\x81',
  1094. b'\x85', # TUPLE1
  1095. b'\x86', # TUPLE2
  1096. b'N\x86',
  1097. b'\x87', # TUPLE3
  1098. b'N\x87',
  1099. b'NN\x87',
  1100. b'\x90', # ADDITEMS
  1101. b'(\x90',
  1102. b'\x91', # FROZENSET
  1103. b'\x92', # NEWOBJ_EX
  1104. b')}\x92',
  1105. b'\x93', # STACK_GLOBAL
  1106. b'Vlist\n\x93',
  1107. b'\x94', # MEMOIZE
  1108. ]
  1109. for p in badpickles:
  1110. self.check_unpickling_error(self.bad_stack_errors, p)
  1111. def test_bad_mark(self):
  1112. badpickles = [
  1113. b'N(.', # STOP
  1114. b'N(2', # DUP
  1115. b'cbuiltins\nlist\n)(R', # REDUCE
  1116. b'cbuiltins\nlist\n()R',
  1117. b']N(a', # APPEND
  1118. # BUILD
  1119. b'cbuiltins\nValueError\n)R}(b',
  1120. b'cbuiltins\nValueError\n)R(}b',
  1121. b'(Nd', # DICT
  1122. b'N(p1\n', # PUT
  1123. b'N(q\x00', # BINPUT
  1124. b'N(r\x00\x00\x00\x00', # LONG_BINPUT
  1125. b'}NN(s', # SETITEM
  1126. b'}N(Ns',
  1127. b'}(NNs',
  1128. b'}((u', # SETITEMS
  1129. b'cbuiltins\nlist\n)(\x81', # NEWOBJ
  1130. b'cbuiltins\nlist\n()\x81',
  1131. b'N(\x85', # TUPLE1
  1132. b'NN(\x86', # TUPLE2
  1133. b'N(N\x86',
  1134. b'NNN(\x87', # TUPLE3
  1135. b'NN(N\x87',
  1136. b'N(NN\x87',
  1137. b']((\x90', # ADDITEMS
  1138. # NEWOBJ_EX
  1139. b'cbuiltins\nlist\n)}(\x92',
  1140. b'cbuiltins\nlist\n)(}\x92',
  1141. b'cbuiltins\nlist\n()}\x92',
  1142. # STACK_GLOBAL
  1143. b'Vbuiltins\n(Vlist\n\x93',
  1144. b'Vbuiltins\nVlist\n(\x93',
  1145. b'N(\x94', # MEMOIZE
  1146. ]
  1147. for p in badpickles:
  1148. self.check_unpickling_error(self.bad_stack_errors, p)
  1149. def test_truncated_data(self):
  1150. self.check_unpickling_error(EOFError, b'')
  1151. self.check_unpickling_error(EOFError, b'N')
  1152. badpickles = [
  1153. b'B', # BINBYTES
  1154. b'B\x03\x00\x00',
  1155. b'B\x03\x00\x00\x00',
  1156. b'B\x03\x00\x00\x00ab',
  1157. b'C', # SHORT_BINBYTES
  1158. b'C\x03',
  1159. b'C\x03ab',
  1160. b'F', # FLOAT
  1161. b'F0.0',
  1162. b'F0.00',
  1163. b'G', # BINFLOAT
  1164. b'G\x00\x00\x00\x00\x00\x00\x00',
  1165. b'I', # INT
  1166. b'I0',
  1167. b'J', # BININT
  1168. b'J\x00\x00\x00',
  1169. b'K', # BININT1
  1170. b'L', # LONG
  1171. b'L0',
  1172. b'L10',
  1173. b'L0L',
  1174. b'L10L',
  1175. b'M', # BININT2
  1176. b'M\x00',
  1177. # b'P', # PERSID
  1178. # b'Pabc',
  1179. b'S', # STRING
  1180. b"S'abc'",
  1181. b'T', # BINSTRING
  1182. b'T\x03\x00\x00',
  1183. b'T\x03\x00\x00\x00',
  1184. b'T\x03\x00\x00\x00ab',
  1185. b'U', # SHORT_BINSTRING
  1186. b'U\x03',
  1187. b'U\x03ab',
  1188. b'V', # UNICODE
  1189. b'Vabc',
  1190. b'X', # BINUNICODE
  1191. b'X\x03\x00\x00',
  1192. b'X\x03\x00\x00\x00',
  1193. b'X\x03\x00\x00\x00ab',
  1194. b'(c', # GLOBAL
  1195. b'(cbuiltins',
  1196. b'(cbuiltins\n',
  1197. b'(cbuiltins\nlist',
  1198. b'Ng', # GET
  1199. b'Ng0',
  1200. b'(i', # INST
  1201. b'(ibuiltins',
  1202. b'(ibuiltins\n',
  1203. b'(ibuiltins\nlist',
  1204. b'Nh', # BINGET
  1205. b'Nj', # LONG_BINGET
  1206. b'Nj\x00\x00\x00',
  1207. b'Np', # PUT
  1208. b'Np0',
  1209. b'Nq', # BINPUT
  1210. b'Nr', # LONG_BINPUT
  1211. b'Nr\x00\x00\x00',
  1212. b'\x80', # PROTO
  1213. b'\x82', # EXT1
  1214. b'\x83', # EXT2
  1215. b'\x84\x01',
  1216. b'\x84', # EXT4
  1217. b'\x84\x01\x00\x00',
  1218. b'\x8a', # LONG1
  1219. b'\x8b', # LONG4
  1220. b'\x8b\x00\x00\x00',
  1221. b'\x8c', # SHORT_BINUNICODE
  1222. b'\x8c\x03',
  1223. b'\x8c\x03ab',
  1224. b'\x8d', # BINUNICODE8
  1225. b'\x8d\x03\x00\x00\x00\x00\x00\x00',
  1226. b'\x8d\x03\x00\x00\x00\x00\x00\x00\x00',
  1227. b'\x8d\x03\x00\x00\x00\x00\x00\x00\x00ab',
  1228. b'\x8e', # BINBYTES8
  1229. b'\x8e\x03\x00\x00\x00\x00\x00\x00',
  1230. b'\x8e\x03\x00\x00\x00\x00\x00\x00\x00',
  1231. b'\x8e\x03\x00\x00\x00\x00\x00\x00\x00ab',
  1232. b'\x96', # BYTEARRAY8
  1233. b'\x96\x03\x00\x00\x00\x00\x00\x00',
  1234. b'\x96\x03\x00\x00\x00\x00\x00\x00\x00',
  1235. b'\x96\x03\x00\x00\x00\x00\x00\x00\x00ab',
  1236. b'\x95', # FRAME
  1237. b'\x95\x02\x00\x00\x00\x00\x00\x00',
  1238. b'\x95\x02\x00\x00\x00\x00\x00\x00\x00',
  1239. b'\x95\x02\x00\x00\x00\x00\x00\x00\x00N',
  1240. ]
  1241. for p in badpickles:
  1242. self.check_unpickling_error(self.truncated_errors, p)
  1243. @threading_helper.reap_threads
  1244. @threading_helper.requires_working_threading()
  1245. def test_unpickle_module_race(self):
  1246. # https://bugs.python.org/issue34572
  1247. locker_module = dedent("""
  1248. import threading
  1249. barrier = threading.Barrier(2)
  1250. """)
  1251. locking_import_module = dedent("""
  1252. import locker
  1253. locker.barrier.wait()
  1254. class ToBeUnpickled(object):
  1255. pass
  1256. """)
  1257. os.mkdir(TESTFN)
  1258. self.addCleanup(shutil.rmtree, TESTFN)
  1259. sys.path.insert(0, TESTFN)
  1260. self.addCleanup(sys.path.remove, TESTFN)
  1261. with open(os.path.join(TESTFN, "locker.py"), "wb") as f:
  1262. f.write(locker_module.encode('utf-8'))
  1263. with open(os.path.join(TESTFN, "locking_import.py"), "wb") as f:
  1264. f.write(locking_import_module.encode('utf-8'))
  1265. self.addCleanup(forget, "locker")
  1266. self.addCleanup(forget, "locking_import")
  1267. import locker
  1268. pickle_bytes = (
  1269. b'\x80\x03clocking_import\nToBeUnpickled\nq\x00)\x81q\x01.')
  1270. # Then try to unpickle two of these simultaneously
  1271. # One of them will cause the module import, and we want it to block
  1272. # until the other one either:
  1273. # - fails (before the patch for this issue)
  1274. # - blocks on the import lock for the module, as it should
  1275. results = []
  1276. barrier = threading.Barrier(3)
  1277. def t():
  1278. # This ensures the threads have all started
  1279. # presumably barrier release is faster than thread startup
  1280. barrier.wait()
  1281. results.append(pickle.loads(pickle_bytes))
  1282. t1 = threading.Thread(target=t)
  1283. t2 = threading.Thread(target=t)
  1284. t1.start()
  1285. t2.start()
  1286. barrier.wait()
  1287. # could have delay here
  1288. locker.barrier.wait()
  1289. t1.join()
  1290. t2.join()
  1291. from locking_import import ToBeUnpickled
  1292. self.assertEqual(
  1293. [type(x) for x in results],
  1294. [ToBeUnpickled] * 2)
  1295. class AbstractPickleTests:
  1296. # Subclass must define self.dumps, self.loads.
  1297. optimized = False
  1298. _testdata = AbstractUnpickleTests._testdata
  1299. def setUp(self):
  1300. pass
  1301. assert_is_copy = AbstractUnpickleTests.assert_is_copy
  1302. def test_misc(self):
  1303. # test various datatypes not tested by testdata
  1304. for proto in protocols:
  1305. x = myint(4)
  1306. s = self.dumps(x, proto)
  1307. y = self.loads(s)
  1308. self.assert_is_copy(x, y)
  1309. x = (1, ())
  1310. s = self.dumps(x, proto)
  1311. y = self.loads(s)
  1312. self.assert_is_copy(x, y)
  1313. x = initarg(1, x)
  1314. s = self.dumps(x, proto)
  1315. y = self.loads(s)
  1316. self.assert_is_copy(x, y)
  1317. # XXX test __reduce__ protocol?
  1318. def test_roundtrip_equality(self):
  1319. expected = self._testdata
  1320. for proto in protocols:
  1321. s = self.dumps(expected, proto)
  1322. got = self.loads(s)
  1323. self.assert_is_copy(expected, got)
  1324. # There are gratuitous differences between pickles produced by
  1325. # pickle and cPickle, largely because cPickle starts PUT indices at
  1326. # 1 and pickle starts them at 0. See XXX comment in cPickle's put2() --
  1327. # there's a comment with an exclamation point there whose meaning
  1328. # is a mystery. cPickle also suppresses PUT for objects with a refcount
  1329. # of 1.
  1330. def dont_test_disassembly(self):
  1331. from io import StringIO
  1332. from pickletools import dis
  1333. for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS):
  1334. s = self.dumps(self._testdata, proto)
  1335. filelike = StringIO()
  1336. dis(s, out=filelike)
  1337. got = filelike.getvalue()
  1338. self.assertEqual(expected, got)
  1339. def _test_recursive_list(self, cls, aslist=identity, minprotocol=0):
  1340. # List containing itself.
  1341. l = cls()
  1342. l.append(l)
  1343. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1344. s = self.dumps(l, proto)
  1345. x = self.loads(s)
  1346. self.assertIsInstance(x, cls)
  1347. y = aslist(x)
  1348. self.assertEqual(len(y), 1)
  1349. self.assertIs(y[0], x)
  1350. def test_recursive_list(self):
  1351. self._test_recursive_list(list)
  1352. def test_recursive_list_subclass(self):
  1353. self._test_recursive_list(MyList, minprotocol=2)
  1354. def test_recursive_list_like(self):
  1355. self._test_recursive_list(REX_six, aslist=lambda x: x.items)
  1356. def _test_recursive_tuple_and_list(self, cls, aslist=identity, minprotocol=0):
  1357. # Tuple containing a list containing the original tuple.
  1358. t = (cls(),)
  1359. t[0].append(t)
  1360. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1361. s = self.dumps(t, proto)
  1362. x = self.loads(s)
  1363. self.assertIsInstance(x, tuple)
  1364. self.assertEqual(len(x), 1)
  1365. self.assertIsInstance(x[0], cls)
  1366. y = aslist(x[0])
  1367. self.assertEqual(len(y), 1)
  1368. self.assertIs(y[0], x)
  1369. # List containing a tuple containing the original list.
  1370. t, = t
  1371. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1372. s = self.dumps(t, proto)
  1373. x = self.loads(s)
  1374. self.assertIsInstance(x, cls)
  1375. y = aslist(x)
  1376. self.assertEqual(len(y), 1)
  1377. self.assertIsInstance(y[0], tuple)
  1378. self.assertEqual(len(y[0]), 1)
  1379. self.assertIs(y[0][0], x)
  1380. def test_recursive_tuple_and_list(self):
  1381. self._test_recursive_tuple_and_list(list)
  1382. def test_recursive_tuple_and_list_subclass(self):
  1383. self._test_recursive_tuple_and_list(MyList, minprotocol=2)
  1384. def test_recursive_tuple_and_list_like(self):
  1385. self._test_recursive_tuple_and_list(REX_six, aslist=lambda x: x.items)
  1386. def _test_recursive_dict(self, cls, asdict=identity, minprotocol=0):
  1387. # Dict containing itself.
  1388. d = cls()
  1389. d[1] = d
  1390. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1391. s = self.dumps(d, proto)
  1392. x = self.loads(s)
  1393. self.assertIsInstance(x, cls)
  1394. y = asdict(x)
  1395. self.assertEqual(list(y.keys()), [1])
  1396. self.assertIs(y[1], x)
  1397. def test_recursive_dict(self):
  1398. self._test_recursive_dict(dict)
  1399. def test_recursive_dict_subclass(self):
  1400. self._test_recursive_dict(MyDict, minprotocol=2)
  1401. def test_recursive_dict_like(self):
  1402. self._test_recursive_dict(REX_seven, asdict=lambda x: x.table)
  1403. def _test_recursive_tuple_and_dict(self, cls, asdict=identity, minprotocol=0):
  1404. # Tuple containing a dict containing the original tuple.
  1405. t = (cls(),)
  1406. t[0][1] = t
  1407. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1408. s = self.dumps(t, proto)
  1409. x = self.loads(s)
  1410. self.assertIsInstance(x, tuple)
  1411. self.assertEqual(len(x), 1)
  1412. self.assertIsInstance(x[0], cls)
  1413. y = asdict(x[0])
  1414. self.assertEqual(list(y), [1])
  1415. self.assertIs(y[1], x)
  1416. # Dict containing a tuple containing the original dict.
  1417. t, = t
  1418. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1419. s = self.dumps(t, proto)
  1420. x = self.loads(s)
  1421. self.assertIsInstance(x, cls)
  1422. y = asdict(x)
  1423. self.assertEqual(list(y), [1])
  1424. self.assertIsInstance(y[1], tuple)
  1425. self.assertEqual(len(y[1]), 1)
  1426. self.assertIs(y[1][0], x)
  1427. def test_recursive_tuple_and_dict(self):
  1428. self._test_recursive_tuple_and_dict(dict)
  1429. def test_recursive_tuple_and_dict_subclass(self):
  1430. self._test_recursive_tuple_and_dict(MyDict, minprotocol=2)
  1431. def test_recursive_tuple_and_dict_like(self):
  1432. self._test_recursive_tuple_and_dict(REX_seven, asdict=lambda x: x.table)
  1433. def _test_recursive_dict_key(self, cls, asdict=identity, minprotocol=0):
  1434. # Dict containing an immutable object (as key) containing the original
  1435. # dict.
  1436. d = cls()
  1437. d[K(d)] = 1
  1438. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1439. s = self.dumps(d, proto)
  1440. x = self.loads(s)
  1441. self.assertIsInstance(x, cls)
  1442. y = asdict(x)
  1443. self.assertEqual(len(y.keys()), 1)
  1444. self.assertIsInstance(list(y.keys())[0], K)
  1445. self.assertIs(list(y.keys())[0].value, x)
  1446. def test_recursive_dict_key(self):
  1447. self._test_recursive_dict_key(dict)
  1448. def test_recursive_dict_subclass_key(self):
  1449. self._test_recursive_dict_key(MyDict, minprotocol=2)
  1450. def test_recursive_dict_like_key(self):
  1451. self._test_recursive_dict_key(REX_seven, asdict=lambda x: x.table)
  1452. def _test_recursive_tuple_and_dict_key(self, cls, asdict=identity, minprotocol=0):
  1453. # Tuple containing a dict containing an immutable object (as key)
  1454. # containing the original tuple.
  1455. t = (cls(),)
  1456. t[0][K(t)] = 1
  1457. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1458. s = self.dumps(t, proto)
  1459. x = self.loads(s)
  1460. self.assertIsInstance(x, tuple)
  1461. self.assertEqual(len(x), 1)
  1462. self.assertIsInstance(x[0], cls)
  1463. y = asdict(x[0])
  1464. self.assertEqual(len(y), 1)
  1465. self.assertIsInstance(list(y.keys())[0], K)
  1466. self.assertIs(list(y.keys())[0].value, x)
  1467. # Dict containing an immutable object (as key) containing a tuple
  1468. # containing the original dict.
  1469. t, = t
  1470. for proto in range(minprotocol, pickle.HIGHEST_PROTOCOL + 1):
  1471. s = self.dumps(t, proto)
  1472. x = self.loads(s)
  1473. self.assertIsInstance(x, cls)
  1474. y = asdict(x)
  1475. self.assertEqual(len(y), 1)
  1476. self.assertIsInstance(list(y.keys())[0], K)
  1477. self.assertIs(list(y.keys())[0].value[0], x)
  1478. def test_recursive_tuple_and_dict_key(self):
  1479. self._test_recursive_tuple_and_dict_key(dict)
  1480. def test_recursive_tuple_and_dict_subclass_key(self):
  1481. self._test_recursive_tuple_and_dict_key(MyDict, minprotocol=2)
  1482. def test_recursive_tuple_and_dict_like_key(self):
  1483. self._test_recursive_tuple_and_dict_key(REX_seven, asdict=lambda x: x.table)
  1484. def test_recursive_set(self):
  1485. # Set containing an immutable object containing the original set.
  1486. y = set()
  1487. y.add(K(y))
  1488. for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
  1489. s = self.dumps(y, proto)
  1490. x = self.loads(s)
  1491. self.assertIsInstance(x, set)
  1492. self.assertEqual(len(x), 1)
  1493. self.assertIsInstance(list(x)[0], K)
  1494. self.assertIs(list(x)[0].value, x)
  1495. # Immutable object containing a set containing the original object.
  1496. y, = y
  1497. for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
  1498. s = self.dumps(y, proto)
  1499. x = self.loads(s)
  1500. self.assertIsInstance(x, K)
  1501. self.assertIsInstance(x.value, set)
  1502. self.assertEqual(len(x.value), 1)
  1503. self.assertIs(list(x.value)[0], x)
  1504. def test_recursive_inst(self):
  1505. # Mutable object containing itself.
  1506. i = Object()
  1507. i.attr = i
  1508. for proto in protocols:
  1509. s = self.dumps(i, proto)
  1510. x = self.loads(s)
  1511. self.assertIsInstance(x, Object)
  1512. self.assertEqual(dir(x), dir(i))
  1513. self.assertIs(x.attr, x)
  1514. def test_recursive_multi(self):
  1515. l = []
  1516. d = {1:l}
  1517. i = Object()
  1518. i.attr = d
  1519. l.append(i)
  1520. for proto in protocols:
  1521. s = self.dumps(l, proto)
  1522. x = self.loads(s)
  1523. self.assertIsInstance(x, list)
  1524. self.assertEqual(len(x), 1)
  1525. self.assertEqual(dir(x[0]), dir(i))
  1526. self.assertEqual(list(x[0].attr.keys()), [1])
  1527. self.assertIs(x[0].attr[1], x)
  1528. def _test_recursive_collection_and_inst(self, factory):
  1529. # Mutable object containing a collection containing the original
  1530. # object.
  1531. o = Object()
  1532. o.attr = factory([o])
  1533. t = type(o.attr)
  1534. for proto in protocols:
  1535. s = self.dumps(o, proto)
  1536. x = self.loads(s)
  1537. self.assertIsInstance(x.attr, t)
  1538. self.assertEqual(len(x.attr), 1)
  1539. self.assertIsInstance(list(x.attr)[0], Object)
  1540. self.assertIs(list(x.attr)[0], x)
  1541. # Collection containing a mutable object containing the original
  1542. # collection.
  1543. o = o.attr
  1544. for proto in protocols:
  1545. s = self.dumps(o, proto)
  1546. x = self.loads(s)
  1547. self.assertIsInstance(x, t)
  1548. self.assertEqual(len(x), 1)
  1549. self.assertIsInstance(list(x)[0], Object)
  1550. self.assertIs(list(x)[0].attr, x)
  1551. def test_recursive_list_and_inst(self):
  1552. self._test_recursive_collection_and_inst(list)
  1553. def test_recursive_tuple_and_inst(self):
  1554. self._test_recursive_collection_and_inst(tuple)
  1555. def test_recursive_dict_and_inst(self):
  1556. self._test_recursive_collection_and_inst(dict.fromkeys)
  1557. def test_recursive_set_and_inst(self):
  1558. self._test_recursive_collection_and_inst(set)
  1559. def test_recursive_frozenset_and_inst(self):
  1560. self._test_recursive_collection_and_inst(frozenset)
  1561. def test_recursive_list_subclass_and_inst(self):
  1562. self._test_recursive_collection_and_inst(MyList)
  1563. def test_recursive_tuple_subclass_and_inst(self):
  1564. self._test_recursive_collection_and_inst(MyTuple)
  1565. def test_recursive_dict_subclass_and_inst(self):
  1566. self._test_recursive_collection_and_inst(MyDict.fromkeys)
  1567. def test_recursive_set_subclass_and_inst(self):
  1568. self._test_recursive_collection_and_inst(MySet)
  1569. def test_recursive_frozenset_subclass_and_inst(self):
  1570. self._test_recursive_collection_and_inst(MyFrozenSet)
  1571. def test_recursive_inst_state(self):
  1572. # Mutable object containing itself.
  1573. y = REX_state()
  1574. y.state = y
  1575. for proto in protocols:
  1576. s = self.dumps(y, proto)
  1577. x = self.loads(s)
  1578. self.assertIsInstance(x, REX_state)
  1579. self.assertIs(x.state, x)
  1580. def test_recursive_tuple_and_inst_state(self):
  1581. # Tuple containing a mutable object containing the original tuple.
  1582. t = (REX_state(),)
  1583. t[0].state = t
  1584. for proto in protocols:
  1585. s = self.dumps(t, proto)
  1586. x = self.loads(s)
  1587. self.assertIsInstance(x, tuple)
  1588. self.assertEqual(len(x), 1)
  1589. self.assertIsInstance(x[0], REX_state)
  1590. self.assertIs(x[0].state, x)
  1591. # Mutable object containing a tuple containing the object.
  1592. t, = t
  1593. for proto in protocols:
  1594. s = self.dumps(t, proto)
  1595. x = self.loads(s)
  1596. self.assertIsInstance(x, REX_state)
  1597. self.assertIsInstance(x.state, tuple)
  1598. self.assertEqual(len(x.state), 1)
  1599. self.assertIs(x.state[0], x)
  1600. def test_unicode(self):
  1601. endcases = ['', '<\\u>', '<\\\u1234>', '<\n>',
  1602. '<\\>', '<\\\U00012345>',
  1603. # surrogates
  1604. '<\udc80>']
  1605. for proto in protocols:
  1606. for u in endcases:
  1607. p = self.dumps(u, proto)
  1608. u2 = self.loads(p)
  1609. self.assert_is_copy(u, u2)
  1610. def test_unicode_high_plane(self):
  1611. t = '\U00012345'
  1612. for proto in protocols:
  1613. p = self.dumps(t, proto)
  1614. t2 = self.loads(p)
  1615. self.assert_is_copy(t, t2)
  1616. def test_bytes(self):
  1617. for proto in protocols:
  1618. for s in b'', b'xyz', b'xyz'*100:
  1619. p = self.dumps(s, proto)
  1620. self.assert_is_copy(s, self.loads(p))
  1621. for s in [bytes([i]) for i in range(256)]:
  1622. p = self.dumps(s, proto)
  1623. self.assert_is_copy(s, self.loads(p))
  1624. for s in [bytes([i, i]) for i in range(256)]:
  1625. p = self.dumps(s, proto)
  1626. self.assert_is_copy(s, self.loads(p))
  1627. def test_bytearray(self):
  1628. for proto in protocols:
  1629. for s in b'', b'xyz', b'xyz'*100:
  1630. b = bytearray(s)
  1631. p = self.dumps(b, proto)
  1632. bb = self.loads(p)
  1633. self.assertIsNot(bb, b)
  1634. self.assert_is_copy(b, bb)
  1635. if proto <= 3:
  1636. # bytearray is serialized using a global reference
  1637. self.assertIn(b'bytearray', p)
  1638. self.assertTrue(opcode_in_pickle(pickle.GLOBAL, p))
  1639. elif proto == 4:
  1640. self.assertIn(b'bytearray', p)
  1641. self.assertTrue(opcode_in_pickle(pickle.STACK_GLOBAL, p))
  1642. elif proto == 5:
  1643. self.assertNotIn(b'bytearray', p)
  1644. self.assertTrue(opcode_in_pickle(pickle.BYTEARRAY8, p))
  1645. def test_bytearray_memoization_bug(self):
  1646. for proto in protocols:
  1647. for s in b'', b'xyz', b'xyz'*100:
  1648. b = bytearray(s)
  1649. p = self.dumps((b, b), proto)
  1650. b1, b2 = self.loads(p)
  1651. self.assertIs(b1, b2)
  1652. def test_ints(self):
  1653. for proto in protocols:
  1654. n = sys.maxsize
  1655. while n:
  1656. for expected in (-n, n):
  1657. s = self.dumps(expected, proto)
  1658. n2 = self.loads(s)
  1659. self.assert_is_copy(expected, n2)
  1660. n = n >> 1
  1661. def test_long(self):
  1662. for proto in protocols:
  1663. # 256 bytes is where LONG4 begins.
  1664. for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257:
  1665. nbase = 1 << nbits
  1666. for npos in nbase-1, nbase, nbase+1:
  1667. for n in npos, -npos:
  1668. pickle = self.dumps(n, proto)
  1669. got = self.loads(pickle)
  1670. self.assert_is_copy(n, got)
  1671. # Try a monster. This is quadratic-time in protos 0 & 1, so don't
  1672. # bother with those.
  1673. nbase = int("deadbeeffeedface", 16)
  1674. nbase += nbase << 1000000
  1675. for n in nbase, -nbase:
  1676. p = self.dumps(n, 2)
  1677. got = self.loads(p)
  1678. # assert_is_copy is very expensive here as it precomputes
  1679. # a failure message by computing the repr() of n and got,
  1680. # we just do the check ourselves.
  1681. self.assertIs(type(got), int)
  1682. self.assertEqual(n, got)
  1683. def test_float(self):
  1684. test_values = [0.0, 4.94e-324, 1e-310, 7e-308, 6.626e-34, 0.1, 0.5,
  1685. 3.14, 263.44582062374053, 6.022e23, 1e30]
  1686. test_values = test_values + [-x for x in test_values]
  1687. for proto in protocols:
  1688. for value in test_values:
  1689. pickle = self.dumps(value, proto)
  1690. got = self.loads(pickle)
  1691. self.assert_is_copy(value, got)
  1692. @run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
  1693. def test_float_format(self):
  1694. # make sure that floats are formatted locale independent with proto 0
  1695. self.assertEqual(self.dumps(1.2, 0)[0:3], b'F1.')
  1696. def test_reduce(self):
  1697. for proto in protocols:
  1698. inst = AAA()
  1699. dumped = self.dumps(inst, proto)
  1700. loaded = self.loads(dumped)
  1701. self.assertEqual(loaded, REDUCE_A)
  1702. def test_getinitargs(self):
  1703. for proto in protocols:
  1704. inst = initarg(1, 2)
  1705. dumped = self.dumps(inst, proto)
  1706. loaded = self.loads(dumped)
  1707. self.assert_is_copy(inst, loaded)
  1708. def test_metaclass(self):
  1709. a = use_metaclass()
  1710. for proto in protocols:
  1711. s = self.dumps(a, proto)
  1712. b = self.loads(s)
  1713. self.assertEqual(a.__class__, b.__class__)
  1714. def test_dynamic_class(self):
  1715. a = create_dynamic_class("my_dynamic_class", (object,))
  1716. copyreg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
  1717. for proto in protocols:
  1718. s = self.dumps(a, proto)
  1719. b = self.loads(s)
  1720. self.assertEqual(a, b)
  1721. self.assertIs(type(a), type(b))
  1722. def test_structseq(self):
  1723. import time
  1724. import os
  1725. t = time.localtime()
  1726. for proto in protocols:
  1727. s = self.dumps(t, proto)
  1728. u = self.loads(s)
  1729. self.assert_is_copy(t, u)
  1730. t = os.stat(os.curdir)
  1731. s = self.dumps(t, proto)
  1732. u = self.loads(s)
  1733. self.assert_is_copy(t, u)
  1734. if hasattr(os, "statvfs"):
  1735. t = os.statvfs(os.curdir)
  1736. s = self.dumps(t, proto)
  1737. u = self.loads(s)
  1738. self.assert_is_copy(t, u)
  1739. def test_ellipsis(self):
  1740. for proto in protocols:
  1741. s = self.dumps(..., proto)
  1742. u = self.loads(s)
  1743. self.assertIs(..., u)
  1744. def test_notimplemented(self):
  1745. for proto in protocols:
  1746. s = self.dumps(NotImplemented, proto)
  1747. u = self.loads(s)
  1748. self.assertIs(NotImplemented, u)
  1749. def test_singleton_types(self):
  1750. # Issue #6477: Test that types of built-in singletons can be pickled.
  1751. singletons = [None, ..., NotImplemented]
  1752. for singleton in singletons:
  1753. for proto in protocols:
  1754. s = self.dumps(type(singleton), proto)
  1755. u = self.loads(s)
  1756. self.assertIs(type(singleton), u)
  1757. def test_builtin_types(self):
  1758. for t in builtins.__dict__.values():
  1759. if isinstance(t, type) and not issubclass(t, BaseException):
  1760. for proto in protocols:
  1761. s = self.dumps(t, proto)
  1762. self.assertIs(self.loads(s), t)
  1763. def test_builtin_exceptions(self):
  1764. for t in builtins.__dict__.values():
  1765. if isinstance(t, type) and issubclass(t, BaseException):
  1766. for proto in protocols:
  1767. s = self.dumps(t, proto)
  1768. u = self.loads(s)
  1769. if proto <= 2 and issubclass(t, OSError) and t is not BlockingIOError:
  1770. self.assertIs(u, OSError)
  1771. elif proto <= 2 and issubclass(t, ImportError):
  1772. self.assertIs(u, ImportError)
  1773. else:
  1774. self.assertIs(u, t)
  1775. def test_builtin_functions(self):
  1776. for t in builtins.__dict__.values():
  1777. if isinstance(t, types.BuiltinFunctionType):
  1778. for proto in protocols:
  1779. s = self.dumps(t, proto)
  1780. self.assertIs(self.loads(s), t)
  1781. # Tests for protocol 2
  1782. def test_proto(self):
  1783. for proto in protocols:
  1784. pickled = self.dumps(None, proto)
  1785. if proto >= 2:
  1786. proto_header = pickle.PROTO + bytes([proto])
  1787. self.assertTrue(pickled.startswith(proto_header))
  1788. else:
  1789. self.assertEqual(count_opcode(pickle.PROTO, pickled), 0)
  1790. oob = protocols[-1] + 1 # a future protocol
  1791. build_none = pickle.NONE + pickle.STOP
  1792. badpickle = pickle.PROTO + bytes([oob]) + build_none
  1793. try:
  1794. self.loads(badpickle)
  1795. except ValueError as err:
  1796. self.assertIn("unsupported pickle protocol", str(err))
  1797. else:
  1798. self.fail("expected bad protocol number to raise ValueError")
  1799. def test_long1(self):
  1800. x = 12345678910111213141516178920
  1801. for proto in protocols:
  1802. s = self.dumps(x, proto)
  1803. y = self.loads(s)
  1804. self.assert_is_copy(x, y)
  1805. self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2)
  1806. def test_long4(self):
  1807. x = 12345678910111213141516178920 << (256*8)
  1808. for proto in protocols:
  1809. s = self.dumps(x, proto)
  1810. y = self.loads(s)
  1811. self.assert_is_copy(x, y)
  1812. self.assertEqual(opcode_in_pickle(pickle.LONG4, s), proto >= 2)
  1813. def test_short_tuples(self):
  1814. # Map (proto, len(tuple)) to expected opcode.
  1815. expected_opcode = {(0, 0): pickle.TUPLE,
  1816. (0, 1): pickle.TUPLE,
  1817. (0, 2): pickle.TUPLE,
  1818. (0, 3): pickle.TUPLE,
  1819. (0, 4): pickle.TUPLE,
  1820. (1, 0): pickle.EMPTY_TUPLE,
  1821. (1, 1): pickle.TUPLE,
  1822. (1, 2): pickle.TUPLE,
  1823. (1, 3): pickle.TUPLE,
  1824. (1, 4): pickle.TUPLE,
  1825. (2, 0): pickle.EMPTY_TUPLE,
  1826. (2, 1): pickle.TUPLE1,
  1827. (2, 2): pickle.TUPLE2,
  1828. (2, 3): pickle.TUPLE3,
  1829. (2, 4): pickle.TUPLE,
  1830. (3, 0): pickle.EMPTY_TUPLE,
  1831. (3, 1): pickle.TUPLE1,
  1832. (3, 2): pickle.TUPLE2,
  1833. (3, 3): pickle.TUPLE3,
  1834. (3, 4): pickle.TUPLE,
  1835. }
  1836. a = ()
  1837. b = (1,)
  1838. c = (1, 2)
  1839. d = (1, 2, 3)
  1840. e = (1, 2, 3, 4)
  1841. for proto in protocols:
  1842. for x in a, b, c, d, e:
  1843. s = self.dumps(x, proto)
  1844. y = self.loads(s)
  1845. self.assert_is_copy(x, y)
  1846. expected = expected_opcode[min(proto, 3), len(x)]
  1847. self.assertTrue(opcode_in_pickle(expected, s))
  1848. def test_singletons(self):
  1849. # Map (proto, singleton) to expected opcode.
  1850. expected_opcode = {(0, None): pickle.NONE,
  1851. (1, None): pickle.NONE,
  1852. (2, None): pickle.NONE,
  1853. (3, None): pickle.NONE,
  1854. (0, True): pickle.INT,
  1855. (1, True): pickle.INT,
  1856. (2, True): pickle.NEWTRUE,
  1857. (3, True): pickle.NEWTRUE,
  1858. (0, False): pickle.INT,
  1859. (1, False): pickle.INT,
  1860. (2, False): pickle.NEWFALSE,
  1861. (3, False): pickle.NEWFALSE,
  1862. }
  1863. for proto in protocols:
  1864. for x in None, False, True:
  1865. s = self.dumps(x, proto)
  1866. y = self.loads(s)
  1867. self.assertTrue(x is y, (proto, x, s, y))
  1868. expected = expected_opcode[min(proto, 3), x]
  1869. self.assertTrue(opcode_in_pickle(expected, s))
  1870. def test_newobj_tuple(self):
  1871. x = MyTuple([1, 2, 3])
  1872. x.foo = 42
  1873. x.bar = "hello"
  1874. for proto in protocols:
  1875. s = self.dumps(x, proto)
  1876. y = self.loads(s)
  1877. self.assert_is_copy(x, y)
  1878. def test_newobj_list(self):
  1879. x = MyList([1, 2, 3])
  1880. x.foo = 42
  1881. x.bar = "hello"
  1882. for proto in protocols:
  1883. s = self.dumps(x, proto)
  1884. y = self.loads(s)
  1885. self.assert_is_copy(x, y)
  1886. def test_newobj_generic(self):
  1887. for proto in protocols:
  1888. for C in myclasses:
  1889. B = C.__base__
  1890. x = C(C.sample)
  1891. x.foo = 42
  1892. s = self.dumps(x, proto)
  1893. y = self.loads(s)
  1894. detail = (proto, C, B, x, y, type(y))
  1895. self.assert_is_copy(x, y) # XXX revisit
  1896. self.assertEqual(B(x), B(y), detail)
  1897. self.assertEqual(x.__dict__, y.__dict__, detail)
  1898. def test_newobj_proxies(self):
  1899. # NEWOBJ should use the __class__ rather than the raw type
  1900. classes = myclasses[:]
  1901. # Cannot create weakproxies to these classes
  1902. for c in (MyInt, MyTuple):
  1903. classes.remove(c)
  1904. for proto in protocols:
  1905. for C in classes:
  1906. B = C.__base__
  1907. x = C(C.sample)
  1908. x.foo = 42
  1909. p = weakref.proxy(x)
  1910. s = self.dumps(p, proto)
  1911. y = self.loads(s)
  1912. self.assertEqual(type(y), type(x)) # rather than type(p)
  1913. detail = (proto, C, B, x, y, type(y))
  1914. self.assertEqual(B(x), B(y), detail)
  1915. self.assertEqual(x.__dict__, y.__dict__, detail)
  1916. def test_newobj_overridden_new(self):
  1917. # Test that Python class with C implemented __new__ is pickleable
  1918. for proto in protocols:
  1919. x = MyIntWithNew2(1)
  1920. x.foo = 42
  1921. s = self.dumps(x, proto)
  1922. y = self.loads(s)
  1923. self.assertIs(type(y), MyIntWithNew2)
  1924. self.assertEqual(int(y), 1)
  1925. self.assertEqual(y.foo, 42)
  1926. def test_newobj_not_class(self):
  1927. # Issue 24552
  1928. global SimpleNewObj
  1929. save = SimpleNewObj
  1930. o = SimpleNewObj.__new__(SimpleNewObj)
  1931. b = self.dumps(o, 4)
  1932. try:
  1933. SimpleNewObj = 42
  1934. self.assertRaises((TypeError, pickle.UnpicklingError), self.loads, b)
  1935. finally:
  1936. SimpleNewObj = save
  1937. # Register a type with copyreg, with extension code extcode. Pickle
  1938. # an object of that type. Check that the resulting pickle uses opcode
  1939. # (EXT[124]) under proto 2, and not in proto 1.
  1940. def produce_global_ext(self, extcode, opcode):
  1941. e = ExtensionSaver(extcode)
  1942. try:
  1943. copyreg.add_extension(__name__, "MyList", extcode)
  1944. x = MyList([1, 2, 3])
  1945. x.foo = 42
  1946. x.bar = "hello"
  1947. # Dump using protocol 1 for comparison.
  1948. s1 = self.dumps(x, 1)
  1949. self.assertIn(__name__.encode("utf-8"), s1)
  1950. self.assertIn(b"MyList", s1)
  1951. self.assertFalse(opcode_in_pickle(opcode, s1))
  1952. y = self.loads(s1)
  1953. self.assert_is_copy(x, y)
  1954. # Dump using protocol 2 for test.
  1955. s2 = self.dumps(x, 2)
  1956. self.assertNotIn(__name__.encode("utf-8"), s2)
  1957. self.assertNotIn(b"MyList", s2)
  1958. self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2))
  1959. y = self.loads(s2)
  1960. self.assert_is_copy(x, y)
  1961. finally:
  1962. e.restore()
  1963. def test_global_ext1(self):
  1964. self.produce_global_ext(0x00000001, pickle.EXT1) # smallest EXT1 code
  1965. self.produce_global_ext(0x000000ff, pickle.EXT1) # largest EXT1 code
  1966. def test_global_ext2(self):
  1967. self.produce_global_ext(0x00000100, pickle.EXT2) # smallest EXT2 code
  1968. self.produce_global_ext(0x0000ffff, pickle.EXT2) # largest EXT2 code
  1969. self.produce_global_ext(0x0000abcd, pickle.EXT2) # check endianness
  1970. def test_global_ext4(self):
  1971. self.produce_global_ext(0x00010000, pickle.EXT4) # smallest EXT4 code
  1972. self.produce_global_ext(0x7fffffff, pickle.EXT4) # largest EXT4 code
  1973. self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness
  1974. def test_list_chunking(self):
  1975. n = 10 # too small to chunk
  1976. x = list(range(n))
  1977. for proto in protocols:
  1978. s = self.dumps(x, proto)
  1979. y = self.loads(s)
  1980. self.assert_is_copy(x, y)
  1981. num_appends = count_opcode(pickle.APPENDS, s)
  1982. self.assertEqual(num_appends, proto > 0)
  1983. n = 2500 # expect at least two chunks when proto > 0
  1984. x = list(range(n))
  1985. for proto in protocols:
  1986. s = self.dumps(x, proto)
  1987. y = self.loads(s)
  1988. self.assert_is_copy(x, y)
  1989. num_appends = count_opcode(pickle.APPENDS, s)
  1990. if proto == 0:
  1991. self.assertEqual(num_appends, 0)
  1992. else:
  1993. self.assertTrue(num_appends >= 2)
  1994. def test_dict_chunking(self):
  1995. n = 10 # too small to chunk
  1996. x = dict.fromkeys(range(n))
  1997. for proto in protocols:
  1998. s = self.dumps(x, proto)
  1999. self.assertIsInstance(s, bytes_types)
  2000. y = self.loads(s)
  2001. self.assert_is_copy(x, y)
  2002. num_setitems = count_opcode(pickle.SETITEMS, s)
  2003. self.assertEqual(num_setitems, proto > 0)
  2004. n = 2500 # expect at least two chunks when proto > 0
  2005. x = dict.fromkeys(range(n))
  2006. for proto in protocols:
  2007. s = self.dumps(x, proto)
  2008. y = self.loads(s)
  2009. self.assert_is_copy(x, y)
  2010. num_setitems = count_opcode(pickle.SETITEMS, s)
  2011. if proto == 0:
  2012. self.assertEqual(num_setitems, 0)
  2013. else:
  2014. self.assertTrue(num_setitems >= 2)
  2015. def test_set_chunking(self):
  2016. n = 10 # too small to chunk
  2017. x = set(range(n))
  2018. for proto in protocols:
  2019. s = self.dumps(x, proto)
  2020. y = self.loads(s)
  2021. self.assert_is_copy(x, y)
  2022. num_additems = count_opcode(pickle.ADDITEMS, s)
  2023. if proto < 4:
  2024. self.assertEqual(num_additems, 0)
  2025. else:
  2026. self.assertEqual(num_additems, 1)
  2027. n = 2500 # expect at least two chunks when proto >= 4
  2028. x = set(range(n))
  2029. for proto in protocols:
  2030. s = self.dumps(x, proto)
  2031. y = self.loads(s)
  2032. self.assert_is_copy(x, y)
  2033. num_additems = count_opcode(pickle.ADDITEMS, s)
  2034. if proto < 4:
  2035. self.assertEqual(num_additems, 0)
  2036. else:
  2037. self.assertGreaterEqual(num_additems, 2)
  2038. def test_simple_newobj(self):
  2039. x = SimpleNewObj.__new__(SimpleNewObj, 0xface) # avoid __init__
  2040. x.abc = 666
  2041. for proto in protocols:
  2042. with self.subTest(proto=proto):
  2043. s = self.dumps(x, proto)
  2044. if proto < 1:
  2045. self.assertIn(b'\nI64206', s) # INT
  2046. else:
  2047. self.assertIn(b'M\xce\xfa', s) # BININT2
  2048. self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s),
  2049. 2 <= proto)
  2050. self.assertFalse(opcode_in_pickle(pickle.NEWOBJ_EX, s))
  2051. y = self.loads(s) # will raise TypeError if __init__ called
  2052. self.assert_is_copy(x, y)
  2053. def test_complex_newobj(self):
  2054. x = ComplexNewObj.__new__(ComplexNewObj, 0xface) # avoid __init__
  2055. x.abc = 666
  2056. for proto in protocols:
  2057. with self.subTest(proto=proto):
  2058. s = self.dumps(x, proto)
  2059. if proto < 1:
  2060. self.assertIn(b'\nI64206', s) # INT
  2061. elif proto < 2:
  2062. self.assertIn(b'M\xce\xfa', s) # BININT2
  2063. elif proto < 4:
  2064. self.assertIn(b'X\x04\x00\x00\x00FACE', s) # BINUNICODE
  2065. else:
  2066. self.assertIn(b'\x8c\x04FACE', s) # SHORT_BINUNICODE
  2067. self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s),
  2068. 2 <= proto)
  2069. self.assertFalse(opcode_in_pickle(pickle.NEWOBJ_EX, s))
  2070. y = self.loads(s) # will raise TypeError if __init__ called
  2071. self.assert_is_copy(x, y)
  2072. def test_complex_newobj_ex(self):
  2073. x = ComplexNewObjEx.__new__(ComplexNewObjEx, 0xface) # avoid __init__
  2074. x.abc = 666
  2075. for proto in protocols:
  2076. with self.subTest(proto=proto):
  2077. s = self.dumps(x, proto)
  2078. if proto < 1:
  2079. self.assertIn(b'\nI64206', s) # INT
  2080. elif proto < 2:
  2081. self.assertIn(b'M\xce\xfa', s) # BININT2
  2082. elif proto < 4:
  2083. self.assertIn(b'X\x04\x00\x00\x00FACE', s) # BINUNICODE
  2084. else:
  2085. self.assertIn(b'\x8c\x04FACE', s) # SHORT_BINUNICODE
  2086. self.assertFalse(opcode_in_pickle(pickle.NEWOBJ, s))
  2087. self.assertEqual(opcode_in_pickle(pickle.NEWOBJ_EX, s),
  2088. 4 <= proto)
  2089. y = self.loads(s) # will raise TypeError if __init__ called
  2090. self.assert_is_copy(x, y)
  2091. def test_newobj_list_slots(self):
  2092. x = SlotList([1, 2, 3])
  2093. x.foo = 42
  2094. x.bar = "hello"
  2095. s = self.dumps(x, 2)
  2096. y = self.loads(s)
  2097. self.assert_is_copy(x, y)
  2098. def test_reduce_overrides_default_reduce_ex(self):
  2099. for proto in protocols:
  2100. x = REX_one()
  2101. self.assertEqual(x._reduce_called, 0)
  2102. s = self.dumps(x, proto)
  2103. self.assertEqual(x._reduce_called, 1)
  2104. y = self.loads(s)
  2105. self.assertEqual(y._reduce_called, 0)
  2106. def test_reduce_ex_called(self):
  2107. for proto in protocols:
  2108. x = REX_two()
  2109. self.assertEqual(x._proto, None)
  2110. s = self.dumps(x, proto)
  2111. self.assertEqual(x._proto, proto)
  2112. y = self.loads(s)
  2113. self.assertEqual(y._proto, None)
  2114. def test_reduce_ex_overrides_reduce(self):
  2115. for proto in protocols:
  2116. x = REX_three()
  2117. self.assertEqual(x._proto, None)
  2118. s = self.dumps(x, proto)
  2119. self.assertEqual(x._proto, proto)
  2120. y = self.loads(s)
  2121. self.assertEqual(y._proto, None)
  2122. def test_reduce_ex_calls_base(self):
  2123. for proto in protocols:
  2124. x = REX_four()
  2125. self.assertEqual(x._proto, None)
  2126. s = self.dumps(x, proto)
  2127. self.assertEqual(x._proto, proto)
  2128. y = self.loads(s)
  2129. self.assertEqual(y._proto, proto)
  2130. def test_reduce_calls_base(self):
  2131. for proto in protocols:
  2132. x = REX_five()
  2133. self.assertEqual(x._reduce_called, 0)
  2134. s = self.dumps(x, proto)
  2135. self.assertEqual(x._reduce_called, 1)
  2136. y = self.loads(s)
  2137. self.assertEqual(y._reduce_called, 1)
  2138. @no_tracing
  2139. def test_bad_getattr(self):
  2140. # Issue #3514: crash when there is an infinite loop in __getattr__
  2141. x = BadGetattr()
  2142. for proto in range(2):
  2143. with support.infinite_recursion():
  2144. self.assertRaises(RuntimeError, self.dumps, x, proto)
  2145. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  2146. s = self.dumps(x, proto)
  2147. def test_reduce_bad_iterator(self):
  2148. # Issue4176: crash when 4th and 5th items of __reduce__()
  2149. # are not iterators
  2150. class C(object):
  2151. def __reduce__(self):
  2152. # 4th item is not an iterator
  2153. return list, (), None, [], None
  2154. class D(object):
  2155. def __reduce__(self):
  2156. # 5th item is not an iterator
  2157. return dict, (), None, None, []
  2158. # Python implementation is less strict and also accepts iterables.
  2159. for proto in protocols:
  2160. try:
  2161. self.dumps(C(), proto)
  2162. except pickle.PicklingError:
  2163. pass
  2164. try:
  2165. self.dumps(D(), proto)
  2166. except pickle.PicklingError:
  2167. pass
  2168. def test_many_puts_and_gets(self):
  2169. # Test that internal data structures correctly deal with lots of
  2170. # puts/gets.
  2171. keys = ("aaa" + str(i) for i in range(100))
  2172. large_dict = dict((k, [4, 5, 6]) for k in keys)
  2173. obj = [dict(large_dict), dict(large_dict), dict(large_dict)]
  2174. for proto in protocols:
  2175. with self.subTest(proto=proto):
  2176. dumped = self.dumps(obj, proto)
  2177. loaded = self.loads(dumped)
  2178. self.assert_is_copy(obj, loaded)
  2179. def test_attribute_name_interning(self):
  2180. # Test that attribute names of pickled objects are interned when
  2181. # unpickling.
  2182. for proto in protocols:
  2183. x = C()
  2184. x.foo = 42
  2185. x.bar = "hello"
  2186. s = self.dumps(x, proto)
  2187. y = self.loads(s)
  2188. x_keys = sorted(x.__dict__)
  2189. y_keys = sorted(y.__dict__)
  2190. for x_key, y_key in zip(x_keys, y_keys):
  2191. self.assertIs(x_key, y_key)
  2192. def test_pickle_to_2x(self):
  2193. # Pickle non-trivial data with protocol 2, expecting that it yields
  2194. # the same result as Python 2.x did.
  2195. # NOTE: this test is a bit too strong since we can produce different
  2196. # bytecode that 2.x will still understand.
  2197. dumped = self.dumps(range(5), 2)
  2198. self.assertEqual(dumped, DATA_XRANGE)
  2199. dumped = self.dumps(set([3]), 2)
  2200. self.assertEqual(dumped, DATA_SET2)
  2201. def test_large_pickles(self):
  2202. # Test the correctness of internal buffering routines when handling
  2203. # large data.
  2204. for proto in protocols:
  2205. data = (1, min, b'xy' * (30 * 1024), len)
  2206. dumped = self.dumps(data, proto)
  2207. loaded = self.loads(dumped)
  2208. self.assertEqual(len(loaded), len(data))
  2209. self.assertEqual(loaded, data)
  2210. def test_int_pickling_efficiency(self):
  2211. # Test compacity of int representation (see issue #12744)
  2212. for proto in protocols:
  2213. with self.subTest(proto=proto):
  2214. pickles = [self.dumps(2**n, proto) for n in range(70)]
  2215. sizes = list(map(len, pickles))
  2216. # the size function is monotonic
  2217. self.assertEqual(sorted(sizes), sizes)
  2218. if proto >= 2:
  2219. for p in pickles:
  2220. self.assertFalse(opcode_in_pickle(pickle.LONG, p))
  2221. def _check_pickling_with_opcode(self, obj, opcode, proto):
  2222. pickled = self.dumps(obj, proto)
  2223. self.assertTrue(opcode_in_pickle(opcode, pickled))
  2224. unpickled = self.loads(pickled)
  2225. self.assertEqual(obj, unpickled)
  2226. def test_appends_on_non_lists(self):
  2227. # Issue #17720
  2228. obj = REX_six([1, 2, 3])
  2229. for proto in protocols:
  2230. if proto == 0:
  2231. self._check_pickling_with_opcode(obj, pickle.APPEND, proto)
  2232. else:
  2233. self._check_pickling_with_opcode(obj, pickle.APPENDS, proto)
  2234. def test_setitems_on_non_dicts(self):
  2235. obj = REX_seven({1: -1, 2: -2, 3: -3})
  2236. for proto in protocols:
  2237. if proto == 0:
  2238. self._check_pickling_with_opcode(obj, pickle.SETITEM, proto)
  2239. else:
  2240. self._check_pickling_with_opcode(obj, pickle.SETITEMS, proto)
  2241. # Exercise framing (proto >= 4) for significant workloads
  2242. FRAME_SIZE_MIN = 4
  2243. FRAME_SIZE_TARGET = 64 * 1024
  2244. def check_frame_opcodes(self, pickled):
  2245. """
  2246. Check the arguments of FRAME opcodes in a protocol 4+ pickle.
  2247. Note that binary objects that are larger than FRAME_SIZE_TARGET are not
  2248. framed by default and are therefore considered a frame by themselves in
  2249. the following consistency check.
  2250. """
  2251. frame_end = frameless_start = None
  2252. frameless_opcodes = {'BINBYTES', 'BINUNICODE', 'BINBYTES8',
  2253. 'BINUNICODE8', 'BYTEARRAY8'}
  2254. for op, arg, pos in pickletools.genops(pickled):
  2255. if frame_end is not None:
  2256. self.assertLessEqual(pos, frame_end)
  2257. if pos == frame_end:
  2258. frame_end = None
  2259. if frame_end is not None: # framed
  2260. self.assertNotEqual(op.name, 'FRAME')
  2261. if op.name in frameless_opcodes:
  2262. # Only short bytes and str objects should be written
  2263. # in a frame
  2264. self.assertLessEqual(len(arg), self.FRAME_SIZE_TARGET)
  2265. else: # not framed
  2266. if (op.name == 'FRAME' or
  2267. (op.name in frameless_opcodes and
  2268. len(arg) > self.FRAME_SIZE_TARGET)):
  2269. # Frame or large bytes or str object
  2270. if frameless_start is not None:
  2271. # Only short data should be written outside of a frame
  2272. self.assertLess(pos - frameless_start,
  2273. self.FRAME_SIZE_MIN)
  2274. frameless_start = None
  2275. elif frameless_start is None and op.name != 'PROTO':
  2276. frameless_start = pos
  2277. if op.name == 'FRAME':
  2278. self.assertGreaterEqual(arg, self.FRAME_SIZE_MIN)
  2279. frame_end = pos + 9 + arg
  2280. pos = len(pickled)
  2281. if frame_end is not None:
  2282. self.assertEqual(frame_end, pos)
  2283. elif frameless_start is not None:
  2284. self.assertLess(pos - frameless_start, self.FRAME_SIZE_MIN)
  2285. @support.skip_if_pgo_task
  2286. def test_framing_many_objects(self):
  2287. obj = list(range(10**5))
  2288. for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
  2289. with self.subTest(proto=proto):
  2290. pickled = self.dumps(obj, proto)
  2291. unpickled = self.loads(pickled)
  2292. self.assertEqual(obj, unpickled)
  2293. bytes_per_frame = (len(pickled) /
  2294. count_opcode(pickle.FRAME, pickled))
  2295. self.assertGreater(bytes_per_frame,
  2296. self.FRAME_SIZE_TARGET / 2)
  2297. self.assertLessEqual(bytes_per_frame,
  2298. self.FRAME_SIZE_TARGET * 1)
  2299. self.check_frame_opcodes(pickled)
  2300. def test_framing_large_objects(self):
  2301. N = 1024 * 1024
  2302. small_items = [[i] for i in range(10)]
  2303. obj = [b'x' * N, *small_items, b'y' * N, 'z' * N]
  2304. for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
  2305. for fast in [False, True]:
  2306. with self.subTest(proto=proto, fast=fast):
  2307. if not fast:
  2308. # fast=False by default.
  2309. # This covers in-memory pickling with pickle.dumps().
  2310. pickled = self.dumps(obj, proto)
  2311. else:
  2312. # Pickler is required when fast=True.
  2313. if not hasattr(self, 'pickler'):
  2314. continue
  2315. buf = io.BytesIO()
  2316. pickler = self.pickler(buf, protocol=proto)
  2317. pickler.fast = fast
  2318. pickler.dump(obj)
  2319. pickled = buf.getvalue()
  2320. unpickled = self.loads(pickled)
  2321. # More informative error message in case of failure.
  2322. self.assertEqual([len(x) for x in obj],
  2323. [len(x) for x in unpickled])
  2324. # Perform full equality check if the lengths match.
  2325. self.assertEqual(obj, unpickled)
  2326. n_frames = count_opcode(pickle.FRAME, pickled)
  2327. # A single frame for small objects between
  2328. # first two large objects.
  2329. self.assertEqual(n_frames, 1)
  2330. self.check_frame_opcodes(pickled)
  2331. def test_optional_frames(self):
  2332. if pickle.HIGHEST_PROTOCOL < 4:
  2333. return
  2334. def remove_frames(pickled, keep_frame=None):
  2335. """Remove frame opcodes from the given pickle."""
  2336. frame_starts = []
  2337. # 1 byte for the opcode and 8 for the argument
  2338. frame_opcode_size = 9
  2339. for opcode, _, pos in pickletools.genops(pickled):
  2340. if opcode.name == 'FRAME':
  2341. frame_starts.append(pos)
  2342. newpickle = bytearray()
  2343. last_frame_end = 0
  2344. for i, pos in enumerate(frame_starts):
  2345. if keep_frame and keep_frame(i):
  2346. continue
  2347. newpickle += pickled[last_frame_end:pos]
  2348. last_frame_end = pos + frame_opcode_size
  2349. newpickle += pickled[last_frame_end:]
  2350. return newpickle
  2351. frame_size = self.FRAME_SIZE_TARGET
  2352. num_frames = 20
  2353. # Large byte objects (dict values) intermittent with small objects
  2354. # (dict keys)
  2355. for bytes_type in (bytes, bytearray):
  2356. obj = {i: bytes_type([i]) * frame_size for i in range(num_frames)}
  2357. for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
  2358. pickled = self.dumps(obj, proto)
  2359. frameless_pickle = remove_frames(pickled)
  2360. self.assertEqual(count_opcode(pickle.FRAME, frameless_pickle), 0)
  2361. self.assertEqual(obj, self.loads(frameless_pickle))
  2362. some_frames_pickle = remove_frames(pickled, lambda i: i % 2)
  2363. self.assertLess(count_opcode(pickle.FRAME, some_frames_pickle),
  2364. count_opcode(pickle.FRAME, pickled))
  2365. self.assertEqual(obj, self.loads(some_frames_pickle))
  2366. @support.skip_if_pgo_task
  2367. def test_framed_write_sizes_with_delayed_writer(self):
  2368. class ChunkAccumulator:
  2369. """Accumulate pickler output in a list of raw chunks."""
  2370. def __init__(self):
  2371. self.chunks = []
  2372. def write(self, chunk):
  2373. self.chunks.append(chunk)
  2374. def concatenate_chunks(self):
  2375. return b"".join(self.chunks)
  2376. for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
  2377. objects = [(str(i).encode('ascii'), i % 42, {'i': str(i)})
  2378. for i in range(int(1e4))]
  2379. # Add a large unique ASCII string
  2380. objects.append('0123456789abcdef' *
  2381. (self.FRAME_SIZE_TARGET // 16 + 1))
  2382. # Protocol 4 packs groups of small objects into frames and issues
  2383. # calls to write only once or twice per frame:
  2384. # The C pickler issues one call to write per-frame (header and
  2385. # contents) while Python pickler issues two calls to write: one for
  2386. # the frame header and one for the frame binary contents.
  2387. writer = ChunkAccumulator()
  2388. self.pickler(writer, proto).dump(objects)
  2389. # Actually read the binary content of the chunks after the end
  2390. # of the call to dump: any memoryview passed to write should not
  2391. # be released otherwise this delayed access would not be possible.
  2392. pickled = writer.concatenate_chunks()
  2393. reconstructed = self.loads(pickled)
  2394. self.assertEqual(reconstructed, objects)
  2395. self.assertGreater(len(writer.chunks), 1)
  2396. # memoryviews should own the memory.
  2397. del objects
  2398. support.gc_collect()
  2399. self.assertEqual(writer.concatenate_chunks(), pickled)
  2400. n_frames = (len(pickled) - 1) // self.FRAME_SIZE_TARGET + 1
  2401. # There should be at least one call to write per frame
  2402. self.assertGreaterEqual(len(writer.chunks), n_frames)
  2403. # but not too many either: there can be one for the proto,
  2404. # one per-frame header, one per frame for the actual contents,
  2405. # and two for the header.
  2406. self.assertLessEqual(len(writer.chunks), 2 * n_frames + 3)
  2407. chunk_sizes = [len(c) for c in writer.chunks]
  2408. large_sizes = [s for s in chunk_sizes
  2409. if s >= self.FRAME_SIZE_TARGET]
  2410. medium_sizes = [s for s in chunk_sizes
  2411. if 9 < s < self.FRAME_SIZE_TARGET]
  2412. small_sizes = [s for s in chunk_sizes if s <= 9]
  2413. # Large chunks should not be too large:
  2414. for chunk_size in large_sizes:
  2415. self.assertLess(chunk_size, 2 * self.FRAME_SIZE_TARGET,
  2416. chunk_sizes)
  2417. # There shouldn't bee too many small chunks: the protocol header,
  2418. # the frame headers and the large string headers are written
  2419. # in small chunks.
  2420. self.assertLessEqual(len(small_sizes),
  2421. len(large_sizes) + len(medium_sizes) + 3,
  2422. chunk_sizes)
  2423. def test_nested_names(self):
  2424. global Nested
  2425. class Nested:
  2426. class A:
  2427. class B:
  2428. class C:
  2429. pass
  2430. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2431. for obj in [Nested.A, Nested.A.B, Nested.A.B.C]:
  2432. with self.subTest(proto=proto, obj=obj):
  2433. unpickled = self.loads(self.dumps(obj, proto))
  2434. self.assertIs(obj, unpickled)
  2435. def test_recursive_nested_names(self):
  2436. global Recursive
  2437. class Recursive:
  2438. pass
  2439. Recursive.mod = sys.modules[Recursive.__module__]
  2440. Recursive.__qualname__ = 'Recursive.mod.Recursive'
  2441. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2442. with self.subTest(proto=proto):
  2443. unpickled = self.loads(self.dumps(Recursive, proto))
  2444. self.assertIs(unpickled, Recursive)
  2445. del Recursive.mod # break reference loop
  2446. def test_py_methods(self):
  2447. global PyMethodsTest
  2448. class PyMethodsTest:
  2449. @staticmethod
  2450. def cheese():
  2451. return "cheese"
  2452. @classmethod
  2453. def wine(cls):
  2454. assert cls is PyMethodsTest
  2455. return "wine"
  2456. def biscuits(self):
  2457. assert isinstance(self, PyMethodsTest)
  2458. return "biscuits"
  2459. class Nested:
  2460. "Nested class"
  2461. @staticmethod
  2462. def ketchup():
  2463. return "ketchup"
  2464. @classmethod
  2465. def maple(cls):
  2466. assert cls is PyMethodsTest.Nested
  2467. return "maple"
  2468. def pie(self):
  2469. assert isinstance(self, PyMethodsTest.Nested)
  2470. return "pie"
  2471. py_methods = (
  2472. PyMethodsTest.cheese,
  2473. PyMethodsTest.wine,
  2474. PyMethodsTest().biscuits,
  2475. PyMethodsTest.Nested.ketchup,
  2476. PyMethodsTest.Nested.maple,
  2477. PyMethodsTest.Nested().pie
  2478. )
  2479. py_unbound_methods = (
  2480. (PyMethodsTest.biscuits, PyMethodsTest),
  2481. (PyMethodsTest.Nested.pie, PyMethodsTest.Nested)
  2482. )
  2483. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2484. for method in py_methods:
  2485. with self.subTest(proto=proto, method=method):
  2486. unpickled = self.loads(self.dumps(method, proto))
  2487. self.assertEqual(method(), unpickled())
  2488. for method, cls in py_unbound_methods:
  2489. obj = cls()
  2490. with self.subTest(proto=proto, method=method):
  2491. unpickled = self.loads(self.dumps(method, proto))
  2492. self.assertEqual(method(obj), unpickled(obj))
  2493. descriptors = (
  2494. PyMethodsTest.__dict__['cheese'], # static method descriptor
  2495. PyMethodsTest.__dict__['wine'], # class method descriptor
  2496. )
  2497. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2498. for descr in descriptors:
  2499. with self.subTest(proto=proto, descr=descr):
  2500. self.assertRaises(TypeError, self.dumps, descr, proto)
  2501. def test_c_methods(self):
  2502. global Subclass
  2503. class Subclass(tuple):
  2504. class Nested(str):
  2505. pass
  2506. c_methods = (
  2507. # bound built-in method
  2508. ("abcd".index, ("c",)),
  2509. # unbound built-in method
  2510. (str.index, ("abcd", "c")),
  2511. # bound "slot" method
  2512. ([1, 2, 3].__len__, ()),
  2513. # unbound "slot" method
  2514. (list.__len__, ([1, 2, 3],)),
  2515. # bound "coexist" method
  2516. ({1, 2}.__contains__, (2,)),
  2517. # unbound "coexist" method
  2518. (set.__contains__, ({1, 2}, 2)),
  2519. # built-in class method
  2520. (dict.fromkeys, (("a", 1), ("b", 2))),
  2521. # built-in static method
  2522. (bytearray.maketrans, (b"abc", b"xyz")),
  2523. # subclass methods
  2524. (Subclass([1,2,2]).count, (2,)),
  2525. (Subclass.count, (Subclass([1,2,2]), 2)),
  2526. (Subclass.Nested("sweet").count, ("e",)),
  2527. (Subclass.Nested.count, (Subclass.Nested("sweet"), "e")),
  2528. )
  2529. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2530. for method, args in c_methods:
  2531. with self.subTest(proto=proto, method=method):
  2532. unpickled = self.loads(self.dumps(method, proto))
  2533. self.assertEqual(method(*args), unpickled(*args))
  2534. descriptors = (
  2535. bytearray.__dict__['maketrans'], # built-in static method descriptor
  2536. dict.__dict__['fromkeys'], # built-in class method descriptor
  2537. )
  2538. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2539. for descr in descriptors:
  2540. with self.subTest(proto=proto, descr=descr):
  2541. self.assertRaises(TypeError, self.dumps, descr, proto)
  2542. def test_compat_pickle(self):
  2543. tests = [
  2544. (range(1, 7), '__builtin__', 'xrange'),
  2545. (map(int, '123'), 'itertools', 'imap'),
  2546. (functools.reduce, '__builtin__', 'reduce'),
  2547. (dbm.whichdb, 'whichdb', 'whichdb'),
  2548. (Exception(), 'exceptions', 'Exception'),
  2549. (collections.UserDict(), 'UserDict', 'IterableUserDict'),
  2550. (collections.UserList(), 'UserList', 'UserList'),
  2551. (collections.defaultdict(), 'collections', 'defaultdict'),
  2552. ]
  2553. for val, mod, name in tests:
  2554. for proto in range(3):
  2555. with self.subTest(type=type(val), proto=proto):
  2556. pickled = self.dumps(val, proto)
  2557. self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled)
  2558. self.assertIs(type(self.loads(pickled)), type(val))
  2559. def test_local_lookup_error(self):
  2560. # Test that whichmodule() errors out cleanly when looking up
  2561. # an assumed globally-reachable object fails.
  2562. def f():
  2563. pass
  2564. # Since the function is local, lookup will fail
  2565. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  2566. with self.assertRaises((AttributeError, pickle.PicklingError)):
  2567. pickletools.dis(self.dumps(f, proto))
  2568. # Same without a __module__ attribute (exercises a different path
  2569. # in _pickle.c).
  2570. del f.__module__
  2571. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  2572. with self.assertRaises((AttributeError, pickle.PicklingError)):
  2573. pickletools.dis(self.dumps(f, proto))
  2574. # Yet a different path.
  2575. f.__name__ = f.__qualname__
  2576. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  2577. with self.assertRaises((AttributeError, pickle.PicklingError)):
  2578. pickletools.dis(self.dumps(f, proto))
  2579. #
  2580. # PEP 574 tests below
  2581. #
  2582. def buffer_like_objects(self):
  2583. # Yield buffer-like objects with the bytestring "abcdef" in them
  2584. bytestring = b"abcdefgh"
  2585. yield ZeroCopyBytes(bytestring)
  2586. yield ZeroCopyBytearray(bytestring)
  2587. if _testbuffer is not None:
  2588. items = list(bytestring)
  2589. value = int.from_bytes(bytestring, byteorder='little')
  2590. for flags in (0, _testbuffer.ND_WRITABLE):
  2591. # 1-D, contiguous
  2592. yield PicklableNDArray(items, format='B', shape=(8,),
  2593. flags=flags)
  2594. # 2-D, C-contiguous
  2595. yield PicklableNDArray(items, format='B', shape=(4, 2),
  2596. strides=(2, 1), flags=flags)
  2597. # 2-D, Fortran-contiguous
  2598. yield PicklableNDArray(items, format='B',
  2599. shape=(4, 2), strides=(1, 4),
  2600. flags=flags)
  2601. def test_in_band_buffers(self):
  2602. # Test in-band buffers (PEP 574)
  2603. for obj in self.buffer_like_objects():
  2604. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  2605. data = self.dumps(obj, proto)
  2606. if obj.c_contiguous and proto >= 5:
  2607. # The raw memory bytes are serialized in physical order
  2608. self.assertIn(b"abcdefgh", data)
  2609. self.assertEqual(count_opcode(pickle.NEXT_BUFFER, data), 0)
  2610. if proto >= 5:
  2611. self.assertEqual(count_opcode(pickle.SHORT_BINBYTES, data),
  2612. 1 if obj.readonly else 0)
  2613. self.assertEqual(count_opcode(pickle.BYTEARRAY8, data),
  2614. 0 if obj.readonly else 1)
  2615. # Return a true value from buffer_callback should have
  2616. # the same effect
  2617. def buffer_callback(obj):
  2618. return True
  2619. data2 = self.dumps(obj, proto,
  2620. buffer_callback=buffer_callback)
  2621. self.assertEqual(data2, data)
  2622. new = self.loads(data)
  2623. # It's a copy
  2624. self.assertIsNot(new, obj)
  2625. self.assertIs(type(new), type(obj))
  2626. self.assertEqual(new, obj)
  2627. # XXX Unfortunately cannot test non-contiguous array
  2628. # (see comment in PicklableNDArray.__reduce_ex__)
  2629. def test_oob_buffers(self):
  2630. # Test out-of-band buffers (PEP 574)
  2631. for obj in self.buffer_like_objects():
  2632. for proto in range(0, 5):
  2633. # Need protocol >= 5 for buffer_callback
  2634. with self.assertRaises(ValueError):
  2635. self.dumps(obj, proto,
  2636. buffer_callback=[].append)
  2637. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  2638. buffers = []
  2639. buffer_callback = lambda pb: buffers.append(pb.raw())
  2640. data = self.dumps(obj, proto,
  2641. buffer_callback=buffer_callback)
  2642. self.assertNotIn(b"abcdefgh", data)
  2643. self.assertEqual(count_opcode(pickle.SHORT_BINBYTES, data), 0)
  2644. self.assertEqual(count_opcode(pickle.BYTEARRAY8, data), 0)
  2645. self.assertEqual(count_opcode(pickle.NEXT_BUFFER, data), 1)
  2646. self.assertEqual(count_opcode(pickle.READONLY_BUFFER, data),
  2647. 1 if obj.readonly else 0)
  2648. if obj.c_contiguous:
  2649. self.assertEqual(bytes(buffers[0]), b"abcdefgh")
  2650. # Need buffers argument to unpickle properly
  2651. with self.assertRaises(pickle.UnpicklingError):
  2652. self.loads(data)
  2653. new = self.loads(data, buffers=buffers)
  2654. if obj.zero_copy_reconstruct:
  2655. # Zero-copy achieved
  2656. self.assertIs(new, obj)
  2657. else:
  2658. self.assertIs(type(new), type(obj))
  2659. self.assertEqual(new, obj)
  2660. # Non-sequence buffers accepted too
  2661. new = self.loads(data, buffers=iter(buffers))
  2662. if obj.zero_copy_reconstruct:
  2663. # Zero-copy achieved
  2664. self.assertIs(new, obj)
  2665. else:
  2666. self.assertIs(type(new), type(obj))
  2667. self.assertEqual(new, obj)
  2668. def test_oob_buffers_writable_to_readonly(self):
  2669. # Test reconstructing readonly object from writable buffer
  2670. obj = ZeroCopyBytes(b"foobar")
  2671. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  2672. buffers = []
  2673. buffer_callback = buffers.append
  2674. data = self.dumps(obj, proto, buffer_callback=buffer_callback)
  2675. buffers = map(bytearray, buffers)
  2676. new = self.loads(data, buffers=buffers)
  2677. self.assertIs(type(new), type(obj))
  2678. self.assertEqual(new, obj)
  2679. def test_picklebuffer_error(self):
  2680. # PickleBuffer forbidden with protocol < 5
  2681. pb = pickle.PickleBuffer(b"foobar")
  2682. for proto in range(0, 5):
  2683. with self.assertRaises(pickle.PickleError):
  2684. self.dumps(pb, proto)
  2685. def test_buffer_callback_error(self):
  2686. def buffer_callback(buffers):
  2687. 1/0
  2688. pb = pickle.PickleBuffer(b"foobar")
  2689. with self.assertRaises(ZeroDivisionError):
  2690. self.dumps(pb, 5, buffer_callback=buffer_callback)
  2691. def test_buffers_error(self):
  2692. pb = pickle.PickleBuffer(b"foobar")
  2693. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  2694. data = self.dumps(pb, proto, buffer_callback=[].append)
  2695. # Non iterable buffers
  2696. with self.assertRaises(TypeError):
  2697. self.loads(data, buffers=object())
  2698. # Buffer iterable exhausts too early
  2699. with self.assertRaises(pickle.UnpicklingError):
  2700. self.loads(data, buffers=[])
  2701. def test_inband_accept_default_buffers_argument(self):
  2702. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  2703. data_pickled = self.dumps(1, proto, buffer_callback=None)
  2704. data = self.loads(data_pickled, buffers=None)
  2705. @unittest.skipIf(np is None, "Test needs Numpy")
  2706. def test_buffers_numpy(self):
  2707. def check_no_copy(x, y):
  2708. np.testing.assert_equal(x, y)
  2709. self.assertEqual(x.ctypes.data, y.ctypes.data)
  2710. def check_copy(x, y):
  2711. np.testing.assert_equal(x, y)
  2712. self.assertNotEqual(x.ctypes.data, y.ctypes.data)
  2713. def check_array(arr):
  2714. # In-band
  2715. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  2716. data = self.dumps(arr, proto)
  2717. new = self.loads(data)
  2718. check_copy(arr, new)
  2719. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  2720. buffer_callback = lambda _: True
  2721. data = self.dumps(arr, proto, buffer_callback=buffer_callback)
  2722. new = self.loads(data)
  2723. check_copy(arr, new)
  2724. # Out-of-band
  2725. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  2726. buffers = []
  2727. buffer_callback = buffers.append
  2728. data = self.dumps(arr, proto, buffer_callback=buffer_callback)
  2729. new = self.loads(data, buffers=buffers)
  2730. if arr.flags.c_contiguous or arr.flags.f_contiguous:
  2731. check_no_copy(arr, new)
  2732. else:
  2733. check_copy(arr, new)
  2734. # 1-D
  2735. arr = np.arange(6)
  2736. check_array(arr)
  2737. # 1-D, non-contiguous
  2738. check_array(arr[::2])
  2739. # 2-D, C-contiguous
  2740. arr = np.arange(12).reshape((3, 4))
  2741. check_array(arr)
  2742. # 2-D, F-contiguous
  2743. check_array(arr.T)
  2744. # 2-D, non-contiguous
  2745. check_array(arr[::2])
  2746. def test_evil_class_mutating_dict(self):
  2747. # https://github.com/python/cpython/issues/92930
  2748. from random import getrandbits
  2749. global Bad
  2750. class Bad:
  2751. def __eq__(self, other):
  2752. return ENABLED
  2753. def __hash__(self):
  2754. return 42
  2755. def __reduce__(self):
  2756. if getrandbits(6) == 0:
  2757. collection.clear()
  2758. return (Bad, ())
  2759. for proto in protocols:
  2760. for _ in range(20):
  2761. ENABLED = False
  2762. collection = {Bad(): Bad() for _ in range(20)}
  2763. for bad in collection:
  2764. bad.bad = bad
  2765. bad.collection = collection
  2766. ENABLED = True
  2767. try:
  2768. data = self.dumps(collection, proto)
  2769. self.loads(data)
  2770. except RuntimeError as e:
  2771. expected = "changed size during iteration"
  2772. self.assertIn(expected, str(e))
  2773. def test_evil_pickler_mutating_collection(self):
  2774. # https://github.com/python/cpython/issues/92930
  2775. if not hasattr(self, "pickler"):
  2776. raise self.skipTest(f"{type(self)} has no associated pickler type")
  2777. global Clearer
  2778. class Clearer:
  2779. pass
  2780. def check(collection):
  2781. class EvilPickler(self.pickler):
  2782. def persistent_id(self, obj):
  2783. if isinstance(obj, Clearer):
  2784. collection.clear()
  2785. return None
  2786. pickler = EvilPickler(io.BytesIO(), proto)
  2787. try:
  2788. pickler.dump(collection)
  2789. except RuntimeError as e:
  2790. expected = "changed size during iteration"
  2791. self.assertIn(expected, str(e))
  2792. for proto in protocols:
  2793. check([Clearer()])
  2794. check([Clearer(), Clearer()])
  2795. check({Clearer()})
  2796. check({Clearer(), Clearer()})
  2797. check({Clearer(): 1})
  2798. check({Clearer(): 1, Clearer(): 2})
  2799. check({1: Clearer(), 2: Clearer()})
  2800. class BigmemPickleTests:
  2801. # Binary protocols can serialize longs of up to 2 GiB-1
  2802. @bigmemtest(size=_2G, memuse=3.6, dry_run=False)
  2803. def test_huge_long_32b(self, size):
  2804. data = 1 << (8 * size)
  2805. try:
  2806. for proto in protocols:
  2807. if proto < 2:
  2808. continue
  2809. with self.subTest(proto=proto):
  2810. with self.assertRaises((ValueError, OverflowError)):
  2811. self.dumps(data, protocol=proto)
  2812. finally:
  2813. data = None
  2814. # Protocol 3 can serialize up to 4 GiB-1 as a bytes object
  2815. # (older protocols don't have a dedicated opcode for bytes and are
  2816. # too inefficient)
  2817. @bigmemtest(size=_2G, memuse=2.5, dry_run=False)
  2818. def test_huge_bytes_32b(self, size):
  2819. data = b"abcd" * (size // 4)
  2820. try:
  2821. for proto in protocols:
  2822. if proto < 3:
  2823. continue
  2824. with self.subTest(proto=proto):
  2825. try:
  2826. pickled = self.dumps(data, protocol=proto)
  2827. header = (pickle.BINBYTES +
  2828. struct.pack("<I", len(data)))
  2829. data_start = pickled.index(data)
  2830. self.assertEqual(
  2831. header,
  2832. pickled[data_start-len(header):data_start])
  2833. finally:
  2834. pickled = None
  2835. finally:
  2836. data = None
  2837. @bigmemtest(size=_4G, memuse=2.5, dry_run=False)
  2838. def test_huge_bytes_64b(self, size):
  2839. data = b"acbd" * (size // 4)
  2840. try:
  2841. for proto in protocols:
  2842. if proto < 3:
  2843. continue
  2844. with self.subTest(proto=proto):
  2845. if proto == 3:
  2846. # Protocol 3 does not support large bytes objects.
  2847. # Verify that we do not crash when processing one.
  2848. with self.assertRaises((ValueError, OverflowError)):
  2849. self.dumps(data, protocol=proto)
  2850. continue
  2851. try:
  2852. pickled = self.dumps(data, protocol=proto)
  2853. header = (pickle.BINBYTES8 +
  2854. struct.pack("<Q", len(data)))
  2855. data_start = pickled.index(data)
  2856. self.assertEqual(
  2857. header,
  2858. pickled[data_start-len(header):data_start])
  2859. finally:
  2860. pickled = None
  2861. finally:
  2862. data = None
  2863. # All protocols use 1-byte per printable ASCII character; we add another
  2864. # byte because the encoded form has to be copied into the internal buffer.
  2865. @bigmemtest(size=_2G, memuse=8, dry_run=False)
  2866. def test_huge_str_32b(self, size):
  2867. data = "abcd" * (size // 4)
  2868. try:
  2869. for proto in protocols:
  2870. if proto == 0:
  2871. continue
  2872. with self.subTest(proto=proto):
  2873. try:
  2874. pickled = self.dumps(data, protocol=proto)
  2875. header = (pickle.BINUNICODE +
  2876. struct.pack("<I", len(data)))
  2877. data_start = pickled.index(b'abcd')
  2878. self.assertEqual(
  2879. header,
  2880. pickled[data_start-len(header):data_start])
  2881. self.assertEqual((pickled.rindex(b"abcd") + len(b"abcd") -
  2882. pickled.index(b"abcd")), len(data))
  2883. finally:
  2884. pickled = None
  2885. finally:
  2886. data = None
  2887. # BINUNICODE (protocols 1, 2 and 3) cannot carry more than 2**32 - 1 bytes
  2888. # of utf-8 encoded unicode. BINUNICODE8 (protocol 4) supports these huge
  2889. # unicode strings however.
  2890. @bigmemtest(size=_4G, memuse=8, dry_run=False)
  2891. def test_huge_str_64b(self, size):
  2892. data = "abcd" * (size // 4)
  2893. try:
  2894. for proto in protocols:
  2895. if proto == 0:
  2896. continue
  2897. with self.subTest(proto=proto):
  2898. if proto < 4:
  2899. with self.assertRaises((ValueError, OverflowError)):
  2900. self.dumps(data, protocol=proto)
  2901. continue
  2902. try:
  2903. pickled = self.dumps(data, protocol=proto)
  2904. header = (pickle.BINUNICODE8 +
  2905. struct.pack("<Q", len(data)))
  2906. data_start = pickled.index(b'abcd')
  2907. self.assertEqual(
  2908. header,
  2909. pickled[data_start-len(header):data_start])
  2910. self.assertEqual((pickled.rindex(b"abcd") + len(b"abcd") -
  2911. pickled.index(b"abcd")), len(data))
  2912. finally:
  2913. pickled = None
  2914. finally:
  2915. data = None
  2916. # Test classes for reduce_ex
  2917. class REX_one(object):
  2918. """No __reduce_ex__ here, but inheriting it from object"""
  2919. _reduce_called = 0
  2920. def __reduce__(self):
  2921. self._reduce_called = 1
  2922. return REX_one, ()
  2923. class REX_two(object):
  2924. """No __reduce__ here, but inheriting it from object"""
  2925. _proto = None
  2926. def __reduce_ex__(self, proto):
  2927. self._proto = proto
  2928. return REX_two, ()
  2929. class REX_three(object):
  2930. _proto = None
  2931. def __reduce_ex__(self, proto):
  2932. self._proto = proto
  2933. return REX_two, ()
  2934. def __reduce__(self):
  2935. raise TestFailed("This __reduce__ shouldn't be called")
  2936. class REX_four(object):
  2937. """Calling base class method should succeed"""
  2938. _proto = None
  2939. def __reduce_ex__(self, proto):
  2940. self._proto = proto
  2941. return object.__reduce_ex__(self, proto)
  2942. class REX_five(object):
  2943. """This one used to fail with infinite recursion"""
  2944. _reduce_called = 0
  2945. def __reduce__(self):
  2946. self._reduce_called = 1
  2947. return object.__reduce__(self)
  2948. class REX_six(object):
  2949. """This class is used to check the 4th argument (list iterator) of
  2950. the reduce protocol.
  2951. """
  2952. def __init__(self, items=None):
  2953. self.items = items if items is not None else []
  2954. def __eq__(self, other):
  2955. return type(self) is type(other) and self.items == other.items
  2956. def append(self, item):
  2957. self.items.append(item)
  2958. def __reduce__(self):
  2959. return type(self), (), None, iter(self.items), None
  2960. class REX_seven(object):
  2961. """This class is used to check the 5th argument (dict iterator) of
  2962. the reduce protocol.
  2963. """
  2964. def __init__(self, table=None):
  2965. self.table = table if table is not None else {}
  2966. def __eq__(self, other):
  2967. return type(self) is type(other) and self.table == other.table
  2968. def __setitem__(self, key, value):
  2969. self.table[key] = value
  2970. def __reduce__(self):
  2971. return type(self), (), None, None, iter(self.table.items())
  2972. class REX_state(object):
  2973. """This class is used to check the 3th argument (state) of
  2974. the reduce protocol.
  2975. """
  2976. def __init__(self, state=None):
  2977. self.state = state
  2978. def __eq__(self, other):
  2979. return type(self) is type(other) and self.state == other.state
  2980. def __setstate__(self, state):
  2981. self.state = state
  2982. def __reduce__(self):
  2983. return type(self), (), self.state
  2984. # Test classes for newobj
  2985. class MyInt(int):
  2986. sample = 1
  2987. class MyFloat(float):
  2988. sample = 1.0
  2989. class MyComplex(complex):
  2990. sample = 1.0 + 0.0j
  2991. class MyStr(str):
  2992. sample = "hello"
  2993. class MyUnicode(str):
  2994. sample = "hello \u1234"
  2995. class MyTuple(tuple):
  2996. sample = (1, 2, 3)
  2997. class MyList(list):
  2998. sample = [1, 2, 3]
  2999. class MyDict(dict):
  3000. sample = {"a": 1, "b": 2}
  3001. class MySet(set):
  3002. sample = {"a", "b"}
  3003. class MyFrozenSet(frozenset):
  3004. sample = frozenset({"a", "b"})
  3005. myclasses = [MyInt, MyFloat,
  3006. MyComplex,
  3007. MyStr, MyUnicode,
  3008. MyTuple, MyList, MyDict, MySet, MyFrozenSet]
  3009. class MyIntWithNew(int):
  3010. def __new__(cls, value):
  3011. raise AssertionError
  3012. class MyIntWithNew2(MyIntWithNew):
  3013. __new__ = int.__new__
  3014. class SlotList(MyList):
  3015. __slots__ = ["foo"]
  3016. class SimpleNewObj(int):
  3017. def __init__(self, *args, **kwargs):
  3018. # raise an error, to make sure this isn't called
  3019. raise TypeError("SimpleNewObj.__init__() didn't expect to get called")
  3020. def __eq__(self, other):
  3021. return int(self) == int(other) and self.__dict__ == other.__dict__
  3022. class ComplexNewObj(SimpleNewObj):
  3023. def __getnewargs__(self):
  3024. return ('%X' % self, 16)
  3025. class ComplexNewObjEx(SimpleNewObj):
  3026. def __getnewargs_ex__(self):
  3027. return ('%X' % self,), {'base': 16}
  3028. class BadGetattr:
  3029. def __getattr__(self, key):
  3030. self.foo
  3031. class AbstractPickleModuleTests:
  3032. def test_dump_closed_file(self):
  3033. f = open(TESTFN, "wb")
  3034. try:
  3035. f.close()
  3036. self.assertRaises(ValueError, self.dump, 123, f)
  3037. finally:
  3038. os_helper.unlink(TESTFN)
  3039. def test_load_closed_file(self):
  3040. f = open(TESTFN, "wb")
  3041. try:
  3042. f.close()
  3043. self.assertRaises(ValueError, self.dump, 123, f)
  3044. finally:
  3045. os_helper.unlink(TESTFN)
  3046. def test_load_from_and_dump_to_file(self):
  3047. stream = io.BytesIO()
  3048. data = [123, {}, 124]
  3049. self.dump(data, stream)
  3050. stream.seek(0)
  3051. unpickled = self.load(stream)
  3052. self.assertEqual(unpickled, data)
  3053. def test_highest_protocol(self):
  3054. # Of course this needs to be changed when HIGHEST_PROTOCOL changes.
  3055. self.assertEqual(pickle.HIGHEST_PROTOCOL, 5)
  3056. def test_callapi(self):
  3057. f = io.BytesIO()
  3058. # With and without keyword arguments
  3059. self.dump(123, f, -1)
  3060. self.dump(123, file=f, protocol=-1)
  3061. self.dumps(123, -1)
  3062. self.dumps(123, protocol=-1)
  3063. self.Pickler(f, -1)
  3064. self.Pickler(f, protocol=-1)
  3065. def test_dump_text_file(self):
  3066. f = open(TESTFN, "w")
  3067. try:
  3068. for proto in protocols:
  3069. self.assertRaises(TypeError, self.dump, 123, f, proto)
  3070. finally:
  3071. f.close()
  3072. os_helper.unlink(TESTFN)
  3073. def test_incomplete_input(self):
  3074. s = io.BytesIO(b"X''.")
  3075. self.assertRaises((EOFError, struct.error, pickle.UnpicklingError), self.load, s)
  3076. def test_bad_init(self):
  3077. # Test issue3664 (pickle can segfault from a badly initialized Pickler).
  3078. # Override initialization without calling __init__() of the superclass.
  3079. class BadPickler(self.Pickler):
  3080. def __init__(self): pass
  3081. class BadUnpickler(self.Unpickler):
  3082. def __init__(self): pass
  3083. self.assertRaises(pickle.PicklingError, BadPickler().dump, 0)
  3084. self.assertRaises(pickle.UnpicklingError, BadUnpickler().load)
  3085. def check_dumps_loads_oob_buffers(self, dumps, loads):
  3086. # No need to do the full gamut of tests here, just enough to
  3087. # check that dumps() and loads() redirect their arguments
  3088. # to the underlying Pickler and Unpickler, respectively.
  3089. obj = ZeroCopyBytes(b"foo")
  3090. for proto in range(0, 5):
  3091. # Need protocol >= 5 for buffer_callback
  3092. with self.assertRaises(ValueError):
  3093. dumps(obj, protocol=proto,
  3094. buffer_callback=[].append)
  3095. for proto in range(5, pickle.HIGHEST_PROTOCOL + 1):
  3096. buffers = []
  3097. buffer_callback = buffers.append
  3098. data = dumps(obj, protocol=proto,
  3099. buffer_callback=buffer_callback)
  3100. self.assertNotIn(b"foo", data)
  3101. self.assertEqual(bytes(buffers[0]), b"foo")
  3102. # Need buffers argument to unpickle properly
  3103. with self.assertRaises(pickle.UnpicklingError):
  3104. loads(data)
  3105. new = loads(data, buffers=buffers)
  3106. self.assertIs(new, obj)
  3107. def test_dumps_loads_oob_buffers(self):
  3108. # Test out-of-band buffers (PEP 574) with top-level dumps() and loads()
  3109. self.check_dumps_loads_oob_buffers(self.dumps, self.loads)
  3110. def test_dump_load_oob_buffers(self):
  3111. # Test out-of-band buffers (PEP 574) with top-level dump() and load()
  3112. def dumps(obj, **kwargs):
  3113. f = io.BytesIO()
  3114. self.dump(obj, f, **kwargs)
  3115. return f.getvalue()
  3116. def loads(data, **kwargs):
  3117. f = io.BytesIO(data)
  3118. return self.load(f, **kwargs)
  3119. self.check_dumps_loads_oob_buffers(dumps, loads)
  3120. class AbstractPersistentPicklerTests:
  3121. # This class defines persistent_id() and persistent_load()
  3122. # functions that should be used by the pickler. All even integers
  3123. # are pickled using persistent ids.
  3124. def persistent_id(self, object):
  3125. if isinstance(object, int) and object % 2 == 0:
  3126. self.id_count += 1
  3127. return str(object)
  3128. elif object == "test_false_value":
  3129. self.false_count += 1
  3130. return ""
  3131. else:
  3132. return None
  3133. def persistent_load(self, oid):
  3134. if not oid:
  3135. self.load_false_count += 1
  3136. return "test_false_value"
  3137. else:
  3138. self.load_count += 1
  3139. object = int(oid)
  3140. assert object % 2 == 0
  3141. return object
  3142. def test_persistence(self):
  3143. L = list(range(10)) + ["test_false_value"]
  3144. for proto in protocols:
  3145. self.id_count = 0
  3146. self.false_count = 0
  3147. self.load_false_count = 0
  3148. self.load_count = 0
  3149. self.assertEqual(self.loads(self.dumps(L, proto)), L)
  3150. self.assertEqual(self.id_count, 5)
  3151. self.assertEqual(self.false_count, 1)
  3152. self.assertEqual(self.load_count, 5)
  3153. self.assertEqual(self.load_false_count, 1)
  3154. class AbstractIdentityPersistentPicklerTests:
  3155. def persistent_id(self, obj):
  3156. return obj
  3157. def persistent_load(self, pid):
  3158. return pid
  3159. def _check_return_correct_type(self, obj, proto):
  3160. unpickled = self.loads(self.dumps(obj, proto))
  3161. self.assertIsInstance(unpickled, type(obj))
  3162. self.assertEqual(unpickled, obj)
  3163. def test_return_correct_type(self):
  3164. for proto in protocols:
  3165. # Protocol 0 supports only ASCII strings.
  3166. if proto == 0:
  3167. self._check_return_correct_type("abc", 0)
  3168. else:
  3169. for obj in [b"abc\n", "abc\n", -1, -1.1 * 0.1, str]:
  3170. self._check_return_correct_type(obj, proto)
  3171. def test_protocol0_is_ascii_only(self):
  3172. non_ascii_str = "\N{EMPTY SET}"
  3173. self.assertRaises(pickle.PicklingError, self.dumps, non_ascii_str, 0)
  3174. pickled = pickle.PERSID + non_ascii_str.encode('utf-8') + b'\n.'
  3175. self.assertRaises(pickle.UnpicklingError, self.loads, pickled)
  3176. class AbstractPicklerUnpicklerObjectTests:
  3177. pickler_class = None
  3178. unpickler_class = None
  3179. def setUp(self):
  3180. assert self.pickler_class
  3181. assert self.unpickler_class
  3182. def test_clear_pickler_memo(self):
  3183. # To test whether clear_memo() has any effect, we pickle an object,
  3184. # then pickle it again without clearing the memo; the two serialized
  3185. # forms should be different. If we clear_memo() and then pickle the
  3186. # object again, the third serialized form should be identical to the
  3187. # first one we obtained.
  3188. data = ["abcdefg", "abcdefg", 44]
  3189. for proto in protocols:
  3190. f = io.BytesIO()
  3191. pickler = self.pickler_class(f, proto)
  3192. pickler.dump(data)
  3193. first_pickled = f.getvalue()
  3194. # Reset BytesIO object.
  3195. f.seek(0)
  3196. f.truncate()
  3197. pickler.dump(data)
  3198. second_pickled = f.getvalue()
  3199. # Reset the Pickler and BytesIO objects.
  3200. pickler.clear_memo()
  3201. f.seek(0)
  3202. f.truncate()
  3203. pickler.dump(data)
  3204. third_pickled = f.getvalue()
  3205. self.assertNotEqual(first_pickled, second_pickled)
  3206. self.assertEqual(first_pickled, third_pickled)
  3207. def test_priming_pickler_memo(self):
  3208. # Verify that we can set the Pickler's memo attribute.
  3209. data = ["abcdefg", "abcdefg", 44]
  3210. f = io.BytesIO()
  3211. pickler = self.pickler_class(f)
  3212. pickler.dump(data)
  3213. first_pickled = f.getvalue()
  3214. f = io.BytesIO()
  3215. primed = self.pickler_class(f)
  3216. primed.memo = pickler.memo
  3217. primed.dump(data)
  3218. primed_pickled = f.getvalue()
  3219. self.assertNotEqual(first_pickled, primed_pickled)
  3220. def test_priming_unpickler_memo(self):
  3221. # Verify that we can set the Unpickler's memo attribute.
  3222. data = ["abcdefg", "abcdefg", 44]
  3223. f = io.BytesIO()
  3224. pickler = self.pickler_class(f)
  3225. pickler.dump(data)
  3226. first_pickled = f.getvalue()
  3227. f = io.BytesIO()
  3228. primed = self.pickler_class(f)
  3229. primed.memo = pickler.memo
  3230. primed.dump(data)
  3231. primed_pickled = f.getvalue()
  3232. unpickler = self.unpickler_class(io.BytesIO(first_pickled))
  3233. unpickled_data1 = unpickler.load()
  3234. self.assertEqual(unpickled_data1, data)
  3235. primed = self.unpickler_class(io.BytesIO(primed_pickled))
  3236. primed.memo = unpickler.memo
  3237. unpickled_data2 = primed.load()
  3238. primed.memo.clear()
  3239. self.assertEqual(unpickled_data2, data)
  3240. self.assertTrue(unpickled_data2 is unpickled_data1)
  3241. def test_reusing_unpickler_objects(self):
  3242. data1 = ["abcdefg", "abcdefg", 44]
  3243. f = io.BytesIO()
  3244. pickler = self.pickler_class(f)
  3245. pickler.dump(data1)
  3246. pickled1 = f.getvalue()
  3247. data2 = ["abcdefg", 44, 44]
  3248. f = io.BytesIO()
  3249. pickler = self.pickler_class(f)
  3250. pickler.dump(data2)
  3251. pickled2 = f.getvalue()
  3252. f = io.BytesIO()
  3253. f.write(pickled1)
  3254. f.seek(0)
  3255. unpickler = self.unpickler_class(f)
  3256. self.assertEqual(unpickler.load(), data1)
  3257. f.seek(0)
  3258. f.truncate()
  3259. f.write(pickled2)
  3260. f.seek(0)
  3261. self.assertEqual(unpickler.load(), data2)
  3262. def _check_multiple_unpicklings(self, ioclass, *, seekable=True):
  3263. for proto in protocols:
  3264. with self.subTest(proto=proto):
  3265. data1 = [(x, str(x)) for x in range(2000)] + [b"abcde", len]
  3266. f = ioclass()
  3267. pickler = self.pickler_class(f, protocol=proto)
  3268. pickler.dump(data1)
  3269. pickled = f.getvalue()
  3270. N = 5
  3271. f = ioclass(pickled * N)
  3272. unpickler = self.unpickler_class(f)
  3273. for i in range(N):
  3274. if seekable:
  3275. pos = f.tell()
  3276. self.assertEqual(unpickler.load(), data1)
  3277. if seekable:
  3278. self.assertEqual(f.tell(), pos + len(pickled))
  3279. self.assertRaises(EOFError, unpickler.load)
  3280. def test_multiple_unpicklings_seekable(self):
  3281. self._check_multiple_unpicklings(io.BytesIO)
  3282. def test_multiple_unpicklings_unseekable(self):
  3283. self._check_multiple_unpicklings(UnseekableIO, seekable=False)
  3284. def test_multiple_unpicklings_minimal(self):
  3285. # File-like object that doesn't support peek() and readinto()
  3286. # (bpo-39681)
  3287. self._check_multiple_unpicklings(MinimalIO, seekable=False)
  3288. def test_unpickling_buffering_readline(self):
  3289. # Issue #12687: the unpickler's buffering logic could fail with
  3290. # text mode opcodes.
  3291. data = list(range(10))
  3292. for proto in protocols:
  3293. for buf_size in range(1, 11):
  3294. f = io.BufferedRandom(io.BytesIO(), buffer_size=buf_size)
  3295. pickler = self.pickler_class(f, protocol=proto)
  3296. pickler.dump(data)
  3297. f.seek(0)
  3298. unpickler = self.unpickler_class(f)
  3299. self.assertEqual(unpickler.load(), data)
  3300. # Tests for dispatch_table attribute
  3301. REDUCE_A = 'reduce_A'
  3302. class AAA(object):
  3303. def __reduce__(self):
  3304. return str, (REDUCE_A,)
  3305. class BBB(object):
  3306. def __init__(self):
  3307. # Add an instance attribute to enable state-saving routines at pickling
  3308. # time.
  3309. self.a = "some attribute"
  3310. def __setstate__(self, state):
  3311. self.a = "BBB.__setstate__"
  3312. def setstate_bbb(obj, state):
  3313. """Custom state setter for BBB objects
  3314. Such callable may be created by other persons than the ones who created the
  3315. BBB class. If passed as the state_setter item of a custom reducer, this
  3316. allows for custom state setting behavior of BBB objects. One can think of
  3317. it as the analogous of list_setitems or dict_setitems but for foreign
  3318. classes/functions.
  3319. """
  3320. obj.a = "custom state_setter"
  3321. class AbstractCustomPicklerClass:
  3322. """Pickler implementing a reducing hook using reducer_override."""
  3323. def reducer_override(self, obj):
  3324. obj_name = getattr(obj, "__name__", None)
  3325. if obj_name == 'f':
  3326. # asking the pickler to save f as 5
  3327. return int, (5, )
  3328. if obj_name == 'MyClass':
  3329. return str, ('some str',)
  3330. elif obj_name == 'g':
  3331. # in this case, the callback returns an invalid result (not a 2-5
  3332. # tuple or a string), the pickler should raise a proper error.
  3333. return False
  3334. elif obj_name == 'h':
  3335. # Simulate a case when the reducer fails. The error should
  3336. # be propagated to the original ``dump`` call.
  3337. raise ValueError('The reducer just failed')
  3338. return NotImplemented
  3339. class AbstractHookTests:
  3340. def test_pickler_hook(self):
  3341. # test the ability of a custom, user-defined CPickler subclass to
  3342. # override the default reducing routines of any type using the method
  3343. # reducer_override
  3344. def f():
  3345. pass
  3346. def g():
  3347. pass
  3348. def h():
  3349. pass
  3350. class MyClass:
  3351. pass
  3352. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  3353. with self.subTest(proto=proto):
  3354. bio = io.BytesIO()
  3355. p = self.pickler_class(bio, proto)
  3356. p.dump([f, MyClass, math.log])
  3357. new_f, some_str, math_log = pickle.loads(bio.getvalue())
  3358. self.assertEqual(new_f, 5)
  3359. self.assertEqual(some_str, 'some str')
  3360. # math.log does not have its usual reducer overridden, so the
  3361. # custom reduction callback should silently direct the pickler
  3362. # to the default pickling by attribute, by returning
  3363. # NotImplemented
  3364. self.assertIs(math_log, math.log)
  3365. with self.assertRaises(pickle.PicklingError):
  3366. p.dump(g)
  3367. with self.assertRaisesRegex(
  3368. ValueError, 'The reducer just failed'):
  3369. p.dump(h)
  3370. @support.cpython_only
  3371. def test_reducer_override_no_reference_cycle(self):
  3372. # bpo-39492: reducer_override used to induce a spurious reference cycle
  3373. # inside the Pickler object, that could prevent all serialized objects
  3374. # from being garbage-collected without explicitly invoking gc.collect.
  3375. for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
  3376. with self.subTest(proto=proto):
  3377. def f():
  3378. pass
  3379. wr = weakref.ref(f)
  3380. bio = io.BytesIO()
  3381. p = self.pickler_class(bio, proto)
  3382. p.dump(f)
  3383. new_f = pickle.loads(bio.getvalue())
  3384. assert new_f == 5
  3385. del p
  3386. del f
  3387. self.assertIsNone(wr())
  3388. class AbstractDispatchTableTests:
  3389. def test_default_dispatch_table(self):
  3390. # No dispatch_table attribute by default
  3391. f = io.BytesIO()
  3392. p = self.pickler_class(f, 0)
  3393. with self.assertRaises(AttributeError):
  3394. p.dispatch_table
  3395. self.assertFalse(hasattr(p, 'dispatch_table'))
  3396. def test_class_dispatch_table(self):
  3397. # A dispatch_table attribute can be specified class-wide
  3398. dt = self.get_dispatch_table()
  3399. class MyPickler(self.pickler_class):
  3400. dispatch_table = dt
  3401. def dumps(obj, protocol=None):
  3402. f = io.BytesIO()
  3403. p = MyPickler(f, protocol)
  3404. self.assertEqual(p.dispatch_table, dt)
  3405. p.dump(obj)
  3406. return f.getvalue()
  3407. self._test_dispatch_table(dumps, dt)
  3408. def test_instance_dispatch_table(self):
  3409. # A dispatch_table attribute can also be specified instance-wide
  3410. dt = self.get_dispatch_table()
  3411. def dumps(obj, protocol=None):
  3412. f = io.BytesIO()
  3413. p = self.pickler_class(f, protocol)
  3414. p.dispatch_table = dt
  3415. self.assertEqual(p.dispatch_table, dt)
  3416. p.dump(obj)
  3417. return f.getvalue()
  3418. self._test_dispatch_table(dumps, dt)
  3419. def _test_dispatch_table(self, dumps, dispatch_table):
  3420. def custom_load_dump(obj):
  3421. return pickle.loads(dumps(obj, 0))
  3422. def default_load_dump(obj):
  3423. return pickle.loads(pickle.dumps(obj, 0))
  3424. # pickling complex numbers using protocol 0 relies on copyreg
  3425. # so check pickling a complex number still works
  3426. z = 1 + 2j
  3427. self.assertEqual(custom_load_dump(z), z)
  3428. self.assertEqual(default_load_dump(z), z)
  3429. # modify pickling of complex
  3430. REDUCE_1 = 'reduce_1'
  3431. def reduce_1(obj):
  3432. return str, (REDUCE_1,)
  3433. dispatch_table[complex] = reduce_1
  3434. self.assertEqual(custom_load_dump(z), REDUCE_1)
  3435. self.assertEqual(default_load_dump(z), z)
  3436. # check picklability of AAA and BBB
  3437. a = AAA()
  3438. b = BBB()
  3439. self.assertEqual(custom_load_dump(a), REDUCE_A)
  3440. self.assertIsInstance(custom_load_dump(b), BBB)
  3441. self.assertEqual(default_load_dump(a), REDUCE_A)
  3442. self.assertIsInstance(default_load_dump(b), BBB)
  3443. # modify pickling of BBB
  3444. dispatch_table[BBB] = reduce_1
  3445. self.assertEqual(custom_load_dump(a), REDUCE_A)
  3446. self.assertEqual(custom_load_dump(b), REDUCE_1)
  3447. self.assertEqual(default_load_dump(a), REDUCE_A)
  3448. self.assertIsInstance(default_load_dump(b), BBB)
  3449. # revert pickling of BBB and modify pickling of AAA
  3450. REDUCE_2 = 'reduce_2'
  3451. def reduce_2(obj):
  3452. return str, (REDUCE_2,)
  3453. dispatch_table[AAA] = reduce_2
  3454. del dispatch_table[BBB]
  3455. self.assertEqual(custom_load_dump(a), REDUCE_2)
  3456. self.assertIsInstance(custom_load_dump(b), BBB)
  3457. self.assertEqual(default_load_dump(a), REDUCE_A)
  3458. self.assertIsInstance(default_load_dump(b), BBB)
  3459. # End-to-end testing of save_reduce with the state_setter keyword
  3460. # argument. This is a dispatch_table test as the primary goal of
  3461. # state_setter is to tweak objects reduction behavior.
  3462. # In particular, state_setter is useful when the default __setstate__
  3463. # behavior is not flexible enough.
  3464. # No custom reducer for b has been registered for now, so
  3465. # BBB.__setstate__ should be used at unpickling time
  3466. self.assertEqual(default_load_dump(b).a, "BBB.__setstate__")
  3467. def reduce_bbb(obj):
  3468. return BBB, (), obj.__dict__, None, None, setstate_bbb
  3469. dispatch_table[BBB] = reduce_bbb
  3470. # The custom reducer reduce_bbb includes a state setter, that should
  3471. # have priority over BBB.__setstate__
  3472. self.assertEqual(custom_load_dump(b).a, "custom state_setter")
  3473. if __name__ == "__main__":
  3474. # Print some stuff that can be used to rewrite DATA{0,1,2}
  3475. from pickletools import dis
  3476. x = create_data()
  3477. for i in range(pickle.HIGHEST_PROTOCOL+1):
  3478. p = pickle.dumps(x, i)
  3479. print("DATA{0} = (".format(i))
  3480. for j in range(0, len(p), 20):
  3481. b = bytes(p[j:j+20])
  3482. print(" {0!r}".format(b))
  3483. print(")")
  3484. print()
  3485. print("# Disassembly of DATA{0}".format(i))
  3486. print("DATA{0}_DIS = \"\"\"\\".format(i))
  3487. dis(p)
  3488. print("\"\"\"")
  3489. print()