test_descr.py 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802
  1. import __builtin__
  2. import gc
  3. import sys
  4. import types
  5. import unittest
  6. import weakref
  7. from copy import deepcopy
  8. from test import test_support
  9. class OperatorsTest(unittest.TestCase):
  10. def __init__(self, *args, **kwargs):
  11. unittest.TestCase.__init__(self, *args, **kwargs)
  12. self.binops = {
  13. 'add': '+',
  14. 'sub': '-',
  15. 'mul': '*',
  16. 'div': '/',
  17. 'divmod': 'divmod',
  18. 'pow': '**',
  19. 'lshift': '<<',
  20. 'rshift': '>>',
  21. 'and': '&',
  22. 'xor': '^',
  23. 'or': '|',
  24. 'cmp': 'cmp',
  25. 'lt': '<',
  26. 'le': '<=',
  27. 'eq': '==',
  28. 'ne': '!=',
  29. 'gt': '>',
  30. 'ge': '>=',
  31. }
  32. for name, expr in self.binops.items():
  33. if expr.islower():
  34. expr = expr + "(a, b)"
  35. else:
  36. expr = 'a %s b' % expr
  37. self.binops[name] = expr
  38. self.unops = {
  39. 'pos': '+',
  40. 'neg': '-',
  41. 'abs': 'abs',
  42. 'invert': '~',
  43. 'int': 'int',
  44. 'long': 'long',
  45. 'float': 'float',
  46. 'oct': 'oct',
  47. 'hex': 'hex',
  48. }
  49. for name, expr in self.unops.items():
  50. if expr.islower():
  51. expr = expr + "(a)"
  52. else:
  53. expr = '%s a' % expr
  54. self.unops[name] = expr
  55. def unop_test(self, a, res, expr="len(a)", meth="__len__"):
  56. d = {'a': a}
  57. self.assertEqual(eval(expr, d), res)
  58. t = type(a)
  59. m = getattr(t, meth)
  60. # Find method in parent class
  61. while meth not in t.__dict__:
  62. t = t.__bases__[0]
  63. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  64. # method object; the getattr() below obtains its underlying function.
  65. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  66. self.assertEqual(m(a), res)
  67. bm = getattr(a, meth)
  68. self.assertEqual(bm(), res)
  69. def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
  70. d = {'a': a, 'b': b}
  71. # XXX Hack so this passes before 2.3 when -Qnew is specified.
  72. if meth == "__div__" and 1/2 == 0.5:
  73. meth = "__truediv__"
  74. if meth == '__divmod__': pass
  75. self.assertEqual(eval(expr, d), res)
  76. t = type(a)
  77. m = getattr(t, meth)
  78. while meth not in t.__dict__:
  79. t = t.__bases__[0]
  80. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  81. # method object; the getattr() below obtains its underlying function.
  82. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  83. self.assertEqual(m(a, b), res)
  84. bm = getattr(a, meth)
  85. self.assertEqual(bm(b), res)
  86. def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
  87. d = {'a': a, 'b': b, 'c': c}
  88. self.assertEqual(eval(expr, d), res)
  89. t = type(a)
  90. m = getattr(t, meth)
  91. while meth not in t.__dict__:
  92. t = t.__bases__[0]
  93. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  94. # method object; the getattr() below obtains its underlying function.
  95. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  96. self.assertEqual(m(a, b, c), res)
  97. bm = getattr(a, meth)
  98. self.assertEqual(bm(b, c), res)
  99. def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
  100. d = {'a': deepcopy(a), 'b': b}
  101. exec stmt in d
  102. self.assertEqual(d['a'], res)
  103. t = type(a)
  104. m = getattr(t, meth)
  105. while meth not in t.__dict__:
  106. t = t.__bases__[0]
  107. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  108. # method object; the getattr() below obtains its underlying function.
  109. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  110. d['a'] = deepcopy(a)
  111. m(d['a'], b)
  112. self.assertEqual(d['a'], res)
  113. d['a'] = deepcopy(a)
  114. bm = getattr(d['a'], meth)
  115. bm(b)
  116. self.assertEqual(d['a'], res)
  117. def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
  118. d = {'a': deepcopy(a), 'b': b, 'c': c}
  119. exec stmt in d
  120. self.assertEqual(d['a'], res)
  121. t = type(a)
  122. m = getattr(t, meth)
  123. while meth not in t.__dict__:
  124. t = t.__bases__[0]
  125. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  126. # method object; the getattr() below obtains its underlying function.
  127. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  128. d['a'] = deepcopy(a)
  129. m(d['a'], b, c)
  130. self.assertEqual(d['a'], res)
  131. d['a'] = deepcopy(a)
  132. bm = getattr(d['a'], meth)
  133. bm(b, c)
  134. self.assertEqual(d['a'], res)
  135. def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
  136. dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
  137. exec stmt in dictionary
  138. self.assertEqual(dictionary['a'], res)
  139. t = type(a)
  140. while meth not in t.__dict__:
  141. t = t.__bases__[0]
  142. m = getattr(t, meth)
  143. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  144. # method object; the getattr() below obtains its underlying function.
  145. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  146. dictionary['a'] = deepcopy(a)
  147. m(dictionary['a'], b, c, d)
  148. self.assertEqual(dictionary['a'], res)
  149. dictionary['a'] = deepcopy(a)
  150. bm = getattr(dictionary['a'], meth)
  151. bm(b, c, d)
  152. self.assertEqual(dictionary['a'], res)
  153. def test_lists(self):
  154. # Testing list operations...
  155. # Asserts are within individual test methods
  156. self.binop_test([1], [2], [1,2], "a+b", "__add__")
  157. self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
  158. self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
  159. self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
  160. self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
  161. self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
  162. self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
  163. self.unop_test([1,2,3], 3, "len(a)", "__len__")
  164. self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
  165. self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
  166. self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
  167. self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
  168. "__setslice__")
  169. def test_dicts(self):
  170. # Testing dict operations...
  171. if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
  172. self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
  173. else:
  174. self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
  175. self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
  176. self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
  177. self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
  178. d = {1:2, 3:4}
  179. l1 = []
  180. for i in d.keys():
  181. l1.append(i)
  182. l = []
  183. for i in iter(d):
  184. l.append(i)
  185. self.assertEqual(l, l1)
  186. l = []
  187. for i in d.__iter__():
  188. l.append(i)
  189. self.assertEqual(l, l1)
  190. l = []
  191. for i in dict.__iter__(d):
  192. l.append(i)
  193. self.assertEqual(l, l1)
  194. d = {1:2, 3:4}
  195. self.unop_test(d, 2, "len(a)", "__len__")
  196. self.assertEqual(eval(repr(d), {}), d)
  197. self.assertEqual(eval(d.__repr__(), {}), d)
  198. self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
  199. "__setitem__")
  200. # Tests for unary and binary operators
  201. def number_operators(self, a, b, skip=[]):
  202. dict = {'a': a, 'b': b}
  203. for name, expr in self.binops.items():
  204. if name not in skip:
  205. name = "__%s__" % name
  206. if hasattr(a, name):
  207. res = eval(expr, dict)
  208. self.binop_test(a, b, res, expr, name)
  209. for name, expr in self.unops.items():
  210. if name not in skip:
  211. name = "__%s__" % name
  212. if hasattr(a, name):
  213. res = eval(expr, dict)
  214. self.unop_test(a, res, expr, name)
  215. def test_ints(self):
  216. # Testing int operations...
  217. self.number_operators(100, 3)
  218. # The following crashes in Python 2.2
  219. self.assertEqual((1).__nonzero__(), 1)
  220. self.assertEqual((0).__nonzero__(), 0)
  221. # This returns 'NotImplemented' in Python 2.2
  222. class C(int):
  223. def __add__(self, other):
  224. return NotImplemented
  225. self.assertEqual(C(5L), 5)
  226. try:
  227. C() + ""
  228. except TypeError:
  229. pass
  230. else:
  231. self.fail("NotImplemented should have caused TypeError")
  232. try:
  233. C(sys.maxint+1)
  234. except OverflowError:
  235. pass
  236. else:
  237. self.fail("should have raised OverflowError")
  238. def test_longs(self):
  239. # Testing long operations...
  240. self.number_operators(100L, 3L)
  241. def test_floats(self):
  242. # Testing float operations...
  243. self.number_operators(100.0, 3.0)
  244. def test_complexes(self):
  245. # Testing complex operations...
  246. self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
  247. 'int', 'long', 'float'])
  248. class Number(complex):
  249. __slots__ = ['prec']
  250. def __new__(cls, *args, **kwds):
  251. result = complex.__new__(cls, *args)
  252. result.prec = kwds.get('prec', 12)
  253. return result
  254. def __repr__(self):
  255. prec = self.prec
  256. if self.imag == 0.0:
  257. return "%.*g" % (prec, self.real)
  258. if self.real == 0.0:
  259. return "%.*gj" % (prec, self.imag)
  260. return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
  261. __str__ = __repr__
  262. a = Number(3.14, prec=6)
  263. self.assertEqual(repr(a), "3.14")
  264. self.assertEqual(a.prec, 6)
  265. a = Number(a, prec=2)
  266. self.assertEqual(repr(a), "3.1")
  267. self.assertEqual(a.prec, 2)
  268. a = Number(234.5)
  269. self.assertEqual(repr(a), "234.5")
  270. self.assertEqual(a.prec, 12)
  271. @test_support.impl_detail("the module 'xxsubtype' is internal")
  272. def test_spam_lists(self):
  273. # Testing spamlist operations...
  274. import copy, xxsubtype as spam
  275. def spamlist(l, memo=None):
  276. import xxsubtype as spam
  277. return spam.spamlist(l)
  278. # This is an ugly hack:
  279. copy._deepcopy_dispatch[spam.spamlist] = spamlist
  280. self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
  281. "__add__")
  282. self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
  283. self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
  284. self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
  285. self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
  286. "__getslice__")
  287. self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
  288. "__iadd__")
  289. self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
  290. "__imul__")
  291. self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
  292. self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
  293. "__mul__")
  294. self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
  295. "__rmul__")
  296. self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
  297. "__setitem__")
  298. self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
  299. spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
  300. # Test subclassing
  301. class C(spam.spamlist):
  302. def foo(self): return 1
  303. a = C()
  304. self.assertEqual(a, [])
  305. self.assertEqual(a.foo(), 1)
  306. a.append(100)
  307. self.assertEqual(a, [100])
  308. self.assertEqual(a.getstate(), 0)
  309. a.setstate(42)
  310. self.assertEqual(a.getstate(), 42)
  311. @test_support.impl_detail("the module 'xxsubtype' is internal")
  312. def test_spam_dicts(self):
  313. # Testing spamdict operations...
  314. import copy, xxsubtype as spam
  315. def spamdict(d, memo=None):
  316. import xxsubtype as spam
  317. sd = spam.spamdict()
  318. for k, v in d.items():
  319. sd[k] = v
  320. return sd
  321. # This is an ugly hack:
  322. copy._deepcopy_dispatch[spam.spamdict] = spamdict
  323. self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
  324. "__cmp__")
  325. self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
  326. self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
  327. self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
  328. d = spamdict({1:2,3:4})
  329. l1 = []
  330. for i in d.keys():
  331. l1.append(i)
  332. l = []
  333. for i in iter(d):
  334. l.append(i)
  335. self.assertEqual(l, l1)
  336. l = []
  337. for i in d.__iter__():
  338. l.append(i)
  339. self.assertEqual(l, l1)
  340. l = []
  341. for i in type(spamdict({})).__iter__(d):
  342. l.append(i)
  343. self.assertEqual(l, l1)
  344. straightd = {1:2, 3:4}
  345. spamd = spamdict(straightd)
  346. self.unop_test(spamd, 2, "len(a)", "__len__")
  347. self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
  348. self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
  349. "a[b]=c", "__setitem__")
  350. # Test subclassing
  351. class C(spam.spamdict):
  352. def foo(self): return 1
  353. a = C()
  354. self.assertEqual(a.items(), [])
  355. self.assertEqual(a.foo(), 1)
  356. a['foo'] = 'bar'
  357. self.assertEqual(a.items(), [('foo', 'bar')])
  358. self.assertEqual(a.getstate(), 0)
  359. a.setstate(100)
  360. self.assertEqual(a.getstate(), 100)
  361. class ClassPropertiesAndMethods(unittest.TestCase):
  362. def assertHasAttr(self, obj, name):
  363. self.assertTrue(hasattr(obj, name),
  364. '%r has no attribute %r' % (obj, name))
  365. def assertNotHasAttr(self, obj, name):
  366. self.assertFalse(hasattr(obj, name),
  367. '%r has unexpected attribute %r' % (obj, name))
  368. def test_python_dicts(self):
  369. # Testing Python subclass of dict...
  370. self.assertTrue(issubclass(dict, dict))
  371. self.assertIsInstance({}, dict)
  372. d = dict()
  373. self.assertEqual(d, {})
  374. self.assertIs(d.__class__, dict)
  375. self.assertIsInstance(d, dict)
  376. class C(dict):
  377. state = -1
  378. def __init__(self_local, *a, **kw):
  379. if a:
  380. self.assertEqual(len(a), 1)
  381. self_local.state = a[0]
  382. if kw:
  383. for k, v in kw.items():
  384. self_local[v] = k
  385. def __getitem__(self, key):
  386. return self.get(key, 0)
  387. def __setitem__(self_local, key, value):
  388. self.assertIsInstance(key, type(0))
  389. dict.__setitem__(self_local, key, value)
  390. def setstate(self, state):
  391. self.state = state
  392. def getstate(self):
  393. return self.state
  394. self.assertTrue(issubclass(C, dict))
  395. a1 = C(12)
  396. self.assertEqual(a1.state, 12)
  397. a2 = C(foo=1, bar=2)
  398. self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
  399. a = C()
  400. self.assertEqual(a.state, -1)
  401. self.assertEqual(a.getstate(), -1)
  402. a.setstate(0)
  403. self.assertEqual(a.state, 0)
  404. self.assertEqual(a.getstate(), 0)
  405. a.setstate(10)
  406. self.assertEqual(a.state, 10)
  407. self.assertEqual(a.getstate(), 10)
  408. self.assertEqual(a[42], 0)
  409. a[42] = 24
  410. self.assertEqual(a[42], 24)
  411. N = 50
  412. for i in range(N):
  413. a[i] = C()
  414. for j in range(N):
  415. a[i][j] = i*j
  416. for i in range(N):
  417. for j in range(N):
  418. self.assertEqual(a[i][j], i*j)
  419. def test_python_lists(self):
  420. # Testing Python subclass of list...
  421. class C(list):
  422. def __getitem__(self, i):
  423. return list.__getitem__(self, i) + 100
  424. def __getslice__(self, i, j):
  425. return (i, j)
  426. a = C()
  427. a.extend([0,1,2])
  428. self.assertEqual(a[0], 100)
  429. self.assertEqual(a[1], 101)
  430. self.assertEqual(a[2], 102)
  431. self.assertEqual(a[100:200], (100,200))
  432. def test_metaclass(self):
  433. # Testing __metaclass__...
  434. class C:
  435. __metaclass__ = type
  436. def __init__(self):
  437. self.__state = 0
  438. def getstate(self):
  439. return self.__state
  440. def setstate(self, state):
  441. self.__state = state
  442. a = C()
  443. self.assertEqual(a.getstate(), 0)
  444. a.setstate(10)
  445. self.assertEqual(a.getstate(), 10)
  446. class D:
  447. class __metaclass__(type):
  448. def myself(cls): return cls
  449. self.assertEqual(D.myself(), D)
  450. d = D()
  451. self.assertEqual(d.__class__, D)
  452. class M1(type):
  453. def __new__(cls, name, bases, dict):
  454. dict['__spam__'] = 1
  455. return type.__new__(cls, name, bases, dict)
  456. class C:
  457. __metaclass__ = M1
  458. self.assertEqual(C.__spam__, 1)
  459. c = C()
  460. self.assertEqual(c.__spam__, 1)
  461. class _instance(object):
  462. pass
  463. class M2(object):
  464. @staticmethod
  465. def __new__(cls, name, bases, dict):
  466. self = object.__new__(cls)
  467. self.name = name
  468. self.bases = bases
  469. self.dict = dict
  470. return self
  471. def __call__(self):
  472. it = _instance()
  473. # Early binding of methods
  474. for key in self.dict:
  475. if key.startswith("__"):
  476. continue
  477. setattr(it, key, self.dict[key].__get__(it, self))
  478. return it
  479. class C:
  480. __metaclass__ = M2
  481. def spam(self):
  482. return 42
  483. self.assertEqual(C.name, 'C')
  484. self.assertEqual(C.bases, ())
  485. self.assertIn('spam', C.dict)
  486. c = C()
  487. self.assertEqual(c.spam(), 42)
  488. # More metaclass examples
  489. class autosuper(type):
  490. # Automatically add __super to the class
  491. # This trick only works for dynamic classes
  492. def __new__(metaclass, name, bases, dict):
  493. cls = super(autosuper, metaclass).__new__(metaclass,
  494. name, bases, dict)
  495. # Name mangling for __super removes leading underscores
  496. while name[:1] == "_":
  497. name = name[1:]
  498. if name:
  499. name = "_%s__super" % name
  500. else:
  501. name = "__super"
  502. setattr(cls, name, super(cls))
  503. return cls
  504. class A:
  505. __metaclass__ = autosuper
  506. def meth(self):
  507. return "A"
  508. class B(A):
  509. def meth(self):
  510. return "B" + self.__super.meth()
  511. class C(A):
  512. def meth(self):
  513. return "C" + self.__super.meth()
  514. class D(C, B):
  515. def meth(self):
  516. return "D" + self.__super.meth()
  517. self.assertEqual(D().meth(), "DCBA")
  518. class E(B, C):
  519. def meth(self):
  520. return "E" + self.__super.meth()
  521. self.assertEqual(E().meth(), "EBCA")
  522. class autoproperty(type):
  523. # Automatically create property attributes when methods
  524. # named _get_x and/or _set_x are found
  525. def __new__(metaclass, name, bases, dict):
  526. hits = {}
  527. for key, val in dict.iteritems():
  528. if key.startswith("_get_"):
  529. key = key[5:]
  530. get, set = hits.get(key, (None, None))
  531. get = val
  532. hits[key] = get, set
  533. elif key.startswith("_set_"):
  534. key = key[5:]
  535. get, set = hits.get(key, (None, None))
  536. set = val
  537. hits[key] = get, set
  538. for key, (get, set) in hits.iteritems():
  539. dict[key] = property(get, set)
  540. return super(autoproperty, metaclass).__new__(metaclass,
  541. name, bases, dict)
  542. class A:
  543. __metaclass__ = autoproperty
  544. def _get_x(self):
  545. return -self.__x
  546. def _set_x(self, x):
  547. self.__x = -x
  548. a = A()
  549. self.assertNotHasAttr(a, "x")
  550. a.x = 12
  551. self.assertEqual(a.x, 12)
  552. self.assertEqual(a._A__x, -12)
  553. class multimetaclass(autoproperty, autosuper):
  554. # Merge of multiple cooperating metaclasses
  555. pass
  556. class A:
  557. __metaclass__ = multimetaclass
  558. def _get_x(self):
  559. return "A"
  560. class B(A):
  561. def _get_x(self):
  562. return "B" + self.__super._get_x()
  563. class C(A):
  564. def _get_x(self):
  565. return "C" + self.__super._get_x()
  566. class D(C, B):
  567. def _get_x(self):
  568. return "D" + self.__super._get_x()
  569. self.assertEqual(D().x, "DCBA")
  570. # Make sure type(x) doesn't call x.__class__.__init__
  571. class T(type):
  572. counter = 0
  573. def __init__(self, *args):
  574. T.counter += 1
  575. class C:
  576. __metaclass__ = T
  577. self.assertEqual(T.counter, 1)
  578. a = C()
  579. self.assertEqual(type(a), C)
  580. self.assertEqual(T.counter, 1)
  581. class C(object): pass
  582. c = C()
  583. try: c()
  584. except TypeError: pass
  585. else: self.fail("calling object w/o call method should raise "
  586. "TypeError")
  587. # Testing code to find most derived baseclass
  588. class A(type):
  589. def __new__(*args, **kwargs):
  590. return type.__new__(*args, **kwargs)
  591. class B(object):
  592. pass
  593. class C(object):
  594. __metaclass__ = A
  595. # The most derived metaclass of D is A rather than type.
  596. class D(B, C):
  597. pass
  598. def test_module_subclasses(self):
  599. # Testing Python subclass of module...
  600. log = []
  601. MT = type(sys)
  602. class MM(MT):
  603. def __init__(self, name):
  604. MT.__init__(self, name)
  605. def __getattribute__(self, name):
  606. log.append(("getattr", name))
  607. return MT.__getattribute__(self, name)
  608. def __setattr__(self, name, value):
  609. log.append(("setattr", name, value))
  610. MT.__setattr__(self, name, value)
  611. def __delattr__(self, name):
  612. log.append(("delattr", name))
  613. MT.__delattr__(self, name)
  614. a = MM("a")
  615. a.foo = 12
  616. x = a.foo
  617. del a.foo
  618. self.assertEqual(log, [("setattr", "foo", 12),
  619. ("getattr", "foo"),
  620. ("delattr", "foo")])
  621. # http://python.org/sf/1174712
  622. try:
  623. class Module(types.ModuleType, str):
  624. pass
  625. except TypeError:
  626. pass
  627. else:
  628. self.fail("inheriting from ModuleType and str at the same time "
  629. "should fail")
  630. def test_multiple_inheritence(self):
  631. # Testing multiple inheritance...
  632. class C(object):
  633. def __init__(self):
  634. self.__state = 0
  635. def getstate(self):
  636. return self.__state
  637. def setstate(self, state):
  638. self.__state = state
  639. a = C()
  640. self.assertEqual(a.getstate(), 0)
  641. a.setstate(10)
  642. self.assertEqual(a.getstate(), 10)
  643. class D(dict, C):
  644. def __init__(self):
  645. type({}).__init__(self)
  646. C.__init__(self)
  647. d = D()
  648. self.assertEqual(d.keys(), [])
  649. d["hello"] = "world"
  650. self.assertEqual(d.items(), [("hello", "world")])
  651. self.assertEqual(d["hello"], "world")
  652. self.assertEqual(d.getstate(), 0)
  653. d.setstate(10)
  654. self.assertEqual(d.getstate(), 10)
  655. self.assertEqual(D.__mro__, (D, dict, C, object))
  656. # SF bug #442833
  657. class Node(object):
  658. def __int__(self):
  659. return int(self.foo())
  660. def foo(self):
  661. return "23"
  662. class Frag(Node, list):
  663. def foo(self):
  664. return "42"
  665. self.assertEqual(Node().__int__(), 23)
  666. self.assertEqual(int(Node()), 23)
  667. self.assertEqual(Frag().__int__(), 42)
  668. self.assertEqual(int(Frag()), 42)
  669. # MI mixing classic and new-style classes.
  670. class A:
  671. x = 1
  672. class B(A):
  673. pass
  674. class C(A):
  675. x = 2
  676. class D(B, C):
  677. pass
  678. self.assertEqual(D.x, 1)
  679. # Classic MRO is preserved for a classic base class.
  680. class E(D, object):
  681. pass
  682. self.assertEqual(E.__mro__, (E, D, B, A, C, object))
  683. self.assertEqual(E.x, 1)
  684. # But with a mix of classic bases, their MROs are combined using
  685. # new-style MRO.
  686. class F(B, C, object):
  687. pass
  688. self.assertEqual(F.__mro__, (F, B, C, A, object))
  689. self.assertEqual(F.x, 2)
  690. # Try something else.
  691. class C:
  692. def cmethod(self):
  693. return "C a"
  694. def all_method(self):
  695. return "C b"
  696. class M1(C, object):
  697. def m1method(self):
  698. return "M1 a"
  699. def all_method(self):
  700. return "M1 b"
  701. self.assertEqual(M1.__mro__, (M1, C, object))
  702. m = M1()
  703. self.assertEqual(m.cmethod(), "C a")
  704. self.assertEqual(m.m1method(), "M1 a")
  705. self.assertEqual(m.all_method(), "M1 b")
  706. class D(C):
  707. def dmethod(self):
  708. return "D a"
  709. def all_method(self):
  710. return "D b"
  711. class M2(D, object):
  712. def m2method(self):
  713. return "M2 a"
  714. def all_method(self):
  715. return "M2 b"
  716. self.assertEqual(M2.__mro__, (M2, D, C, object))
  717. m = M2()
  718. self.assertEqual(m.cmethod(), "C a")
  719. self.assertEqual(m.dmethod(), "D a")
  720. self.assertEqual(m.m2method(), "M2 a")
  721. self.assertEqual(m.all_method(), "M2 b")
  722. class M3(M1, M2, object):
  723. def m3method(self):
  724. return "M3 a"
  725. def all_method(self):
  726. return "M3 b"
  727. self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
  728. m = M3()
  729. self.assertEqual(m.cmethod(), "C a")
  730. self.assertEqual(m.dmethod(), "D a")
  731. self.assertEqual(m.m1method(), "M1 a")
  732. self.assertEqual(m.m2method(), "M2 a")
  733. self.assertEqual(m.m3method(), "M3 a")
  734. self.assertEqual(m.all_method(), "M3 b")
  735. class Classic:
  736. pass
  737. try:
  738. class New(Classic):
  739. __metaclass__ = type
  740. except TypeError:
  741. pass
  742. else:
  743. self.fail("new class with only classic bases - shouldn't be")
  744. def test_diamond_inheritence(self):
  745. # Testing multiple inheritance special cases...
  746. class A(object):
  747. def spam(self): return "A"
  748. self.assertEqual(A().spam(), "A")
  749. class B(A):
  750. def boo(self): return "B"
  751. def spam(self): return "B"
  752. self.assertEqual(B().spam(), "B")
  753. self.assertEqual(B().boo(), "B")
  754. class C(A):
  755. def boo(self): return "C"
  756. self.assertEqual(C().spam(), "A")
  757. self.assertEqual(C().boo(), "C")
  758. class D(B, C): pass
  759. self.assertEqual(D().spam(), "B")
  760. self.assertEqual(D().boo(), "B")
  761. self.assertEqual(D.__mro__, (D, B, C, A, object))
  762. class E(C, B): pass
  763. self.assertEqual(E().spam(), "B")
  764. self.assertEqual(E().boo(), "C")
  765. self.assertEqual(E.__mro__, (E, C, B, A, object))
  766. # MRO order disagreement
  767. try:
  768. class F(D, E): pass
  769. except TypeError:
  770. pass
  771. else:
  772. self.fail("expected MRO order disagreement (F)")
  773. try:
  774. class G(E, D): pass
  775. except TypeError:
  776. pass
  777. else:
  778. self.fail("expected MRO order disagreement (G)")
  779. # see thread python-dev/2002-October/029035.html
  780. def test_ex5_from_c3_switch(self):
  781. # Testing ex5 from C3 switch discussion...
  782. class A(object): pass
  783. class B(object): pass
  784. class C(object): pass
  785. class X(A): pass
  786. class Y(A): pass
  787. class Z(X,B,Y,C): pass
  788. self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
  789. # see "A Monotonic Superclass Linearization for Dylan",
  790. # by Kim Barrett et al. (OOPSLA 1996)
  791. def test_monotonicity(self):
  792. # Testing MRO monotonicity...
  793. class Boat(object): pass
  794. class DayBoat(Boat): pass
  795. class WheelBoat(Boat): pass
  796. class EngineLess(DayBoat): pass
  797. class SmallMultihull(DayBoat): pass
  798. class PedalWheelBoat(EngineLess,WheelBoat): pass
  799. class SmallCatamaran(SmallMultihull): pass
  800. class Pedalo(PedalWheelBoat,SmallCatamaran): pass
  801. self.assertEqual(PedalWheelBoat.__mro__,
  802. (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
  803. self.assertEqual(SmallCatamaran.__mro__,
  804. (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
  805. self.assertEqual(Pedalo.__mro__,
  806. (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
  807. SmallMultihull, DayBoat, WheelBoat, Boat, object))
  808. # see "A Monotonic Superclass Linearization for Dylan",
  809. # by Kim Barrett et al. (OOPSLA 1996)
  810. def test_consistency_with_epg(self):
  811. # Testing consistency with EPG...
  812. class Pane(object): pass
  813. class ScrollingMixin(object): pass
  814. class EditingMixin(object): pass
  815. class ScrollablePane(Pane,ScrollingMixin): pass
  816. class EditablePane(Pane,EditingMixin): pass
  817. class EditableScrollablePane(ScrollablePane,EditablePane): pass
  818. self.assertEqual(EditableScrollablePane.__mro__,
  819. (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
  820. ScrollingMixin, EditingMixin, object))
  821. def test_mro_disagreement(self):
  822. # Testing error messages for MRO disagreement...
  823. mro_err_msg = """Cannot create a consistent method resolution
  824. order (MRO) for bases """
  825. def raises(exc, expected, callable, *args):
  826. try:
  827. callable(*args)
  828. except exc, msg:
  829. # the exact msg is generally considered an impl detail
  830. if test_support.check_impl_detail():
  831. if not str(msg).startswith(expected):
  832. self.fail("Message %r, expected %r" %
  833. (str(msg), expected))
  834. else:
  835. self.fail("Expected %s" % exc)
  836. class A(object): pass
  837. class B(A): pass
  838. class C(object): pass
  839. # Test some very simple errors
  840. raises(TypeError, "duplicate base class A",
  841. type, "X", (A, A), {})
  842. raises(TypeError, mro_err_msg,
  843. type, "X", (A, B), {})
  844. raises(TypeError, mro_err_msg,
  845. type, "X", (A, C, B), {})
  846. # Test a slightly more complex error
  847. class GridLayout(object): pass
  848. class HorizontalGrid(GridLayout): pass
  849. class VerticalGrid(GridLayout): pass
  850. class HVGrid(HorizontalGrid, VerticalGrid): pass
  851. class VHGrid(VerticalGrid, HorizontalGrid): pass
  852. raises(TypeError, mro_err_msg,
  853. type, "ConfusedGrid", (HVGrid, VHGrid), {})
  854. def test_object_class(self):
  855. # Testing object class...
  856. a = object()
  857. self.assertEqual(a.__class__, object)
  858. self.assertEqual(type(a), object)
  859. b = object()
  860. self.assertNotEqual(a, b)
  861. self.assertNotHasAttr(a, "foo")
  862. try:
  863. a.foo = 12
  864. except (AttributeError, TypeError):
  865. pass
  866. else:
  867. self.fail("object() should not allow setting a foo attribute")
  868. self.assertNotHasAttr(object(), "__dict__")
  869. class Cdict(object):
  870. pass
  871. x = Cdict()
  872. self.assertEqual(x.__dict__, {})
  873. x.foo = 1
  874. self.assertEqual(x.foo, 1)
  875. self.assertEqual(x.__dict__, {'foo': 1})
  876. def test_slots(self):
  877. # Testing __slots__...
  878. class C0(object):
  879. __slots__ = []
  880. x = C0()
  881. self.assertNotHasAttr(x, "__dict__")
  882. self.assertNotHasAttr(x, "foo")
  883. class C1(object):
  884. __slots__ = ['a']
  885. x = C1()
  886. self.assertNotHasAttr(x, "__dict__")
  887. self.assertNotHasAttr(x, "a")
  888. x.a = 1
  889. self.assertEqual(x.a, 1)
  890. x.a = None
  891. self.assertEqual(x.a, None)
  892. del x.a
  893. self.assertNotHasAttr(x, "a")
  894. class C3(object):
  895. __slots__ = ['a', 'b', 'c']
  896. x = C3()
  897. self.assertNotHasAttr(x, "__dict__")
  898. self.assertNotHasAttr(x, 'a')
  899. self.assertNotHasAttr(x, 'b')
  900. self.assertNotHasAttr(x, 'c')
  901. x.a = 1
  902. x.b = 2
  903. x.c = 3
  904. self.assertEqual(x.a, 1)
  905. self.assertEqual(x.b, 2)
  906. self.assertEqual(x.c, 3)
  907. class C4(object):
  908. """Validate name mangling"""
  909. __slots__ = ['__a']
  910. def __init__(self, value):
  911. self.__a = value
  912. def get(self):
  913. return self.__a
  914. x = C4(5)
  915. self.assertNotHasAttr(x, '__dict__')
  916. self.assertNotHasAttr(x, '__a')
  917. self.assertEqual(x.get(), 5)
  918. try:
  919. x.__a = 6
  920. except AttributeError:
  921. pass
  922. else:
  923. self.fail("Double underscored names not mangled")
  924. # Make sure slot names are proper identifiers
  925. try:
  926. class C(object):
  927. __slots__ = [None]
  928. except TypeError:
  929. pass
  930. else:
  931. self.fail("[None] slots not caught")
  932. try:
  933. class C(object):
  934. __slots__ = ["foo bar"]
  935. except TypeError:
  936. pass
  937. else:
  938. self.fail("['foo bar'] slots not caught")
  939. try:
  940. class C(object):
  941. __slots__ = ["foo\0bar"]
  942. except TypeError:
  943. pass
  944. else:
  945. self.fail("['foo\\0bar'] slots not caught")
  946. try:
  947. class C(object):
  948. __slots__ = ["1"]
  949. except TypeError:
  950. pass
  951. else:
  952. self.fail("['1'] slots not caught")
  953. try:
  954. class C(object):
  955. __slots__ = [""]
  956. except TypeError:
  957. pass
  958. else:
  959. self.fail("[''] slots not caught")
  960. class C(object):
  961. __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
  962. # XXX(nnorwitz): was there supposed to be something tested
  963. # from the class above?
  964. # Test a single string is not expanded as a sequence.
  965. class C(object):
  966. __slots__ = "abc"
  967. c = C()
  968. c.abc = 5
  969. self.assertEqual(c.abc, 5)
  970. def test_unicode_slots(self):
  971. # Test unicode slot names
  972. try:
  973. unicode
  974. except NameError:
  975. self.skipTest('no unicode support')
  976. else:
  977. # Test a single unicode string is not expanded as a sequence.
  978. class C(object):
  979. __slots__ = unicode("abc")
  980. c = C()
  981. c.abc = 5
  982. self.assertEqual(c.abc, 5)
  983. # _unicode_to_string used to modify slots in certain circumstances
  984. slots = (unicode("foo"), unicode("bar"))
  985. class C(object):
  986. __slots__ = slots
  987. x = C()
  988. x.foo = 5
  989. self.assertEqual(x.foo, 5)
  990. self.assertEqual(type(slots[0]), unicode)
  991. # this used to leak references
  992. try:
  993. class C(object):
  994. __slots__ = [unichr(128)]
  995. except (TypeError, UnicodeEncodeError):
  996. pass
  997. else:
  998. self.fail("[unichr(128)] slots not caught")
  999. # Test leaks
  1000. class Counted(object):
  1001. counter = 0 # counts the number of instances alive
  1002. def __init__(self):
  1003. Counted.counter += 1
  1004. def __del__(self):
  1005. Counted.counter -= 1
  1006. class C(object):
  1007. __slots__ = ['a', 'b', 'c']
  1008. x = C()
  1009. x.a = Counted()
  1010. x.b = Counted()
  1011. x.c = Counted()
  1012. self.assertEqual(Counted.counter, 3)
  1013. del x
  1014. test_support.gc_collect()
  1015. self.assertEqual(Counted.counter, 0)
  1016. class D(C):
  1017. pass
  1018. x = D()
  1019. x.a = Counted()
  1020. x.z = Counted()
  1021. self.assertEqual(Counted.counter, 2)
  1022. del x
  1023. test_support.gc_collect()
  1024. self.assertEqual(Counted.counter, 0)
  1025. class E(D):
  1026. __slots__ = ['e']
  1027. x = E()
  1028. x.a = Counted()
  1029. x.z = Counted()
  1030. x.e = Counted()
  1031. self.assertEqual(Counted.counter, 3)
  1032. del x
  1033. test_support.gc_collect()
  1034. self.assertEqual(Counted.counter, 0)
  1035. # Test cyclical leaks [SF bug 519621]
  1036. class F(object):
  1037. __slots__ = ['a', 'b']
  1038. s = F()
  1039. s.a = [Counted(), s]
  1040. self.assertEqual(Counted.counter, 1)
  1041. s = None
  1042. test_support.gc_collect()
  1043. self.assertEqual(Counted.counter, 0)
  1044. # Test lookup leaks [SF bug 572567]
  1045. if hasattr(gc, 'get_objects'):
  1046. class G(object):
  1047. def __cmp__(self, other):
  1048. return 0
  1049. __hash__ = None # Silence Py3k warning
  1050. g = G()
  1051. orig_objects = len(gc.get_objects())
  1052. for i in xrange(10):
  1053. g==g
  1054. new_objects = len(gc.get_objects())
  1055. self.assertEqual(orig_objects, new_objects)
  1056. class H(object):
  1057. __slots__ = ['a', 'b']
  1058. def __init__(self):
  1059. self.a = 1
  1060. self.b = 2
  1061. def __del__(self_):
  1062. self.assertEqual(self_.a, 1)
  1063. self.assertEqual(self_.b, 2)
  1064. with test_support.captured_output('stderr') as s:
  1065. h = H()
  1066. del h
  1067. self.assertEqual(s.getvalue(), '')
  1068. class X(object):
  1069. __slots__ = "a"
  1070. with self.assertRaises(AttributeError):
  1071. del X().a
  1072. def test_slots_special(self):
  1073. # Testing __dict__ and __weakref__ in __slots__...
  1074. class D(object):
  1075. __slots__ = ["__dict__"]
  1076. a = D()
  1077. self.assertHasAttr(a, "__dict__")
  1078. self.assertNotHasAttr(a, "__weakref__")
  1079. a.foo = 42
  1080. self.assertEqual(a.__dict__, {"foo": 42})
  1081. class W(object):
  1082. __slots__ = ["__weakref__"]
  1083. a = W()
  1084. self.assertHasAttr(a, "__weakref__")
  1085. self.assertNotHasAttr(a, "__dict__")
  1086. try:
  1087. a.foo = 42
  1088. except AttributeError:
  1089. pass
  1090. else:
  1091. self.fail("shouldn't be allowed to set a.foo")
  1092. class C1(W, D):
  1093. __slots__ = []
  1094. a = C1()
  1095. self.assertHasAttr(a, "__dict__")
  1096. self.assertHasAttr(a, "__weakref__")
  1097. a.foo = 42
  1098. self.assertEqual(a.__dict__, {"foo": 42})
  1099. class C2(D, W):
  1100. __slots__ = []
  1101. a = C2()
  1102. self.assertHasAttr(a, "__dict__")
  1103. self.assertHasAttr(a, "__weakref__")
  1104. a.foo = 42
  1105. self.assertEqual(a.__dict__, {"foo": 42})
  1106. def test_slots_descriptor(self):
  1107. # Issue2115: slot descriptors did not correctly check
  1108. # the type of the given object
  1109. import abc
  1110. class MyABC:
  1111. __metaclass__ = abc.ABCMeta
  1112. __slots__ = "a"
  1113. class Unrelated(object):
  1114. pass
  1115. MyABC.register(Unrelated)
  1116. u = Unrelated()
  1117. self.assertIsInstance(u, MyABC)
  1118. # This used to crash
  1119. self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
  1120. def test_metaclass_cmp(self):
  1121. # See bug 7491.
  1122. class M(type):
  1123. def __cmp__(self, other):
  1124. return -1
  1125. class X(object):
  1126. __metaclass__ = M
  1127. self.assertTrue(X < M)
  1128. def test_dynamics(self):
  1129. # Testing class attribute propagation...
  1130. class D(object):
  1131. pass
  1132. class E(D):
  1133. pass
  1134. class F(D):
  1135. pass
  1136. D.foo = 1
  1137. self.assertEqual(D.foo, 1)
  1138. # Test that dynamic attributes are inherited
  1139. self.assertEqual(E.foo, 1)
  1140. self.assertEqual(F.foo, 1)
  1141. # Test dynamic instances
  1142. class C(object):
  1143. pass
  1144. a = C()
  1145. self.assertNotHasAttr(a, "foobar")
  1146. C.foobar = 2
  1147. self.assertEqual(a.foobar, 2)
  1148. C.method = lambda self: 42
  1149. self.assertEqual(a.method(), 42)
  1150. C.__repr__ = lambda self: "C()"
  1151. self.assertEqual(repr(a), "C()")
  1152. C.__int__ = lambda self: 100
  1153. self.assertEqual(int(a), 100)
  1154. self.assertEqual(a.foobar, 2)
  1155. self.assertNotHasAttr(a, "spam")
  1156. def mygetattr(self, name):
  1157. if name == "spam":
  1158. return "spam"
  1159. raise AttributeError
  1160. C.__getattr__ = mygetattr
  1161. self.assertEqual(a.spam, "spam")
  1162. a.new = 12
  1163. self.assertEqual(a.new, 12)
  1164. def mysetattr(self, name, value):
  1165. if name == "spam":
  1166. raise AttributeError
  1167. return object.__setattr__(self, name, value)
  1168. C.__setattr__ = mysetattr
  1169. try:
  1170. a.spam = "not spam"
  1171. except AttributeError:
  1172. pass
  1173. else:
  1174. self.fail("expected AttributeError")
  1175. self.assertEqual(a.spam, "spam")
  1176. class D(C):
  1177. pass
  1178. d = D()
  1179. d.foo = 1
  1180. self.assertEqual(d.foo, 1)
  1181. # Test handling of int*seq and seq*int
  1182. class I(int):
  1183. pass
  1184. self.assertEqual("a"*I(2), "aa")
  1185. self.assertEqual(I(2)*"a", "aa")
  1186. self.assertEqual(2*I(3), 6)
  1187. self.assertEqual(I(3)*2, 6)
  1188. self.assertEqual(I(3)*I(2), 6)
  1189. # Test handling of long*seq and seq*long
  1190. class L(long):
  1191. pass
  1192. self.assertEqual("a"*L(2L), "aa")
  1193. self.assertEqual(L(2L)*"a", "aa")
  1194. self.assertEqual(2*L(3), 6)
  1195. self.assertEqual(L(3)*2, 6)
  1196. self.assertEqual(L(3)*L(2), 6)
  1197. # Test comparison of classes with dynamic metaclasses
  1198. class dynamicmetaclass(type):
  1199. pass
  1200. class someclass:
  1201. __metaclass__ = dynamicmetaclass
  1202. self.assertNotEqual(someclass, object)
  1203. def test_errors(self):
  1204. # Testing errors...
  1205. try:
  1206. class C(list, dict):
  1207. pass
  1208. except TypeError:
  1209. pass
  1210. else:
  1211. self.fail("inheritance from both list and dict should be illegal")
  1212. try:
  1213. class C(object, None):
  1214. pass
  1215. except TypeError:
  1216. pass
  1217. else:
  1218. self.fail("inheritance from non-type should be illegal")
  1219. class Classic:
  1220. pass
  1221. try:
  1222. class C(type(len)):
  1223. pass
  1224. except TypeError:
  1225. pass
  1226. else:
  1227. self.fail("inheritance from CFunction should be illegal")
  1228. try:
  1229. class C(object):
  1230. __slots__ = 1
  1231. except TypeError:
  1232. pass
  1233. else:
  1234. self.fail("__slots__ = 1 should be illegal")
  1235. try:
  1236. class C(object):
  1237. __slots__ = [1]
  1238. except TypeError:
  1239. pass
  1240. else:
  1241. self.fail("__slots__ = [1] should be illegal")
  1242. class M1(type):
  1243. pass
  1244. class M2(type):
  1245. pass
  1246. class A1(object):
  1247. __metaclass__ = M1
  1248. class A2(object):
  1249. __metaclass__ = M2
  1250. try:
  1251. class B(A1, A2):
  1252. pass
  1253. except TypeError:
  1254. pass
  1255. else:
  1256. self.fail("finding the most derived metaclass should have failed")
  1257. def test_classmethods(self):
  1258. # Testing class methods...
  1259. class C(object):
  1260. def foo(*a): return a
  1261. goo = classmethod(foo)
  1262. c = C()
  1263. self.assertEqual(C.goo(1), (C, 1))
  1264. self.assertEqual(c.goo(1), (C, 1))
  1265. self.assertEqual(c.foo(1), (c, 1))
  1266. class D(C):
  1267. pass
  1268. d = D()
  1269. self.assertEqual(D.goo(1), (D, 1))
  1270. self.assertEqual(d.goo(1), (D, 1))
  1271. self.assertEqual(d.foo(1), (d, 1))
  1272. self.assertEqual(D.foo(d, 1), (d, 1))
  1273. # Test for a specific crash (SF bug 528132)
  1274. def f(cls, arg): return (cls, arg)
  1275. ff = classmethod(f)
  1276. self.assertEqual(ff.__get__(0, int)(42), (int, 42))
  1277. self.assertEqual(ff.__get__(0)(42), (int, 42))
  1278. # Test super() with classmethods (SF bug 535444)
  1279. self.assertEqual(C.goo.im_self, C)
  1280. self.assertEqual(D.goo.im_self, D)
  1281. self.assertEqual(super(D,D).goo.im_self, D)
  1282. self.assertEqual(super(D,d).goo.im_self, D)
  1283. self.assertEqual(super(D,D).goo(), (D,))
  1284. self.assertEqual(super(D,d).goo(), (D,))
  1285. # Verify that a non-callable will raise
  1286. meth = classmethod(1).__get__(1)
  1287. self.assertRaises(TypeError, meth)
  1288. # Verify that classmethod() doesn't allow keyword args
  1289. try:
  1290. classmethod(f, kw=1)
  1291. except TypeError:
  1292. pass
  1293. else:
  1294. self.fail("classmethod shouldn't accept keyword args")
  1295. @test_support.impl_detail("the module 'xxsubtype' is internal")
  1296. def test_classmethods_in_c(self):
  1297. # Testing C-based class methods...
  1298. import xxsubtype as spam
  1299. a = (1, 2, 3)
  1300. d = {'abc': 123}
  1301. x, a1, d1 = spam.spamlist.classmeth(*a, **d)
  1302. self.assertEqual(x, spam.spamlist)
  1303. self.assertEqual(a, a1)
  1304. self.assertEqual(d, d1)
  1305. x, a1, d1 = spam.spamlist().classmeth(*a, **d)
  1306. self.assertEqual(x, spam.spamlist)
  1307. self.assertEqual(a, a1)
  1308. self.assertEqual(d, d1)
  1309. spam_cm = spam.spamlist.__dict__['classmeth']
  1310. x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
  1311. self.assertEqual(x2, spam.spamlist)
  1312. self.assertEqual(a2, a1)
  1313. self.assertEqual(d2, d1)
  1314. class SubSpam(spam.spamlist): pass
  1315. x2, a2, d2 = spam_cm(SubSpam, *a, **d)
  1316. self.assertEqual(x2, SubSpam)
  1317. self.assertEqual(a2, a1)
  1318. self.assertEqual(d2, d1)
  1319. with self.assertRaises(TypeError):
  1320. spam_cm()
  1321. with self.assertRaises(TypeError):
  1322. spam_cm(spam.spamlist())
  1323. with self.assertRaises(TypeError):
  1324. spam_cm(list)
  1325. def test_staticmethods(self):
  1326. # Testing static methods...
  1327. class C(object):
  1328. def foo(*a): return a
  1329. goo = staticmethod(foo)
  1330. c = C()
  1331. self.assertEqual(C.goo(1), (1,))
  1332. self.assertEqual(c.goo(1), (1,))
  1333. self.assertEqual(c.foo(1), (c, 1,))
  1334. class D(C):
  1335. pass
  1336. d = D()
  1337. self.assertEqual(D.goo(1), (1,))
  1338. self.assertEqual(d.goo(1), (1,))
  1339. self.assertEqual(d.foo(1), (d, 1))
  1340. self.assertEqual(D.foo(d, 1), (d, 1))
  1341. @test_support.impl_detail("the module 'xxsubtype' is internal")
  1342. def test_staticmethods_in_c(self):
  1343. # Testing C-based static methods...
  1344. import xxsubtype as spam
  1345. a = (1, 2, 3)
  1346. d = {"abc": 123}
  1347. x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
  1348. self.assertEqual(x, None)
  1349. self.assertEqual(a, a1)
  1350. self.assertEqual(d, d1)
  1351. x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
  1352. self.assertEqual(x, None)
  1353. self.assertEqual(a, a1)
  1354. self.assertEqual(d, d1)
  1355. def test_classic(self):
  1356. # Testing classic classes...
  1357. class C:
  1358. def foo(*a): return a
  1359. goo = classmethod(foo)
  1360. c = C()
  1361. self.assertEqual(C.goo(1), (C, 1))
  1362. self.assertEqual(c.goo(1), (C, 1))
  1363. self.assertEqual(c.foo(1), (c, 1))
  1364. class D(C):
  1365. pass
  1366. d = D()
  1367. self.assertEqual(D.goo(1), (D, 1))
  1368. self.assertEqual(d.goo(1), (D, 1))
  1369. self.assertEqual(d.foo(1), (d, 1))
  1370. self.assertEqual(D.foo(d, 1), (d, 1))
  1371. class E: # *not* subclassing from C
  1372. foo = C.foo
  1373. self.assertEqual(E().foo, C.foo) # i.e., unbound
  1374. self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
  1375. def test_compattr(self):
  1376. # Testing computed attributes...
  1377. class C(object):
  1378. class computed_attribute(object):
  1379. def __init__(self, get, set=None, delete=None):
  1380. self.__get = get
  1381. self.__set = set
  1382. self.__delete = delete
  1383. def __get__(self, obj, type=None):
  1384. return self.__get(obj)
  1385. def __set__(self, obj, value):
  1386. return self.__set(obj, value)
  1387. def __delete__(self, obj):
  1388. return self.__delete(obj)
  1389. def __init__(self):
  1390. self.__x = 0
  1391. def __get_x(self):
  1392. x = self.__x
  1393. self.__x = x+1
  1394. return x
  1395. def __set_x(self, x):
  1396. self.__x = x
  1397. def __delete_x(self):
  1398. del self.__x
  1399. x = computed_attribute(__get_x, __set_x, __delete_x)
  1400. a = C()
  1401. self.assertEqual(a.x, 0)
  1402. self.assertEqual(a.x, 1)
  1403. a.x = 10
  1404. self.assertEqual(a.x, 10)
  1405. self.assertEqual(a.x, 11)
  1406. del a.x
  1407. self.assertNotHasAttr(a, 'x')
  1408. def test_newslots(self):
  1409. # Testing __new__ slot override...
  1410. class C(list):
  1411. def __new__(cls):
  1412. self = list.__new__(cls)
  1413. self.foo = 1
  1414. return self
  1415. def __init__(self):
  1416. self.foo = self.foo + 2
  1417. a = C()
  1418. self.assertEqual(a.foo, 3)
  1419. self.assertEqual(a.__class__, C)
  1420. class D(C):
  1421. pass
  1422. b = D()
  1423. self.assertEqual(b.foo, 3)
  1424. self.assertEqual(b.__class__, D)
  1425. def test_altmro(self):
  1426. # Testing mro() and overriding it...
  1427. class A(object):
  1428. def f(self): return "A"
  1429. class B(A):
  1430. pass
  1431. class C(A):
  1432. def f(self): return "C"
  1433. class D(B, C):
  1434. pass
  1435. self.assertEqual(D.mro(), [D, B, C, A, object])
  1436. self.assertEqual(D.__mro__, (D, B, C, A, object))
  1437. self.assertEqual(D().f(), "C")
  1438. class PerverseMetaType(type):
  1439. def mro(cls):
  1440. L = type.mro(cls)
  1441. L.reverse()
  1442. return L
  1443. class X(D,B,C,A):
  1444. __metaclass__ = PerverseMetaType
  1445. self.assertEqual(X.__mro__, (object, A, C, B, D, X))
  1446. self.assertEqual(X().f(), "A")
  1447. try:
  1448. class X(object):
  1449. class __metaclass__(type):
  1450. def mro(self):
  1451. return [self, dict, object]
  1452. # In CPython, the class creation above already raises
  1453. # TypeError, as a protection against the fact that
  1454. # instances of X would segfault it. In other Python
  1455. # implementations it would be ok to let the class X
  1456. # be created, but instead get a clean TypeError on the
  1457. # __setitem__ below.
  1458. x = object.__new__(X)
  1459. x[5] = 6
  1460. except TypeError:
  1461. pass
  1462. else:
  1463. self.fail("devious mro() return not caught")
  1464. try:
  1465. class X(object):
  1466. class __metaclass__(type):
  1467. def mro(self):
  1468. return [1]
  1469. except TypeError:
  1470. pass
  1471. else:
  1472. self.fail("non-class mro() return not caught")
  1473. try:
  1474. class X(object):
  1475. class __metaclass__(type):
  1476. def mro(self):
  1477. return 1
  1478. except TypeError:
  1479. pass
  1480. else:
  1481. self.fail("non-sequence mro() return not caught")
  1482. def test_overloading(self):
  1483. # Testing operator overloading...
  1484. class B(object):
  1485. "Intermediate class because object doesn't have a __setattr__"
  1486. class C(B):
  1487. def __getattr__(self, name):
  1488. if name == "foo":
  1489. return ("getattr", name)
  1490. else:
  1491. raise AttributeError
  1492. def __setattr__(self, name, value):
  1493. if name == "foo":
  1494. self.setattr = (name, value)
  1495. else:
  1496. return B.__setattr__(self, name, value)
  1497. def __delattr__(self, name):
  1498. if name == "foo":
  1499. self.delattr = name
  1500. else:
  1501. return B.__delattr__(self, name)
  1502. def __getitem__(self, key):
  1503. return ("getitem", key)
  1504. def __setitem__(self, key, value):
  1505. self.setitem = (key, value)
  1506. def __delitem__(self, key):
  1507. self.delitem = key
  1508. def __getslice__(self, i, j):
  1509. return ("getslice", i, j)
  1510. def __setslice__(self, i, j, value):
  1511. self.setslice = (i, j, value)
  1512. def __delslice__(self, i, j):
  1513. self.delslice = (i, j)
  1514. a = C()
  1515. self.assertEqual(a.foo, ("getattr", "foo"))
  1516. a.foo = 12
  1517. self.assertEqual(a.setattr, ("foo", 12))
  1518. del a.foo
  1519. self.assertEqual(a.delattr, "foo")
  1520. self.assertEqual(a[12], ("getitem", 12))
  1521. a[12] = 21
  1522. self.assertEqual(a.setitem, (12, 21))
  1523. del a[12]
  1524. self.assertEqual(a.delitem, 12)
  1525. self.assertEqual(a[0:10], ("getslice", 0, 10))
  1526. a[0:10] = "foo"
  1527. self.assertEqual(a.setslice, (0, 10, "foo"))
  1528. del a[0:10]
  1529. self.assertEqual(a.delslice, (0, 10))
  1530. def test_methods(self):
  1531. # Testing methods...
  1532. class C(object):
  1533. def __init__(self, x):
  1534. self.x = x
  1535. def foo(self):
  1536. return self.x
  1537. c1 = C(1)
  1538. self.assertEqual(c1.foo(), 1)
  1539. class D(C):
  1540. boo = C.foo
  1541. goo = c1.foo
  1542. d2 = D(2)
  1543. self.assertEqual(d2.foo(), 2)
  1544. self.assertEqual(d2.boo(), 2)
  1545. self.assertEqual(d2.goo(), 1)
  1546. class E(object):
  1547. foo = C.foo
  1548. self.assertEqual(E().foo, C.foo) # i.e., unbound
  1549. self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
  1550. def test_special_method_lookup(self):
  1551. # The lookup of special methods bypasses __getattr__ and
  1552. # __getattribute__, but they still can be descriptors.
  1553. def run_context(manager):
  1554. with manager:
  1555. pass
  1556. def iden(self):
  1557. return self
  1558. def hello(self):
  1559. return "hello"
  1560. def empty_seq(self):
  1561. return []
  1562. def zero(self):
  1563. return 0
  1564. def complex_num(self):
  1565. return 1j
  1566. def stop(self):
  1567. raise StopIteration
  1568. def return_true(self, thing=None):
  1569. return True
  1570. def do_isinstance(obj):
  1571. return isinstance(int, obj)
  1572. def do_issubclass(obj):
  1573. return issubclass(int, obj)
  1574. def swallow(*args):
  1575. pass
  1576. def do_dict_missing(checker):
  1577. class DictSub(checker.__class__, dict):
  1578. pass
  1579. self.assertEqual(DictSub()["hi"], 4)
  1580. def some_number(self_, key):
  1581. self.assertEqual(key, "hi")
  1582. return 4
  1583. def format_impl(self, spec):
  1584. return "hello"
  1585. # It would be nice to have every special method tested here, but I'm
  1586. # only listing the ones I can remember outside of typeobject.c, since it
  1587. # does it right.
  1588. specials = [
  1589. ("__unicode__", unicode, hello, set(), {}),
  1590. ("__reversed__", reversed, empty_seq, set(), {}),
  1591. ("__length_hint__", list, zero, set(),
  1592. {"__iter__" : iden, "next" : stop}),
  1593. ("__sizeof__", sys.getsizeof, zero, set(), {}),
  1594. ("__instancecheck__", do_isinstance, return_true, set(), {}),
  1595. ("__missing__", do_dict_missing, some_number,
  1596. set(("__class__",)), {}),
  1597. ("__subclasscheck__", do_issubclass, return_true,
  1598. set(("__bases__",)), {}),
  1599. ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
  1600. ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
  1601. ("__complex__", complex, complex_num, set(), {}),
  1602. ("__format__", format, format_impl, set(), {}),
  1603. ("__dir__", dir, empty_seq, set(), {}),
  1604. ]
  1605. class Checker(object):
  1606. def __getattr__(self, attr, test=self):
  1607. test.fail("__getattr__ called with {0}".format(attr))
  1608. def __getattribute__(self, attr, test=self):
  1609. if attr not in ok:
  1610. test.fail("__getattribute__ called with {0}".format(attr))
  1611. return object.__getattribute__(self, attr)
  1612. class SpecialDescr(object):
  1613. def __init__(self, impl):
  1614. self.impl = impl
  1615. def __get__(self, obj, owner):
  1616. record.append(1)
  1617. return self.impl.__get__(obj, owner)
  1618. class MyException(Exception):
  1619. pass
  1620. class ErrDescr(object):
  1621. def __get__(self, obj, owner):
  1622. raise MyException
  1623. for name, runner, meth_impl, ok, env in specials:
  1624. class X(Checker):
  1625. pass
  1626. for attr, obj in env.iteritems():
  1627. setattr(X, attr, obj)
  1628. setattr(X, name, meth_impl)
  1629. runner(X())
  1630. record = []
  1631. class X(Checker):
  1632. pass
  1633. for attr, obj in env.iteritems():
  1634. setattr(X, attr, obj)
  1635. setattr(X, name, SpecialDescr(meth_impl))
  1636. runner(X())
  1637. self.assertEqual(record, [1], name)
  1638. class X(Checker):
  1639. pass
  1640. for attr, obj in env.iteritems():
  1641. setattr(X, attr, obj)
  1642. setattr(X, name, ErrDescr())
  1643. try:
  1644. runner(X())
  1645. except MyException:
  1646. pass
  1647. else:
  1648. self.fail("{0!r} didn't raise".format(name))
  1649. def test_specials(self):
  1650. # Testing special operators...
  1651. # Test operators like __hash__ for which a built-in default exists
  1652. # Test the default behavior for static classes
  1653. class C(object):
  1654. def __getitem__(self, i):
  1655. if 0 <= i < 10: return i
  1656. raise IndexError
  1657. c1 = C()
  1658. c2 = C()
  1659. self.assertFalse(not c1)
  1660. self.assertNotEqual(id(c1), id(c2))
  1661. hash(c1)
  1662. hash(c2)
  1663. self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
  1664. self.assertEqual(c1, c1)
  1665. self.assertTrue(c1 != c2)
  1666. self.assertFalse(c1 != c1)
  1667. self.assertFalse(c1 == c2)
  1668. # Note that the module name appears in str/repr, and that varies
  1669. # depending on whether this test is run standalone or from a framework.
  1670. self.assertGreaterEqual(str(c1).find('C object at '), 0)
  1671. self.assertEqual(str(c1), repr(c1))
  1672. self.assertNotIn(-1, c1)
  1673. for i in range(10):
  1674. self.assertIn(i, c1)
  1675. self.assertNotIn(10, c1)
  1676. # Test the default behavior for dynamic classes
  1677. class D(object):
  1678. def __getitem__(self, i):
  1679. if 0 <= i < 10: return i
  1680. raise IndexError
  1681. d1 = D()
  1682. d2 = D()
  1683. self.assertFalse(not d1)
  1684. self.assertNotEqual(id(d1), id(d2))
  1685. hash(d1)
  1686. hash(d2)
  1687. self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
  1688. self.assertEqual(d1, d1)
  1689. self.assertNotEqual(d1, d2)
  1690. self.assertFalse(d1 != d1)
  1691. self.assertFalse(d1 == d2)
  1692. # Note that the module name appears in str/repr, and that varies
  1693. # depending on whether this test is run standalone or from a framework.
  1694. self.assertGreaterEqual(str(d1).find('D object at '), 0)
  1695. self.assertEqual(str(d1), repr(d1))
  1696. self.assertNotIn(-1, d1)
  1697. for i in range(10):
  1698. self.assertIn(i, d1)
  1699. self.assertNotIn(10, d1)
  1700. # Test overridden behavior for static classes
  1701. class Proxy(object):
  1702. def __init__(self, x):
  1703. self.x = x
  1704. def __nonzero__(self):
  1705. return not not self.x
  1706. def __hash__(self):
  1707. return hash(self.x)
  1708. def __eq__(self, other):
  1709. return self.x == other
  1710. def __ne__(self, other):
  1711. return self.x != other
  1712. def __cmp__(self, other):
  1713. return cmp(self.x, other.x)
  1714. def __str__(self):
  1715. return "Proxy:%s" % self.x
  1716. def __repr__(self):
  1717. return "Proxy(%r)" % self.x
  1718. def __contains__(self, value):
  1719. return value in self.x
  1720. p0 = Proxy(0)
  1721. p1 = Proxy(1)
  1722. p_1 = Proxy(-1)
  1723. self.assertFalse(p0)
  1724. self.assertFalse(not p1)
  1725. self.assertEqual(hash(p0), hash(0))
  1726. self.assertEqual(p0, p0)
  1727. self.assertNotEqual(p0, p1)
  1728. self.assertFalse(p0 != p0)
  1729. self.assertEqual(not p0, p1)
  1730. self.assertEqual(cmp(p0, p1), -1)
  1731. self.assertEqual(cmp(p0, p0), 0)
  1732. self.assertEqual(cmp(p0, p_1), 1)
  1733. self.assertEqual(str(p0), "Proxy:0")
  1734. self.assertEqual(repr(p0), "Proxy(0)")
  1735. p10 = Proxy(range(10))
  1736. self.assertNotIn(-1, p10)
  1737. for i in range(10):
  1738. self.assertIn(i, p10)
  1739. self.assertNotIn(10, p10)
  1740. # Test overridden behavior for dynamic classes
  1741. class DProxy(object):
  1742. def __init__(self, x):
  1743. self.x = x
  1744. def __nonzero__(self):
  1745. return not not self.x
  1746. def __hash__(self):
  1747. return hash(self.x)
  1748. def __eq__(self, other):
  1749. return self.x == other
  1750. def __ne__(self, other):
  1751. return self.x != other
  1752. def __cmp__(self, other):
  1753. return cmp(self.x, other.x)
  1754. def __str__(self):
  1755. return "DProxy:%s" % self.x
  1756. def __repr__(self):
  1757. return "DProxy(%r)" % self.x
  1758. def __contains__(self, value):
  1759. return value in self.x
  1760. p0 = DProxy(0)
  1761. p1 = DProxy(1)
  1762. p_1 = DProxy(-1)
  1763. self.assertFalse(p0)
  1764. self.assertFalse(not p1)
  1765. self.assertEqual(hash(p0), hash(0))
  1766. self.assertEqual(p0, p0)
  1767. self.assertNotEqual(p0, p1)
  1768. self.assertNotEqual(not p0, p0)
  1769. self.assertEqual(not p0, p1)
  1770. self.assertEqual(cmp(p0, p1), -1)
  1771. self.assertEqual(cmp(p0, p0), 0)
  1772. self.assertEqual(cmp(p0, p_1), 1)
  1773. self.assertEqual(str(p0), "DProxy:0")
  1774. self.assertEqual(repr(p0), "DProxy(0)")
  1775. p10 = DProxy(range(10))
  1776. self.assertNotIn(-1, p10)
  1777. for i in range(10):
  1778. self.assertIn(i, p10)
  1779. self.assertNotIn(10, p10)
  1780. # Safety test for __cmp__
  1781. def unsafecmp(a, b):
  1782. if not hasattr(a, '__cmp__'):
  1783. return # some types don't have a __cmp__ any more (so the
  1784. # test doesn't make sense any more), or maybe they
  1785. # never had a __cmp__ at all, e.g. in PyPy
  1786. try:
  1787. a.__class__.__cmp__(a, b)
  1788. except TypeError:
  1789. pass
  1790. else:
  1791. self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
  1792. a.__class__, a, b))
  1793. unsafecmp(u"123", "123")
  1794. unsafecmp("123", u"123")
  1795. unsafecmp(1, 1.0)
  1796. unsafecmp(1.0, 1)
  1797. unsafecmp(1, 1L)
  1798. unsafecmp(1L, 1)
  1799. @test_support.impl_detail("custom logic for printing to real file objects")
  1800. def test_recursions_1(self):
  1801. # Testing recursion checks ...
  1802. class Letter(str):
  1803. def __new__(cls, letter):
  1804. if letter == 'EPS':
  1805. return str.__new__(cls)
  1806. return str.__new__(cls, letter)
  1807. def __str__(self):
  1808. if not self:
  1809. return 'EPS'
  1810. return self
  1811. # sys.stdout needs to be the original to trigger the recursion bug
  1812. test_stdout = sys.stdout
  1813. sys.stdout = test_support.get_original_stdout()
  1814. try:
  1815. # nothing should actually be printed, this should raise an exception
  1816. print Letter('w')
  1817. except RuntimeError:
  1818. pass
  1819. else:
  1820. self.fail("expected a RuntimeError for print recursion")
  1821. finally:
  1822. sys.stdout = test_stdout
  1823. def test_recursions_2(self):
  1824. # Bug #1202533.
  1825. class A(object):
  1826. pass
  1827. A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
  1828. try:
  1829. A()*2
  1830. except RuntimeError:
  1831. pass
  1832. else:
  1833. self.fail("expected a RuntimeError")
  1834. def test_weakrefs(self):
  1835. # Testing weak references...
  1836. import weakref
  1837. class C(object):
  1838. pass
  1839. c = C()
  1840. r = weakref.ref(c)
  1841. self.assertEqual(r(), c)
  1842. del c
  1843. test_support.gc_collect()
  1844. self.assertEqual(r(), None)
  1845. del r
  1846. class NoWeak(object):
  1847. __slots__ = ['foo']
  1848. no = NoWeak()
  1849. try:
  1850. weakref.ref(no)
  1851. except TypeError, msg:
  1852. self.assertIn("weak reference", str(msg))
  1853. else:
  1854. self.fail("weakref.ref(no) should be illegal")
  1855. class Weak(object):
  1856. __slots__ = ['foo', '__weakref__']
  1857. yes = Weak()
  1858. r = weakref.ref(yes)
  1859. self.assertEqual(r(), yes)
  1860. del yes
  1861. test_support.gc_collect()
  1862. self.assertEqual(r(), None)
  1863. del r
  1864. def test_properties(self):
  1865. # Testing property...
  1866. class C(object):
  1867. def getx(self):
  1868. return self.__x
  1869. def setx(self, value):
  1870. self.__x = value
  1871. def delx(self):
  1872. del self.__x
  1873. x = property(getx, setx, delx, doc="I'm the x property.")
  1874. a = C()
  1875. self.assertNotHasAttr(a, "x")
  1876. a.x = 42
  1877. self.assertEqual(a._C__x, 42)
  1878. self.assertEqual(a.x, 42)
  1879. del a.x
  1880. self.assertNotHasAttr(a, "x")
  1881. self.assertNotHasAttr(a, "_C__x")
  1882. C.x.__set__(a, 100)
  1883. self.assertEqual(C.x.__get__(a), 100)
  1884. C.x.__delete__(a)
  1885. self.assertNotHasAttr(a, "x")
  1886. raw = C.__dict__['x']
  1887. self.assertIsInstance(raw, property)
  1888. attrs = dir(raw)
  1889. self.assertIn("__doc__", attrs)
  1890. self.assertIn("fget", attrs)
  1891. self.assertIn("fset", attrs)
  1892. self.assertIn("fdel", attrs)
  1893. self.assertEqual(raw.__doc__, "I'm the x property.")
  1894. self.assertIs(raw.fget, C.__dict__['getx'])
  1895. self.assertIs(raw.fset, C.__dict__['setx'])
  1896. self.assertIs(raw.fdel, C.__dict__['delx'])
  1897. for attr in "__doc__", "fget", "fset", "fdel":
  1898. try:
  1899. setattr(raw, attr, 42)
  1900. except TypeError, msg:
  1901. if str(msg).find('readonly') < 0:
  1902. self.fail("when setting readonly attr %r on a property, "
  1903. "got unexpected TypeError msg %r" % (attr, str(msg)))
  1904. else:
  1905. self.fail("expected TypeError from trying to set readonly %r "
  1906. "attr on a property" % attr)
  1907. class D(object):
  1908. __getitem__ = property(lambda s: 1.0/0.0)
  1909. d = D()
  1910. try:
  1911. for i in d:
  1912. str(i)
  1913. except ZeroDivisionError:
  1914. pass
  1915. else:
  1916. self.fail("expected ZeroDivisionError from bad property")
  1917. @unittest.skipIf(sys.flags.optimize >= 2,
  1918. "Docstrings are omitted with -O2 and above")
  1919. def test_properties_doc_attrib(self):
  1920. class E(object):
  1921. def getter(self):
  1922. "getter method"
  1923. return 0
  1924. def setter(self_, value):
  1925. "setter method"
  1926. pass
  1927. prop = property(getter)
  1928. self.assertEqual(prop.__doc__, "getter method")
  1929. prop2 = property(fset=setter)
  1930. self.assertEqual(prop2.__doc__, None)
  1931. @test_support.cpython_only
  1932. def test_testcapi_no_segfault(self):
  1933. # this segfaulted in 2.5b2
  1934. try:
  1935. import _testcapi
  1936. except ImportError:
  1937. pass
  1938. else:
  1939. class X(object):
  1940. p = property(_testcapi.test_with_docstring)
  1941. def test_properties_plus(self):
  1942. class C(object):
  1943. foo = property(doc="hello")
  1944. @foo.getter
  1945. def foo(self):
  1946. return self._foo
  1947. @foo.setter
  1948. def foo(self, value):
  1949. self._foo = abs(value)
  1950. @foo.deleter
  1951. def foo(self):
  1952. del self._foo
  1953. c = C()
  1954. self.assertEqual(C.foo.__doc__, "hello")
  1955. self.assertNotHasAttr(c, "foo")
  1956. c.foo = -42
  1957. self.assertHasAttr(c, '_foo')
  1958. self.assertEqual(c._foo, 42)
  1959. self.assertEqual(c.foo, 42)
  1960. del c.foo
  1961. self.assertNotHasAttr(c, '_foo')
  1962. self.assertNotHasAttr(c, "foo")
  1963. class D(C):
  1964. @C.foo.deleter
  1965. def foo(self):
  1966. try:
  1967. del self._foo
  1968. except AttributeError:
  1969. pass
  1970. d = D()
  1971. d.foo = 24
  1972. self.assertEqual(d.foo, 24)
  1973. del d.foo
  1974. del d.foo
  1975. class E(object):
  1976. @property
  1977. def foo(self):
  1978. return self._foo
  1979. @foo.setter
  1980. def foo(self, value):
  1981. raise RuntimeError
  1982. @foo.setter
  1983. def foo(self, value):
  1984. self._foo = abs(value)
  1985. @foo.deleter
  1986. def foo(self, value=None):
  1987. del self._foo
  1988. e = E()
  1989. e.foo = -42
  1990. self.assertEqual(e.foo, 42)
  1991. del e.foo
  1992. class F(E):
  1993. @E.foo.deleter
  1994. def foo(self):
  1995. del self._foo
  1996. @foo.setter
  1997. def foo(self, value):
  1998. self._foo = max(0, value)
  1999. f = F()
  2000. f.foo = -10
  2001. self.assertEqual(f.foo, 0)
  2002. del f.foo
  2003. def test_dict_constructors(self):
  2004. # Testing dict constructor ...
  2005. d = dict()
  2006. self.assertEqual(d, {})
  2007. d = dict({})
  2008. self.assertEqual(d, {})
  2009. d = dict({1: 2, 'a': 'b'})
  2010. self.assertEqual(d, {1: 2, 'a': 'b'})
  2011. self.assertEqual(d, dict(d.items()))
  2012. self.assertEqual(d, dict(d.iteritems()))
  2013. d = dict({'one':1, 'two':2})
  2014. self.assertEqual(d, dict(one=1, two=2))
  2015. self.assertEqual(d, dict(**d))
  2016. self.assertEqual(d, dict({"one": 1}, two=2))
  2017. self.assertEqual(d, dict([("two", 2)], one=1))
  2018. self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
  2019. self.assertEqual(d, dict(**d))
  2020. for badarg in 0, 0L, 0j, "0", [0], (0,):
  2021. try:
  2022. dict(badarg)
  2023. except TypeError:
  2024. pass
  2025. except ValueError:
  2026. if badarg == "0":
  2027. # It's a sequence, and its elements are also sequences (gotta
  2028. # love strings <wink>), but they aren't of length 2, so this
  2029. # one seemed better as a ValueError than a TypeError.
  2030. pass
  2031. else:
  2032. self.fail("no TypeError from dict(%r)" % badarg)
  2033. else:
  2034. self.fail("no TypeError from dict(%r)" % badarg)
  2035. try:
  2036. dict({}, {})
  2037. except TypeError:
  2038. pass
  2039. else:
  2040. self.fail("no TypeError from dict({}, {})")
  2041. class Mapping:
  2042. # Lacks a .keys() method; will be added later.
  2043. dict = {1:2, 3:4, 'a':1j}
  2044. try:
  2045. dict(Mapping())
  2046. except TypeError:
  2047. pass
  2048. else:
  2049. self.fail("no TypeError from dict(incomplete mapping)")
  2050. Mapping.keys = lambda self: self.dict.keys()
  2051. Mapping.__getitem__ = lambda self, i: self.dict[i]
  2052. d = dict(Mapping())
  2053. self.assertEqual(d, Mapping.dict)
  2054. # Init from sequence of iterable objects, each producing a 2-sequence.
  2055. class AddressBookEntry:
  2056. def __init__(self, first, last):
  2057. self.first = first
  2058. self.last = last
  2059. def __iter__(self):
  2060. return iter([self.first, self.last])
  2061. d = dict([AddressBookEntry('Tim', 'Warsaw'),
  2062. AddressBookEntry('Barry', 'Peters'),
  2063. AddressBookEntry('Tim', 'Peters'),
  2064. AddressBookEntry('Barry', 'Warsaw')])
  2065. self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
  2066. d = dict(zip(range(4), range(1, 5)))
  2067. self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
  2068. # Bad sequence lengths.
  2069. for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
  2070. try:
  2071. dict(bad)
  2072. except ValueError:
  2073. pass
  2074. else:
  2075. self.fail("no ValueError from dict(%r)" % bad)
  2076. def test_dir(self):
  2077. # Testing dir() ...
  2078. junk = 12
  2079. self.assertEqual(dir(), ['junk', 'self'])
  2080. del junk
  2081. # Just make sure these don't blow up!
  2082. for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
  2083. dir(arg)
  2084. # Try classic classes.
  2085. class C:
  2086. Cdata = 1
  2087. def Cmethod(self): pass
  2088. cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
  2089. self.assertEqual(dir(C), cstuff)
  2090. self.assertIn('im_self', dir(C.Cmethod))
  2091. c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
  2092. self.assertEqual(dir(c), cstuff)
  2093. c.cdata = 2
  2094. c.cmethod = lambda self: 0
  2095. self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
  2096. self.assertIn('im_self', dir(c.Cmethod))
  2097. class A(C):
  2098. Adata = 1
  2099. def Amethod(self): pass
  2100. astuff = ['Adata', 'Amethod'] + cstuff
  2101. self.assertEqual(dir(A), astuff)
  2102. self.assertIn('im_self', dir(A.Amethod))
  2103. a = A()
  2104. self.assertEqual(dir(a), astuff)
  2105. self.assertIn('im_self', dir(a.Amethod))
  2106. a.adata = 42
  2107. a.amethod = lambda self: 3
  2108. self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
  2109. # The same, but with new-style classes. Since these have object as a
  2110. # base class, a lot more gets sucked in.
  2111. def interesting(strings):
  2112. return [s for s in strings if not s.startswith('_')]
  2113. class C(object):
  2114. Cdata = 1
  2115. def Cmethod(self): pass
  2116. cstuff = ['Cdata', 'Cmethod']
  2117. self.assertEqual(interesting(dir(C)), cstuff)
  2118. c = C()
  2119. self.assertEqual(interesting(dir(c)), cstuff)
  2120. self.assertIn('im_self', dir(C.Cmethod))
  2121. c.cdata = 2
  2122. c.cmethod = lambda self: 0
  2123. self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
  2124. self.assertIn('im_self', dir(c.Cmethod))
  2125. class A(C):
  2126. Adata = 1
  2127. def Amethod(self): pass
  2128. astuff = ['Adata', 'Amethod'] + cstuff
  2129. self.assertEqual(interesting(dir(A)), astuff)
  2130. self.assertIn('im_self', dir(A.Amethod))
  2131. a = A()
  2132. self.assertEqual(interesting(dir(a)), astuff)
  2133. a.adata = 42
  2134. a.amethod = lambda self: 3
  2135. self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
  2136. self.assertIn('im_self', dir(a.Amethod))
  2137. # Try a module subclass.
  2138. class M(type(sys)):
  2139. pass
  2140. minstance = M("m")
  2141. minstance.b = 2
  2142. minstance.a = 1
  2143. names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
  2144. self.assertEqual(names, ['a', 'b'])
  2145. class M2(M):
  2146. def getdict(self):
  2147. return "Not a dict!"
  2148. __dict__ = property(getdict)
  2149. m2instance = M2("m2")
  2150. m2instance.b = 2
  2151. m2instance.a = 1
  2152. self.assertEqual(m2instance.__dict__, "Not a dict!")
  2153. try:
  2154. dir(m2instance)
  2155. except TypeError:
  2156. pass
  2157. # Two essentially featureless objects, just inheriting stuff from
  2158. # object.
  2159. self.assertEqual(dir(NotImplemented), dir(Ellipsis))
  2160. if test_support.check_impl_detail():
  2161. # None differs in PyPy: it has a __nonzero__
  2162. self.assertEqual(dir(None), dir(Ellipsis))
  2163. # Nasty test case for proxied objects
  2164. class Wrapper(object):
  2165. def __init__(self, obj):
  2166. self.__obj = obj
  2167. def __repr__(self):
  2168. return "Wrapper(%s)" % repr(self.__obj)
  2169. def __getitem__(self, key):
  2170. return Wrapper(self.__obj[key])
  2171. def __len__(self):
  2172. return len(self.__obj)
  2173. def __getattr__(self, name):
  2174. return Wrapper(getattr(self.__obj, name))
  2175. class C(object):
  2176. def __getclass(self):
  2177. return Wrapper(type(self))
  2178. __class__ = property(__getclass)
  2179. dir(C()) # This used to segfault
  2180. def test_supers(self):
  2181. # Testing super...
  2182. class A(object):
  2183. def meth(self, a):
  2184. return "A(%r)" % a
  2185. self.assertEqual(A().meth(1), "A(1)")
  2186. class B(A):
  2187. def __init__(self):
  2188. self.__super = super(B, self)
  2189. def meth(self, a):
  2190. return "B(%r)" % a + self.__super.meth(a)
  2191. self.assertEqual(B().meth(2), "B(2)A(2)")
  2192. class C(A):
  2193. def meth(self, a):
  2194. return "C(%r)" % a + self.__super.meth(a)
  2195. C._C__super = super(C)
  2196. self.assertEqual(C().meth(3), "C(3)A(3)")
  2197. class D(C, B):
  2198. def meth(self, a):
  2199. return "D(%r)" % a + super(D, self).meth(a)
  2200. self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
  2201. # Test for subclassing super
  2202. class mysuper(super):
  2203. def __init__(self, *args):
  2204. return super(mysuper, self).__init__(*args)
  2205. class E(D):
  2206. def meth(self, a):
  2207. return "E(%r)" % a + mysuper(E, self).meth(a)
  2208. self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
  2209. class F(E):
  2210. def meth(self, a):
  2211. s = self.__super # == mysuper(F, self)
  2212. return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
  2213. F._F__super = mysuper(F)
  2214. self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
  2215. # Make sure certain errors are raised
  2216. try:
  2217. super(D, 42)
  2218. except TypeError:
  2219. pass
  2220. else:
  2221. self.fail("shouldn't allow super(D, 42)")
  2222. try:
  2223. super(D, C())
  2224. except TypeError:
  2225. pass
  2226. else:
  2227. self.fail("shouldn't allow super(D, C())")
  2228. try:
  2229. super(D).__get__(12)
  2230. except TypeError:
  2231. pass
  2232. else:
  2233. self.fail("shouldn't allow super(D).__get__(12)")
  2234. try:
  2235. super(D).__get__(C())
  2236. except TypeError:
  2237. pass
  2238. else:
  2239. self.fail("shouldn't allow super(D).__get__(C())")
  2240. # Make sure data descriptors can be overridden and accessed via super
  2241. # (new feature in Python 2.3)
  2242. class DDbase(object):
  2243. def getx(self): return 42
  2244. x = property(getx)
  2245. class DDsub(DDbase):
  2246. def getx(self): return "hello"
  2247. x = property(getx)
  2248. dd = DDsub()
  2249. self.assertEqual(dd.x, "hello")
  2250. self.assertEqual(super(DDsub, dd).x, 42)
  2251. # Ensure that super() lookup of descriptor from classmethod
  2252. # works (SF ID# 743627)
  2253. class Base(object):
  2254. aProp = property(lambda self: "foo")
  2255. class Sub(Base):
  2256. @classmethod
  2257. def test(klass):
  2258. return super(Sub,klass).aProp
  2259. self.assertEqual(Sub.test(), Base.aProp)
  2260. # Verify that super() doesn't allow keyword args
  2261. try:
  2262. super(Base, kw=1)
  2263. except TypeError:
  2264. pass
  2265. else:
  2266. self.assertEqual("super shouldn't accept keyword args")
  2267. def test_basic_inheritance(self):
  2268. # Testing inheritance from basic types...
  2269. class hexint(int):
  2270. def __repr__(self):
  2271. return hex(self)
  2272. def __add__(self, other):
  2273. return hexint(int.__add__(self, other))
  2274. # (Note that overriding __radd__ doesn't work,
  2275. # because the int type gets first dibs.)
  2276. self.assertEqual(repr(hexint(7) + 9), "0x10")
  2277. self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
  2278. a = hexint(12345)
  2279. self.assertEqual(a, 12345)
  2280. self.assertEqual(int(a), 12345)
  2281. self.assertIs(int(a).__class__, int)
  2282. self.assertEqual(hash(a), hash(12345))
  2283. self.assertIs((+a).__class__, int)
  2284. self.assertIs((a >> 0).__class__, int)
  2285. self.assertIs((a << 0).__class__, int)
  2286. self.assertIs((hexint(0) << 12).__class__, int)
  2287. self.assertIs((hexint(0) >> 12).__class__, int)
  2288. class octlong(long):
  2289. __slots__ = []
  2290. def __str__(self):
  2291. s = oct(self)
  2292. if s[-1] == 'L':
  2293. s = s[:-1]
  2294. return s
  2295. def __add__(self, other):
  2296. return self.__class__(super(octlong, self).__add__(other))
  2297. __radd__ = __add__
  2298. self.assertEqual(str(octlong(3) + 5), "010")
  2299. # (Note that overriding __radd__ here only seems to work
  2300. # because the example uses a short int left argument.)
  2301. self.assertEqual(str(5 + octlong(3000)), "05675")
  2302. a = octlong(12345)
  2303. self.assertEqual(a, 12345L)
  2304. self.assertEqual(long(a), 12345L)
  2305. self.assertEqual(hash(a), hash(12345L))
  2306. self.assertIs(long(a).__class__, long)
  2307. self.assertIs((+a).__class__, long)
  2308. self.assertIs((-a).__class__, long)
  2309. self.assertIs((-octlong(0)).__class__, long)
  2310. self.assertIs((a >> 0).__class__, long)
  2311. self.assertIs((a << 0).__class__, long)
  2312. self.assertIs((a - 0).__class__, long)
  2313. self.assertIs((a * 1).__class__, long)
  2314. self.assertIs((a ** 1).__class__, long)
  2315. self.assertIs((a // 1).__class__, long)
  2316. self.assertIs((1 * a).__class__, long)
  2317. self.assertIs((a | 0).__class__, long)
  2318. self.assertIs((a ^ 0).__class__, long)
  2319. self.assertIs((a & -1L).__class__, long)
  2320. self.assertIs((octlong(0) << 12).__class__, long)
  2321. self.assertIs((octlong(0) >> 12).__class__, long)
  2322. self.assertIs(abs(octlong(0)).__class__, long)
  2323. # Because octlong overrides __add__, we can't check the absence of +0
  2324. # optimizations using octlong.
  2325. class longclone(long):
  2326. pass
  2327. a = longclone(1)
  2328. self.assertIs((a + 0).__class__, long)
  2329. self.assertIs((0 + a).__class__, long)
  2330. # Check that negative clones don't segfault
  2331. a = longclone(-1)
  2332. self.assertEqual(a.__dict__, {})
  2333. self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
  2334. class precfloat(float):
  2335. __slots__ = ['prec']
  2336. def __init__(self, value=0.0, prec=12):
  2337. self.prec = int(prec)
  2338. def __repr__(self):
  2339. return "%.*g" % (self.prec, self)
  2340. self.assertEqual(repr(precfloat(1.1)), "1.1")
  2341. a = precfloat(12345)
  2342. self.assertEqual(a, 12345.0)
  2343. self.assertEqual(float(a), 12345.0)
  2344. self.assertIs(float(a).__class__, float)
  2345. self.assertEqual(hash(a), hash(12345.0))
  2346. self.assertIs((+a).__class__, float)
  2347. class madcomplex(complex):
  2348. def __repr__(self):
  2349. return "%.17gj%+.17g" % (self.imag, self.real)
  2350. a = madcomplex(-3, 4)
  2351. self.assertEqual(repr(a), "4j-3")
  2352. base = complex(-3, 4)
  2353. self.assertEqual(base.__class__, complex)
  2354. self.assertEqual(a, base)
  2355. self.assertEqual(complex(a), base)
  2356. self.assertEqual(complex(a).__class__, complex)
  2357. a = madcomplex(a) # just trying another form of the constructor
  2358. self.assertEqual(repr(a), "4j-3")
  2359. self.assertEqual(a, base)
  2360. self.assertEqual(complex(a), base)
  2361. self.assertEqual(complex(a).__class__, complex)
  2362. self.assertEqual(hash(a), hash(base))
  2363. self.assertEqual((+a).__class__, complex)
  2364. self.assertEqual((a + 0).__class__, complex)
  2365. self.assertEqual(a + 0, base)
  2366. self.assertEqual((a - 0).__class__, complex)
  2367. self.assertEqual(a - 0, base)
  2368. self.assertEqual((a * 1).__class__, complex)
  2369. self.assertEqual(a * 1, base)
  2370. self.assertEqual((a / 1).__class__, complex)
  2371. self.assertEqual(a / 1, base)
  2372. class madtuple(tuple):
  2373. _rev = None
  2374. def rev(self):
  2375. if self._rev is not None:
  2376. return self._rev
  2377. L = list(self)
  2378. L.reverse()
  2379. self._rev = self.__class__(L)
  2380. return self._rev
  2381. a = madtuple((1,2,3,4,5,6,7,8,9,0))
  2382. self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
  2383. self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
  2384. self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
  2385. for i in range(512):
  2386. t = madtuple(range(i))
  2387. u = t.rev()
  2388. v = u.rev()
  2389. self.assertEqual(v, t)
  2390. a = madtuple((1,2,3,4,5))
  2391. self.assertEqual(tuple(a), (1,2,3,4,5))
  2392. self.assertIs(tuple(a).__class__, tuple)
  2393. self.assertEqual(hash(a), hash((1,2,3,4,5)))
  2394. self.assertIs(a[:].__class__, tuple)
  2395. self.assertIs((a * 1).__class__, tuple)
  2396. self.assertIs((a * 0).__class__, tuple)
  2397. self.assertIs((a + ()).__class__, tuple)
  2398. a = madtuple(())
  2399. self.assertEqual(tuple(a), ())
  2400. self.assertIs(tuple(a).__class__, tuple)
  2401. self.assertIs((a + a).__class__, tuple)
  2402. self.assertIs((a * 0).__class__, tuple)
  2403. self.assertIs((a * 1).__class__, tuple)
  2404. self.assertIs((a * 2).__class__, tuple)
  2405. self.assertIs(a[:].__class__, tuple)
  2406. class madstring(str):
  2407. _rev = None
  2408. def rev(self):
  2409. if self._rev is not None:
  2410. return self._rev
  2411. L = list(self)
  2412. L.reverse()
  2413. self._rev = self.__class__("".join(L))
  2414. return self._rev
  2415. s = madstring("abcdefghijklmnopqrstuvwxyz")
  2416. self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
  2417. self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
  2418. self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
  2419. for i in range(256):
  2420. s = madstring("".join(map(chr, range(i))))
  2421. t = s.rev()
  2422. u = t.rev()
  2423. self.assertEqual(u, s)
  2424. s = madstring("12345")
  2425. self.assertEqual(str(s), "12345")
  2426. self.assertIs(str(s).__class__, str)
  2427. base = "\x00" * 5
  2428. s = madstring(base)
  2429. self.assertEqual(s, base)
  2430. self.assertEqual(str(s), base)
  2431. self.assertIs(str(s).__class__, str)
  2432. self.assertEqual(hash(s), hash(base))
  2433. self.assertEqual({s: 1}[base], 1)
  2434. self.assertEqual({base: 1}[s], 1)
  2435. self.assertIs((s + "").__class__, str)
  2436. self.assertEqual(s + "", base)
  2437. self.assertIs(("" + s).__class__, str)
  2438. self.assertEqual("" + s, base)
  2439. self.assertIs((s * 0).__class__, str)
  2440. self.assertEqual(s * 0, "")
  2441. self.assertIs((s * 1).__class__, str)
  2442. self.assertEqual(s * 1, base)
  2443. self.assertIs((s * 2).__class__, str)
  2444. self.assertEqual(s * 2, base + base)
  2445. self.assertIs(s[:].__class__, str)
  2446. self.assertEqual(s[:], base)
  2447. self.assertIs(s[0:0].__class__, str)
  2448. self.assertEqual(s[0:0], "")
  2449. self.assertIs(s.strip().__class__, str)
  2450. self.assertEqual(s.strip(), base)
  2451. self.assertIs(s.lstrip().__class__, str)
  2452. self.assertEqual(s.lstrip(), base)
  2453. self.assertIs(s.rstrip().__class__, str)
  2454. self.assertEqual(s.rstrip(), base)
  2455. identitytab = ''.join([chr(i) for i in range(256)])
  2456. self.assertIs(s.translate(identitytab).__class__, str)
  2457. self.assertEqual(s.translate(identitytab), base)
  2458. self.assertIs(s.translate(identitytab, "x").__class__, str)
  2459. self.assertEqual(s.translate(identitytab, "x"), base)
  2460. self.assertEqual(s.translate(identitytab, "\x00"), "")
  2461. self.assertIs(s.replace("x", "x").__class__, str)
  2462. self.assertEqual(s.replace("x", "x"), base)
  2463. self.assertIs(s.ljust(len(s)).__class__, str)
  2464. self.assertEqual(s.ljust(len(s)), base)
  2465. self.assertIs(s.rjust(len(s)).__class__, str)
  2466. self.assertEqual(s.rjust(len(s)), base)
  2467. self.assertIs(s.center(len(s)).__class__, str)
  2468. self.assertEqual(s.center(len(s)), base)
  2469. self.assertIs(s.lower().__class__, str)
  2470. self.assertEqual(s.lower(), base)
  2471. class madunicode(unicode):
  2472. _rev = None
  2473. def rev(self):
  2474. if self._rev is not None:
  2475. return self._rev
  2476. L = list(self)
  2477. L.reverse()
  2478. self._rev = self.__class__(u"".join(L))
  2479. return self._rev
  2480. u = madunicode("ABCDEF")
  2481. self.assertEqual(u, u"ABCDEF")
  2482. self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
  2483. self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
  2484. base = u"12345"
  2485. u = madunicode(base)
  2486. self.assertEqual(unicode(u), base)
  2487. self.assertIs(unicode(u).__class__, unicode)
  2488. self.assertEqual(hash(u), hash(base))
  2489. self.assertEqual({u: 1}[base], 1)
  2490. self.assertEqual({base: 1}[u], 1)
  2491. self.assertIs(u.strip().__class__, unicode)
  2492. self.assertEqual(u.strip(), base)
  2493. self.assertIs(u.lstrip().__class__, unicode)
  2494. self.assertEqual(u.lstrip(), base)
  2495. self.assertIs(u.rstrip().__class__, unicode)
  2496. self.assertEqual(u.rstrip(), base)
  2497. self.assertIs(u.replace(u"x", u"x").__class__, unicode)
  2498. self.assertEqual(u.replace(u"x", u"x"), base)
  2499. self.assertIs(u.replace(u"xy", u"xy").__class__, unicode)
  2500. self.assertEqual(u.replace(u"xy", u"xy"), base)
  2501. self.assertIs(u.center(len(u)).__class__, unicode)
  2502. self.assertEqual(u.center(len(u)), base)
  2503. self.assertIs(u.ljust(len(u)).__class__, unicode)
  2504. self.assertEqual(u.ljust(len(u)), base)
  2505. self.assertIs(u.rjust(len(u)).__class__, unicode)
  2506. self.assertEqual(u.rjust(len(u)), base)
  2507. self.assertIs(u.lower().__class__, unicode)
  2508. self.assertEqual(u.lower(), base)
  2509. self.assertIs(u.upper().__class__, unicode)
  2510. self.assertEqual(u.upper(), base)
  2511. self.assertIs(u.capitalize().__class__, unicode)
  2512. self.assertEqual(u.capitalize(), base)
  2513. self.assertIs(u.title().__class__, unicode)
  2514. self.assertEqual(u.title(), base)
  2515. self.assertIs((u + u"").__class__, unicode)
  2516. self.assertEqual(u + u"", base)
  2517. self.assertIs((u"" + u).__class__, unicode)
  2518. self.assertEqual(u"" + u, base)
  2519. self.assertIs((u * 0).__class__, unicode)
  2520. self.assertEqual(u * 0, u"")
  2521. self.assertIs((u * 1).__class__, unicode)
  2522. self.assertEqual(u * 1, base)
  2523. self.assertIs((u * 2).__class__, unicode)
  2524. self.assertEqual(u * 2, base + base)
  2525. self.assertIs(u[:].__class__, unicode)
  2526. self.assertEqual(u[:], base)
  2527. self.assertIs(u[0:0].__class__, unicode)
  2528. self.assertEqual(u[0:0], u"")
  2529. class sublist(list):
  2530. pass
  2531. a = sublist(range(5))
  2532. self.assertEqual(a, range(5))
  2533. a.append("hello")
  2534. self.assertEqual(a, range(5) + ["hello"])
  2535. a[5] = 5
  2536. self.assertEqual(a, range(6))
  2537. a.extend(range(6, 20))
  2538. self.assertEqual(a, range(20))
  2539. a[-5:] = []
  2540. self.assertEqual(a, range(15))
  2541. del a[10:15]
  2542. self.assertEqual(len(a), 10)
  2543. self.assertEqual(a, range(10))
  2544. self.assertEqual(list(a), range(10))
  2545. self.assertEqual(a[0], 0)
  2546. self.assertEqual(a[9], 9)
  2547. self.assertEqual(a[-10], 0)
  2548. self.assertEqual(a[-1], 9)
  2549. self.assertEqual(a[:5], range(5))
  2550. class CountedInput(file):
  2551. """Counts lines read by self.readline().
  2552. self.lineno is the 0-based ordinal of the last line read, up to
  2553. a maximum of one greater than the number of lines in the file.
  2554. self.ateof is true if and only if the final "" line has been read,
  2555. at which point self.lineno stops incrementing, and further calls
  2556. to readline() continue to return "".
  2557. """
  2558. lineno = 0
  2559. ateof = 0
  2560. def readline(self):
  2561. if self.ateof:
  2562. return ""
  2563. s = file.readline(self)
  2564. # Next line works too.
  2565. # s = super(CountedInput, self).readline()
  2566. self.lineno += 1
  2567. if s == "":
  2568. self.ateof = 1
  2569. return s
  2570. f = file(name=test_support.TESTFN, mode='w')
  2571. lines = ['a\n', 'b\n', 'c\n']
  2572. try:
  2573. f.writelines(lines)
  2574. f.close()
  2575. f = CountedInput(test_support.TESTFN)
  2576. for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
  2577. got = f.readline()
  2578. self.assertEqual(expected, got)
  2579. self.assertEqual(f.lineno, i)
  2580. self.assertEqual(f.ateof, (i > len(lines)))
  2581. f.close()
  2582. finally:
  2583. try:
  2584. f.close()
  2585. except:
  2586. pass
  2587. test_support.unlink(test_support.TESTFN)
  2588. def test_keywords(self):
  2589. # Testing keyword args to basic type constructors ...
  2590. self.assertEqual(int(x=1), 1)
  2591. self.assertEqual(float(x=2), 2.0)
  2592. self.assertEqual(long(x=3), 3L)
  2593. self.assertEqual(complex(imag=42, real=666), complex(666, 42))
  2594. self.assertEqual(str(object=500), '500')
  2595. self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
  2596. self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
  2597. self.assertEqual(list(sequence=(0, 1, 2)), range(3))
  2598. # note: as of Python 2.3, dict() no longer has an "items" keyword arg
  2599. for constructor in (int, float, long, complex, str, unicode,
  2600. tuple, list, file):
  2601. try:
  2602. constructor(bogus_keyword_arg=1)
  2603. except TypeError:
  2604. pass
  2605. else:
  2606. self.fail("expected TypeError from bogus keyword argument to %r"
  2607. % constructor)
  2608. def test_str_subclass_as_dict_key(self):
  2609. # Testing a str subclass used as dict key ..
  2610. class cistr(str):
  2611. """Sublcass of str that computes __eq__ case-insensitively.
  2612. Also computes a hash code of the string in canonical form.
  2613. """
  2614. def __init__(self, value):
  2615. self.canonical = value.lower()
  2616. self.hashcode = hash(self.canonical)
  2617. def __eq__(self, other):
  2618. if not isinstance(other, cistr):
  2619. other = cistr(other)
  2620. return self.canonical == other.canonical
  2621. def __hash__(self):
  2622. return self.hashcode
  2623. self.assertEqual(cistr('ABC'), 'abc')
  2624. self.assertEqual('aBc', cistr('ABC'))
  2625. self.assertEqual(str(cistr('ABC')), 'ABC')
  2626. d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
  2627. self.assertEqual(d[cistr('one')], 1)
  2628. self.assertEqual(d[cistr('tWo')], 2)
  2629. self.assertEqual(d[cistr('THrEE')], 3)
  2630. self.assertIn(cistr('ONe'), d)
  2631. self.assertEqual(d.get(cistr('thrEE')), 3)
  2632. def test_classic_comparisons(self):
  2633. # Testing classic comparisons...
  2634. class classic:
  2635. pass
  2636. for base in (classic, int, object):
  2637. class C(base):
  2638. def __init__(self, value):
  2639. self.value = int(value)
  2640. def __cmp__(self, other):
  2641. if isinstance(other, C):
  2642. return cmp(self.value, other.value)
  2643. if isinstance(other, int) or isinstance(other, long):
  2644. return cmp(self.value, other)
  2645. return NotImplemented
  2646. __hash__ = None # Silence Py3k warning
  2647. c1 = C(1)
  2648. c2 = C(2)
  2649. c3 = C(3)
  2650. self.assertEqual(c1, 1)
  2651. c = {1: c1, 2: c2, 3: c3}
  2652. for x in 1, 2, 3:
  2653. for y in 1, 2, 3:
  2654. self.assertEqual(cmp(c[x], c[y]), cmp(x, y),
  2655. "x=%d, y=%d" % (x, y))
  2656. for op in "<", "<=", "==", "!=", ">", ">=":
  2657. self.assertEqual(eval("c[x] %s c[y]" % op),
  2658. eval("x %s y" % op),
  2659. "x=%d, y=%d" % (x, y))
  2660. self.assertEqual(cmp(c[x], y), cmp(x, y),
  2661. "x=%d, y=%d" % (x, y))
  2662. self.assertEqual(cmp(x, c[y]), cmp(x, y),
  2663. "x=%d, y=%d" % (x, y))
  2664. def test_rich_comparisons(self):
  2665. # Testing rich comparisons...
  2666. class Z(complex):
  2667. pass
  2668. z = Z(1)
  2669. self.assertEqual(z, 1+0j)
  2670. self.assertEqual(1+0j, z)
  2671. class ZZ(complex):
  2672. def __eq__(self, other):
  2673. try:
  2674. return abs(self - other) <= 1e-6
  2675. except:
  2676. return NotImplemented
  2677. __hash__ = None # Silence Py3k warning
  2678. zz = ZZ(1.0000003)
  2679. self.assertEqual(zz, 1+0j)
  2680. self.assertEqual(1+0j, zz)
  2681. class classic:
  2682. pass
  2683. for base in (classic, int, object, list):
  2684. class C(base):
  2685. def __init__(self, value):
  2686. self.value = int(value)
  2687. def __cmp__(self_, other):
  2688. self.fail("shouldn't call __cmp__")
  2689. __hash__ = None # Silence Py3k warning
  2690. def __eq__(self, other):
  2691. if isinstance(other, C):
  2692. return self.value == other.value
  2693. if isinstance(other, int) or isinstance(other, long):
  2694. return self.value == other
  2695. return NotImplemented
  2696. def __ne__(self, other):
  2697. if isinstance(other, C):
  2698. return self.value != other.value
  2699. if isinstance(other, int) or isinstance(other, long):
  2700. return self.value != other
  2701. return NotImplemented
  2702. def __lt__(self, other):
  2703. if isinstance(other, C):
  2704. return self.value < other.value
  2705. if isinstance(other, int) or isinstance(other, long):
  2706. return self.value < other
  2707. return NotImplemented
  2708. def __le__(self, other):
  2709. if isinstance(other, C):
  2710. return self.value <= other.value
  2711. if isinstance(other, int) or isinstance(other, long):
  2712. return self.value <= other
  2713. return NotImplemented
  2714. def __gt__(self, other):
  2715. if isinstance(other, C):
  2716. return self.value > other.value
  2717. if isinstance(other, int) or isinstance(other, long):
  2718. return self.value > other
  2719. return NotImplemented
  2720. def __ge__(self, other):
  2721. if isinstance(other, C):
  2722. return self.value >= other.value
  2723. if isinstance(other, int) or isinstance(other, long):
  2724. return self.value >= other
  2725. return NotImplemented
  2726. c1 = C(1)
  2727. c2 = C(2)
  2728. c3 = C(3)
  2729. self.assertEqual(c1, 1)
  2730. c = {1: c1, 2: c2, 3: c3}
  2731. for x in 1, 2, 3:
  2732. for y in 1, 2, 3:
  2733. for op in "<", "<=", "==", "!=", ">", ">=":
  2734. self.assertEqual(eval("c[x] %s c[y]" % op),
  2735. eval("x %s y" % op),
  2736. "x=%d, y=%d" % (x, y))
  2737. self.assertEqual(eval("c[x] %s y" % op),
  2738. eval("x %s y" % op),
  2739. "x=%d, y=%d" % (x, y))
  2740. self.assertEqual(eval("x %s c[y]" % op),
  2741. eval("x %s y" % op),
  2742. "x=%d, y=%d" % (x, y))
  2743. def test_coercions(self):
  2744. # Testing coercions...
  2745. class I(int): pass
  2746. coerce(I(0), 0)
  2747. coerce(0, I(0))
  2748. class L(long): pass
  2749. coerce(L(0), 0)
  2750. coerce(L(0), 0L)
  2751. coerce(0, L(0))
  2752. coerce(0L, L(0))
  2753. class F(float): pass
  2754. coerce(F(0), 0)
  2755. coerce(F(0), 0L)
  2756. coerce(F(0), 0.)
  2757. coerce(0, F(0))
  2758. coerce(0L, F(0))
  2759. coerce(0., F(0))
  2760. class C(complex): pass
  2761. coerce(C(0), 0)
  2762. coerce(C(0), 0L)
  2763. coerce(C(0), 0.)
  2764. coerce(C(0), 0j)
  2765. coerce(0, C(0))
  2766. coerce(0L, C(0))
  2767. coerce(0., C(0))
  2768. coerce(0j, C(0))
  2769. def test_descrdoc(self):
  2770. # Testing descriptor doc strings...
  2771. def check(descr, what):
  2772. self.assertEqual(descr.__doc__, what)
  2773. check(file.closed, "True if the file is closed") # getset descriptor
  2774. check(file.name, "file name") # member descriptor
  2775. def test_doc_descriptor(self):
  2776. # Testing __doc__ descriptor...
  2777. # SF bug 542984
  2778. class DocDescr(object):
  2779. def __get__(self, object, otype):
  2780. if object:
  2781. object = object.__class__.__name__ + ' instance'
  2782. if otype:
  2783. otype = otype.__name__
  2784. return 'object=%s; type=%s' % (object, otype)
  2785. class OldClass:
  2786. __doc__ = DocDescr()
  2787. class NewClass(object):
  2788. __doc__ = DocDescr()
  2789. self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
  2790. self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
  2791. self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
  2792. self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
  2793. def test_set_class(self):
  2794. # Testing __class__ assignment...
  2795. class C(object): pass
  2796. class D(object): pass
  2797. class E(object): pass
  2798. class F(D, E): pass
  2799. for cls in C, D, E, F:
  2800. for cls2 in C, D, E, F:
  2801. x = cls()
  2802. x.__class__ = cls2
  2803. self.assertIs(x.__class__, cls2)
  2804. x.__class__ = cls
  2805. self.assertIs(x.__class__, cls)
  2806. def cant(x, C):
  2807. try:
  2808. x.__class__ = C
  2809. except TypeError:
  2810. pass
  2811. else:
  2812. self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
  2813. try:
  2814. delattr(x, "__class__")
  2815. except (TypeError, AttributeError):
  2816. pass
  2817. else:
  2818. self.fail("shouldn't allow del %r.__class__" % x)
  2819. cant(C(), list)
  2820. cant(list(), C)
  2821. cant(C(), 1)
  2822. cant(C(), object)
  2823. cant(object(), list)
  2824. cant(list(), object)
  2825. class Int(int): __slots__ = []
  2826. cant(2, Int)
  2827. cant(Int(), int)
  2828. cant(True, int)
  2829. cant(2, bool)
  2830. o = object()
  2831. cant(o, type(1))
  2832. cant(o, type(None))
  2833. del o
  2834. class G(object):
  2835. __slots__ = ["a", "b"]
  2836. class H(object):
  2837. __slots__ = ["b", "a"]
  2838. try:
  2839. unicode
  2840. except NameError:
  2841. class I(object):
  2842. __slots__ = ["a", "b"]
  2843. else:
  2844. class I(object):
  2845. __slots__ = [unicode("a"), unicode("b")]
  2846. class J(object):
  2847. __slots__ = ["c", "b"]
  2848. class K(object):
  2849. __slots__ = ["a", "b", "d"]
  2850. class L(H):
  2851. __slots__ = ["e"]
  2852. class M(I):
  2853. __slots__ = ["e"]
  2854. class N(J):
  2855. __slots__ = ["__weakref__"]
  2856. class P(J):
  2857. __slots__ = ["__dict__"]
  2858. class Q(J):
  2859. pass
  2860. class R(J):
  2861. __slots__ = ["__dict__", "__weakref__"]
  2862. for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
  2863. x = cls()
  2864. x.a = 1
  2865. x.__class__ = cls2
  2866. self.assertIs(x.__class__, cls2,
  2867. "assigning %r as __class__ for %r silently failed" % (cls2, x))
  2868. self.assertEqual(x.a, 1)
  2869. x.__class__ = cls
  2870. self.assertIs(x.__class__, cls,
  2871. "assigning %r as __class__ for %r silently failed" % (cls, x))
  2872. self.assertEqual(x.a, 1)
  2873. for cls in G, J, K, L, M, N, P, R, list, Int:
  2874. for cls2 in G, J, K, L, M, N, P, R, list, Int:
  2875. if cls is cls2:
  2876. continue
  2877. cant(cls(), cls2)
  2878. # Issue5283: when __class__ changes in __del__, the wrong
  2879. # type gets DECREF'd.
  2880. class O(object):
  2881. pass
  2882. class A(object):
  2883. def __del__(self):
  2884. self.__class__ = O
  2885. l = [A() for x in range(100)]
  2886. del l
  2887. def test_set_dict(self):
  2888. # Testing __dict__ assignment...
  2889. class C(object): pass
  2890. a = C()
  2891. a.__dict__ = {'b': 1}
  2892. self.assertEqual(a.b, 1)
  2893. def cant(x, dict):
  2894. try:
  2895. x.__dict__ = dict
  2896. except (AttributeError, TypeError):
  2897. pass
  2898. else:
  2899. self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
  2900. cant(a, None)
  2901. cant(a, [])
  2902. cant(a, 1)
  2903. del a.__dict__ # Deleting __dict__ is allowed
  2904. class Base(object):
  2905. pass
  2906. def verify_dict_readonly(x):
  2907. """
  2908. x has to be an instance of a class inheriting from Base.
  2909. """
  2910. cant(x, {})
  2911. try:
  2912. del x.__dict__
  2913. except (AttributeError, TypeError):
  2914. pass
  2915. else:
  2916. self.fail("shouldn't allow del %r.__dict__" % x)
  2917. dict_descr = Base.__dict__["__dict__"]
  2918. try:
  2919. dict_descr.__set__(x, {})
  2920. except (AttributeError, TypeError):
  2921. pass
  2922. else:
  2923. self.fail("dict_descr allowed access to %r's dict" % x)
  2924. # Classes don't allow __dict__ assignment and have readonly dicts
  2925. class Meta1(type, Base):
  2926. pass
  2927. class Meta2(Base, type):
  2928. pass
  2929. class D(object):
  2930. __metaclass__ = Meta1
  2931. class E(object):
  2932. __metaclass__ = Meta2
  2933. for cls in C, D, E:
  2934. verify_dict_readonly(cls)
  2935. class_dict = cls.__dict__
  2936. try:
  2937. class_dict["spam"] = "eggs"
  2938. except TypeError:
  2939. pass
  2940. else:
  2941. self.fail("%r's __dict__ can be modified" % cls)
  2942. # Modules also disallow __dict__ assignment
  2943. class Module1(types.ModuleType, Base):
  2944. pass
  2945. class Module2(Base, types.ModuleType):
  2946. pass
  2947. for ModuleType in Module1, Module2:
  2948. mod = ModuleType("spam")
  2949. verify_dict_readonly(mod)
  2950. mod.__dict__["spam"] = "eggs"
  2951. # Exception's __dict__ can be replaced, but not deleted
  2952. # (at least not any more than regular exception's __dict__ can
  2953. # be deleted; on CPython it is not the case, whereas on PyPy they
  2954. # can, just like any other new-style instance's __dict__.)
  2955. def can_delete_dict(e):
  2956. try:
  2957. del e.__dict__
  2958. except (TypeError, AttributeError):
  2959. return False
  2960. else:
  2961. return True
  2962. class Exception1(Exception, Base):
  2963. pass
  2964. class Exception2(Base, Exception):
  2965. pass
  2966. for ExceptionType in Exception, Exception1, Exception2:
  2967. e = ExceptionType()
  2968. e.__dict__ = {"a": 1}
  2969. self.assertEqual(e.a, 1)
  2970. self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
  2971. def test_pickles(self):
  2972. # Testing pickling and copying new-style classes and objects...
  2973. import pickle, cPickle
  2974. def sorteditems(d):
  2975. L = d.items()
  2976. L.sort()
  2977. return L
  2978. global C
  2979. class C(object):
  2980. def __init__(self, a, b):
  2981. super(C, self).__init__()
  2982. self.a = a
  2983. self.b = b
  2984. def __repr__(self):
  2985. return "C(%r, %r)" % (self.a, self.b)
  2986. global C1
  2987. class C1(list):
  2988. def __new__(cls, a, b):
  2989. return super(C1, cls).__new__(cls)
  2990. def __getnewargs__(self):
  2991. return (self.a, self.b)
  2992. def __init__(self, a, b):
  2993. self.a = a
  2994. self.b = b
  2995. def __repr__(self):
  2996. return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
  2997. global C2
  2998. class C2(int):
  2999. def __new__(cls, a, b, val=0):
  3000. return super(C2, cls).__new__(cls, val)
  3001. def __getnewargs__(self):
  3002. return (self.a, self.b, int(self))
  3003. def __init__(self, a, b, val=0):
  3004. self.a = a
  3005. self.b = b
  3006. def __repr__(self):
  3007. return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
  3008. global C3
  3009. class C3(object):
  3010. def __init__(self, foo):
  3011. self.foo = foo
  3012. def __getstate__(self):
  3013. return self.foo
  3014. def __setstate__(self, foo):
  3015. self.foo = foo
  3016. global C4classic, C4
  3017. class C4classic: # classic
  3018. pass
  3019. class C4(C4classic, object): # mixed inheritance
  3020. pass
  3021. for p in pickle, cPickle:
  3022. for bin in range(p.HIGHEST_PROTOCOL + 1):
  3023. for cls in C, C1, C2:
  3024. s = p.dumps(cls, bin)
  3025. cls2 = p.loads(s)
  3026. self.assertIs(cls2, cls)
  3027. a = C1(1, 2); a.append(42); a.append(24)
  3028. b = C2("hello", "world", 42)
  3029. s = p.dumps((a, b), bin)
  3030. x, y = p.loads(s)
  3031. self.assertEqual(x.__class__, a.__class__)
  3032. self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
  3033. self.assertEqual(y.__class__, b.__class__)
  3034. self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
  3035. self.assertEqual(repr(x), repr(a))
  3036. self.assertEqual(repr(y), repr(b))
  3037. # Test for __getstate__ and __setstate__ on new style class
  3038. u = C3(42)
  3039. s = p.dumps(u, bin)
  3040. v = p.loads(s)
  3041. self.assertEqual(u.__class__, v.__class__)
  3042. self.assertEqual(u.foo, v.foo)
  3043. # Test for picklability of hybrid class
  3044. u = C4()
  3045. u.foo = 42
  3046. s = p.dumps(u, bin)
  3047. v = p.loads(s)
  3048. self.assertEqual(u.__class__, v.__class__)
  3049. self.assertEqual(u.foo, v.foo)
  3050. # Testing copy.deepcopy()
  3051. import copy
  3052. for cls in C, C1, C2:
  3053. cls2 = copy.deepcopy(cls)
  3054. self.assertIs(cls2, cls)
  3055. a = C1(1, 2); a.append(42); a.append(24)
  3056. b = C2("hello", "world", 42)
  3057. x, y = copy.deepcopy((a, b))
  3058. self.assertEqual(x.__class__, a.__class__)
  3059. self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
  3060. self.assertEqual(y.__class__, b.__class__)
  3061. self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
  3062. self.assertEqual(repr(x), repr(a))
  3063. self.assertEqual(repr(y), repr(b))
  3064. def test_pickle_slots(self):
  3065. # Testing pickling of classes with __slots__ ...
  3066. import pickle, cPickle
  3067. # Pickling of classes with __slots__ but without __getstate__ should fail
  3068. global B, C, D, E
  3069. class B(object):
  3070. pass
  3071. for base in [object, B]:
  3072. class C(base):
  3073. __slots__ = ['a']
  3074. class D(C):
  3075. pass
  3076. for proto in range(2):
  3077. try:
  3078. pickle.dumps(C(), proto)
  3079. except TypeError:
  3080. pass
  3081. else:
  3082. self.fail("should fail: pickle C instance - %s" % base)
  3083. try:
  3084. cPickle.dumps(C(), proto)
  3085. except TypeError:
  3086. pass
  3087. else:
  3088. self.fail("should fail: cPickle C instance - %s" % base)
  3089. try:
  3090. pickle.dumps(C(), proto)
  3091. except TypeError:
  3092. pass
  3093. else:
  3094. self.fail("should fail: pickle D instance - %s" % base)
  3095. try:
  3096. cPickle.dumps(D(), proto)
  3097. except TypeError:
  3098. pass
  3099. else:
  3100. self.fail("should fail: cPickle D instance - %s" % base)
  3101. # Give C a nice generic __getstate__ and __setstate__
  3102. class C(base):
  3103. __slots__ = ['a']
  3104. def __getstate__(self):
  3105. try:
  3106. d = self.__dict__.copy()
  3107. except AttributeError:
  3108. d = {}
  3109. for cls in self.__class__.__mro__:
  3110. for sn in cls.__dict__.get('__slots__', ()):
  3111. try:
  3112. d[sn] = getattr(self, sn)
  3113. except AttributeError:
  3114. pass
  3115. return d
  3116. def __setstate__(self, d):
  3117. for k, v in d.items():
  3118. setattr(self, k, v)
  3119. class D(C):
  3120. pass
  3121. # Now it should work
  3122. x = C()
  3123. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  3124. y = pickle.loads(pickle.dumps(x, proto))
  3125. self.assertNotHasAttr(y, 'a')
  3126. y = cPickle.loads(cPickle.dumps(x, proto))
  3127. self.assertNotHasAttr(y, 'a')
  3128. x.a = 42
  3129. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  3130. y = pickle.loads(pickle.dumps(x, proto))
  3131. self.assertEqual(y.a, 42)
  3132. y = cPickle.loads(cPickle.dumps(x, proto))
  3133. self.assertEqual(y.a, 42)
  3134. x = D()
  3135. x.a = 42
  3136. x.b = 100
  3137. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  3138. y = pickle.loads(pickle.dumps(x, proto))
  3139. self.assertEqual(y.a + y.b, 142)
  3140. y = cPickle.loads(cPickle.dumps(x, proto))
  3141. self.assertEqual(y.a + y.b, 142)
  3142. # A subclass that adds a slot should also work
  3143. class E(C):
  3144. __slots__ = ['b']
  3145. x = E()
  3146. x.a = 42
  3147. x.b = "foo"
  3148. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  3149. y = pickle.loads(pickle.dumps(x, proto))
  3150. self.assertEqual(y.a, x.a)
  3151. self.assertEqual(y.b, x.b)
  3152. y = cPickle.loads(cPickle.dumps(x, proto))
  3153. self.assertEqual(y.a, x.a)
  3154. self.assertEqual(y.b, x.b)
  3155. def test_binary_operator_override(self):
  3156. # Testing overrides of binary operations...
  3157. class I(int):
  3158. def __repr__(self):
  3159. return "I(%r)" % int(self)
  3160. def __add__(self, other):
  3161. return I(int(self) + int(other))
  3162. __radd__ = __add__
  3163. def __pow__(self, other, mod=None):
  3164. if mod is None:
  3165. return I(pow(int(self), int(other)))
  3166. else:
  3167. return I(pow(int(self), int(other), int(mod)))
  3168. def __rpow__(self, other, mod=None):
  3169. if mod is None:
  3170. return I(pow(int(other), int(self), mod))
  3171. else:
  3172. return I(pow(int(other), int(self), int(mod)))
  3173. self.assertEqual(repr(I(1) + I(2)), "I(3)")
  3174. self.assertEqual(repr(I(1) + 2), "I(3)")
  3175. self.assertEqual(repr(1 + I(2)), "I(3)")
  3176. self.assertEqual(repr(I(2) ** I(3)), "I(8)")
  3177. self.assertEqual(repr(2 ** I(3)), "I(8)")
  3178. self.assertEqual(repr(I(2) ** 3), "I(8)")
  3179. self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
  3180. class S(str):
  3181. def __eq__(self, other):
  3182. return self.lower() == other.lower()
  3183. __hash__ = None # Silence Py3k warning
  3184. def test_subclass_propagation(self):
  3185. # Testing propagation of slot functions to subclasses...
  3186. class A(object):
  3187. pass
  3188. class B(A):
  3189. pass
  3190. class C(A):
  3191. pass
  3192. class D(B, C):
  3193. pass
  3194. d = D()
  3195. orig_hash = hash(d) # related to id(d) in platform-dependent ways
  3196. A.__hash__ = lambda self: 42
  3197. self.assertEqual(hash(d), 42)
  3198. C.__hash__ = lambda self: 314
  3199. self.assertEqual(hash(d), 314)
  3200. B.__hash__ = lambda self: 144
  3201. self.assertEqual(hash(d), 144)
  3202. D.__hash__ = lambda self: 100
  3203. self.assertEqual(hash(d), 100)
  3204. D.__hash__ = None
  3205. self.assertRaises(TypeError, hash, d)
  3206. del D.__hash__
  3207. self.assertEqual(hash(d), 144)
  3208. B.__hash__ = None
  3209. self.assertRaises(TypeError, hash, d)
  3210. del B.__hash__
  3211. self.assertEqual(hash(d), 314)
  3212. C.__hash__ = None
  3213. self.assertRaises(TypeError, hash, d)
  3214. del C.__hash__
  3215. self.assertEqual(hash(d), 42)
  3216. A.__hash__ = None
  3217. self.assertRaises(TypeError, hash, d)
  3218. del A.__hash__
  3219. self.assertEqual(hash(d), orig_hash)
  3220. d.foo = 42
  3221. d.bar = 42
  3222. self.assertEqual(d.foo, 42)
  3223. self.assertEqual(d.bar, 42)
  3224. def __getattribute__(self, name):
  3225. if name == "foo":
  3226. return 24
  3227. return object.__getattribute__(self, name)
  3228. A.__getattribute__ = __getattribute__
  3229. self.assertEqual(d.foo, 24)
  3230. self.assertEqual(d.bar, 42)
  3231. def __getattr__(self, name):
  3232. if name in ("spam", "foo", "bar"):
  3233. return "hello"
  3234. raise AttributeError, name
  3235. B.__getattr__ = __getattr__
  3236. self.assertEqual(d.spam, "hello")
  3237. self.assertEqual(d.foo, 24)
  3238. self.assertEqual(d.bar, 42)
  3239. del A.__getattribute__
  3240. self.assertEqual(d.foo, 42)
  3241. del d.foo
  3242. self.assertEqual(d.foo, "hello")
  3243. self.assertEqual(d.bar, 42)
  3244. del B.__getattr__
  3245. try:
  3246. d.foo
  3247. except AttributeError:
  3248. pass
  3249. else:
  3250. self.fail("d.foo should be undefined now")
  3251. # Test a nasty bug in recurse_down_subclasses()
  3252. class A(object):
  3253. pass
  3254. class B(A):
  3255. pass
  3256. del B
  3257. test_support.gc_collect()
  3258. A.__setitem__ = lambda *a: None # crash
  3259. def test_buffer_inheritance(self):
  3260. # Testing that buffer interface is inherited ...
  3261. import binascii
  3262. # SF bug [#470040] ParseTuple t# vs subclasses.
  3263. class MyStr(str):
  3264. pass
  3265. base = 'abc'
  3266. m = MyStr(base)
  3267. # b2a_hex uses the buffer interface to get its argument's value, via
  3268. # PyArg_ParseTuple 't#' code.
  3269. self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
  3270. # It's not clear that unicode will continue to support the character
  3271. # buffer interface, and this test will fail if that's taken away.
  3272. class MyUni(unicode):
  3273. pass
  3274. base = u'abc'
  3275. m = MyUni(base)
  3276. self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
  3277. class MyInt(int):
  3278. pass
  3279. m = MyInt(42)
  3280. try:
  3281. binascii.b2a_hex(m)
  3282. self.fail('subclass of int should not have a buffer interface')
  3283. except TypeError:
  3284. pass
  3285. def test_str_of_str_subclass(self):
  3286. # Testing __str__ defined in subclass of str ...
  3287. import binascii
  3288. import cStringIO
  3289. class octetstring(str):
  3290. def __str__(self):
  3291. return binascii.b2a_hex(self)
  3292. def __repr__(self):
  3293. return self + " repr"
  3294. o = octetstring('A')
  3295. self.assertEqual(type(o), octetstring)
  3296. self.assertEqual(type(str(o)), str)
  3297. self.assertEqual(type(repr(o)), str)
  3298. self.assertEqual(ord(o), 0x41)
  3299. self.assertEqual(str(o), '41')
  3300. self.assertEqual(repr(o), 'A repr')
  3301. self.assertEqual(o.__str__(), '41')
  3302. self.assertEqual(o.__repr__(), 'A repr')
  3303. capture = cStringIO.StringIO()
  3304. # Calling str() or not exercises different internal paths.
  3305. print >> capture, o
  3306. print >> capture, str(o)
  3307. self.assertEqual(capture.getvalue(), '41\n41\n')
  3308. capture.close()
  3309. def test_keyword_arguments(self):
  3310. # Testing keyword arguments to __init__, __call__...
  3311. def f(a): return a
  3312. self.assertEqual(f.__call__(a=42), 42)
  3313. a = []
  3314. list.__init__(a, sequence=[0, 1, 2])
  3315. self.assertEqual(a, [0, 1, 2])
  3316. def test_recursive_call(self):
  3317. # Testing recursive __call__() by setting to instance of class...
  3318. class A(object):
  3319. pass
  3320. A.__call__ = A()
  3321. try:
  3322. A()()
  3323. except RuntimeError:
  3324. pass
  3325. else:
  3326. self.fail("Recursion limit should have been reached for __call__()")
  3327. def test_delete_hook(self):
  3328. # Testing __del__ hook...
  3329. log = []
  3330. class C(object):
  3331. def __del__(self):
  3332. log.append(1)
  3333. c = C()
  3334. self.assertEqual(log, [])
  3335. del c
  3336. test_support.gc_collect()
  3337. self.assertEqual(log, [1])
  3338. class D(object): pass
  3339. d = D()
  3340. try: del d[0]
  3341. except TypeError: pass
  3342. else: self.fail("invalid del() didn't raise TypeError")
  3343. def test_hash_inheritance(self):
  3344. # Testing hash of mutable subclasses...
  3345. class mydict(dict):
  3346. pass
  3347. d = mydict()
  3348. try:
  3349. hash(d)
  3350. except TypeError:
  3351. pass
  3352. else:
  3353. self.fail("hash() of dict subclass should fail")
  3354. class mylist(list):
  3355. pass
  3356. d = mylist()
  3357. try:
  3358. hash(d)
  3359. except TypeError:
  3360. pass
  3361. else:
  3362. self.fail("hash() of list subclass should fail")
  3363. def test_str_operations(self):
  3364. try: 'a' + 5
  3365. except TypeError: pass
  3366. else: self.fail("'' + 5 doesn't raise TypeError")
  3367. try: ''.split('')
  3368. except ValueError: pass
  3369. else: self.fail("''.split('') doesn't raise ValueError")
  3370. try: ''.join([0])
  3371. except TypeError: pass
  3372. else: self.fail("''.join([0]) doesn't raise TypeError")
  3373. try: ''.rindex('5')
  3374. except ValueError: pass
  3375. else: self.fail("''.rindex('5') doesn't raise ValueError")
  3376. try: '%(n)s' % None
  3377. except TypeError: pass
  3378. else: self.fail("'%(n)s' % None doesn't raise TypeError")
  3379. try: '%(n' % {}
  3380. except ValueError: pass
  3381. else: self.fail("'%(n' % {} '' doesn't raise ValueError")
  3382. try: '%*s' % ('abc')
  3383. except TypeError: pass
  3384. else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
  3385. try: '%*.*s' % ('abc', 5)
  3386. except TypeError: pass
  3387. else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
  3388. try: '%s' % (1, 2)
  3389. except TypeError: pass
  3390. else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
  3391. try: '%' % None
  3392. except ValueError: pass
  3393. else: self.fail("'%' % None doesn't raise ValueError")
  3394. self.assertEqual('534253'.isdigit(), 1)
  3395. self.assertEqual('534253x'.isdigit(), 0)
  3396. self.assertEqual('%c' % 5, '\x05')
  3397. self.assertEqual('%c' % '5', '5')
  3398. def test_deepcopy_recursive(self):
  3399. # Testing deepcopy of recursive objects...
  3400. class Node:
  3401. pass
  3402. a = Node()
  3403. b = Node()
  3404. a.b = b
  3405. b.a = a
  3406. z = deepcopy(a) # This blew up before
  3407. def test_uninitialized_modules(self):
  3408. # Testing uninitialized module objects...
  3409. from types import ModuleType as M
  3410. m = M.__new__(M)
  3411. str(m)
  3412. self.assertNotHasAttr(m, "__name__")
  3413. self.assertNotHasAttr(m, "__file__")
  3414. self.assertNotHasAttr(m, "foo")
  3415. self.assertFalse(m.__dict__) # None or {} are both reasonable answers
  3416. m.foo = 1
  3417. self.assertEqual(m.__dict__, {"foo": 1})
  3418. def test_funny_new(self):
  3419. # Testing __new__ returning something unexpected...
  3420. class C(object):
  3421. def __new__(cls, arg):
  3422. if isinstance(arg, str): return [1, 2, 3]
  3423. elif isinstance(arg, int): return object.__new__(D)
  3424. else: return object.__new__(cls)
  3425. class D(C):
  3426. def __init__(self, arg):
  3427. self.foo = arg
  3428. self.assertEqual(C("1"), [1, 2, 3])
  3429. self.assertEqual(D("1"), [1, 2, 3])
  3430. d = D(None)
  3431. self.assertEqual(d.foo, None)
  3432. d = C(1)
  3433. self.assertEqual(isinstance(d, D), True)
  3434. self.assertEqual(d.foo, 1)
  3435. d = D(1)
  3436. self.assertEqual(isinstance(d, D), True)
  3437. self.assertEqual(d.foo, 1)
  3438. def test_imul_bug(self):
  3439. # Testing for __imul__ problems...
  3440. # SF bug 544647
  3441. class C(object):
  3442. def __imul__(self, other):
  3443. return (self, other)
  3444. x = C()
  3445. y = x
  3446. y *= 1.0
  3447. self.assertEqual(y, (x, 1.0))
  3448. y = x
  3449. y *= 2
  3450. self.assertEqual(y, (x, 2))
  3451. y = x
  3452. y *= 3L
  3453. self.assertEqual(y, (x, 3L))
  3454. y = x
  3455. y *= 1L<<100
  3456. self.assertEqual(y, (x, 1L<<100))
  3457. y = x
  3458. y *= None
  3459. self.assertEqual(y, (x, None))
  3460. y = x
  3461. y *= "foo"
  3462. self.assertEqual(y, (x, "foo"))
  3463. def test_copy_setstate(self):
  3464. # Testing that copy.*copy() correctly uses __setstate__...
  3465. import copy
  3466. class C(object):
  3467. def __init__(self, foo=None):
  3468. self.foo = foo
  3469. self.__foo = foo
  3470. def setfoo(self, foo=None):
  3471. self.foo = foo
  3472. def getfoo(self):
  3473. return self.__foo
  3474. def __getstate__(self):
  3475. return [self.foo]
  3476. def __setstate__(self_, lst):
  3477. self.assertEqual(len(lst), 1)
  3478. self_.__foo = self_.foo = lst[0]
  3479. a = C(42)
  3480. a.setfoo(24)
  3481. self.assertEqual(a.foo, 24)
  3482. self.assertEqual(a.getfoo(), 42)
  3483. b = copy.copy(a)
  3484. self.assertEqual(b.foo, 24)
  3485. self.assertEqual(b.getfoo(), 24)
  3486. b = copy.deepcopy(a)
  3487. self.assertEqual(b.foo, 24)
  3488. self.assertEqual(b.getfoo(), 24)
  3489. def test_slices(self):
  3490. # Testing cases with slices and overridden __getitem__ ...
  3491. # Strings
  3492. self.assertEqual("hello"[:4], "hell")
  3493. self.assertEqual("hello"[slice(4)], "hell")
  3494. self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
  3495. class S(str):
  3496. def __getitem__(self, x):
  3497. return str.__getitem__(self, x)
  3498. self.assertEqual(S("hello")[:4], "hell")
  3499. self.assertEqual(S("hello")[slice(4)], "hell")
  3500. self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
  3501. # Tuples
  3502. self.assertEqual((1,2,3)[:2], (1,2))
  3503. self.assertEqual((1,2,3)[slice(2)], (1,2))
  3504. self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
  3505. class T(tuple):
  3506. def __getitem__(self, x):
  3507. return tuple.__getitem__(self, x)
  3508. self.assertEqual(T((1,2,3))[:2], (1,2))
  3509. self.assertEqual(T((1,2,3))[slice(2)], (1,2))
  3510. self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
  3511. # Lists
  3512. self.assertEqual([1,2,3][:2], [1,2])
  3513. self.assertEqual([1,2,3][slice(2)], [1,2])
  3514. self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
  3515. class L(list):
  3516. def __getitem__(self, x):
  3517. return list.__getitem__(self, x)
  3518. self.assertEqual(L([1,2,3])[:2], [1,2])
  3519. self.assertEqual(L([1,2,3])[slice(2)], [1,2])
  3520. self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
  3521. # Now do lists and __setitem__
  3522. a = L([1,2,3])
  3523. a[slice(1, 3)] = [3,2]
  3524. self.assertEqual(a, [1,3,2])
  3525. a[slice(0, 2, 1)] = [3,1]
  3526. self.assertEqual(a, [3,1,2])
  3527. a.__setitem__(slice(1, 3), [2,1])
  3528. self.assertEqual(a, [3,2,1])
  3529. a.__setitem__(slice(0, 2, 1), [2,3])
  3530. self.assertEqual(a, [2,3,1])
  3531. def test_subtype_resurrection(self):
  3532. # Testing resurrection of new-style instance...
  3533. class C(object):
  3534. container = []
  3535. def __del__(self):
  3536. # resurrect the instance
  3537. C.container.append(self)
  3538. c = C()
  3539. c.attr = 42
  3540. # The most interesting thing here is whether this blows up, due to
  3541. # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
  3542. # bug).
  3543. del c
  3544. # If that didn't blow up, it's also interesting to see whether clearing
  3545. # the last container slot works: that will attempt to delete c again,
  3546. # which will cause c to get appended back to the container again
  3547. # "during" the del. (On non-CPython implementations, however, __del__
  3548. # is typically not called again.)
  3549. test_support.gc_collect()
  3550. self.assertEqual(len(C.container), 1)
  3551. del C.container[-1]
  3552. if test_support.check_impl_detail():
  3553. test_support.gc_collect()
  3554. self.assertEqual(len(C.container), 1)
  3555. self.assertEqual(C.container[-1].attr, 42)
  3556. # Make c mortal again, so that the test framework with -l doesn't report
  3557. # it as a leak.
  3558. del C.__del__
  3559. def test_slots_trash(self):
  3560. # Testing slot trash...
  3561. # Deallocating deeply nested slotted trash caused stack overflows
  3562. class trash(object):
  3563. __slots__ = ['x']
  3564. def __init__(self, x):
  3565. self.x = x
  3566. o = None
  3567. for i in xrange(50000):
  3568. o = trash(o)
  3569. del o
  3570. def test_slots_multiple_inheritance(self):
  3571. # SF bug 575229, multiple inheritance w/ slots dumps core
  3572. class A(object):
  3573. __slots__=()
  3574. class B(object):
  3575. pass
  3576. class C(A,B) :
  3577. __slots__=()
  3578. if test_support.check_impl_detail():
  3579. self.assertEqual(C.__basicsize__, B.__basicsize__)
  3580. self.assertHasAttr(C, '__dict__')
  3581. self.assertHasAttr(C, '__weakref__')
  3582. C().x = 2
  3583. def test_rmul(self):
  3584. # Testing correct invocation of __rmul__...
  3585. # SF patch 592646
  3586. class C(object):
  3587. def __mul__(self, other):
  3588. return "mul"
  3589. def __rmul__(self, other):
  3590. return "rmul"
  3591. a = C()
  3592. self.assertEqual(a*2, "mul")
  3593. self.assertEqual(a*2.2, "mul")
  3594. self.assertEqual(2*a, "rmul")
  3595. self.assertEqual(2.2*a, "rmul")
  3596. def test_ipow(self):
  3597. # Testing correct invocation of __ipow__...
  3598. # [SF bug 620179]
  3599. class C(object):
  3600. def __ipow__(self, other):
  3601. pass
  3602. a = C()
  3603. a **= 2
  3604. def test_mutable_bases(self):
  3605. # Testing mutable bases...
  3606. # stuff that should work:
  3607. class C(object):
  3608. pass
  3609. class C2(object):
  3610. def __getattribute__(self, attr):
  3611. if attr == 'a':
  3612. return 2
  3613. else:
  3614. return super(C2, self).__getattribute__(attr)
  3615. def meth(self):
  3616. return 1
  3617. class D(C):
  3618. pass
  3619. class E(D):
  3620. pass
  3621. d = D()
  3622. e = E()
  3623. D.__bases__ = (C,)
  3624. D.__bases__ = (C2,)
  3625. self.assertEqual(d.meth(), 1)
  3626. self.assertEqual(e.meth(), 1)
  3627. self.assertEqual(d.a, 2)
  3628. self.assertEqual(e.a, 2)
  3629. self.assertEqual(C2.__subclasses__(), [D])
  3630. try:
  3631. del D.__bases__
  3632. except (TypeError, AttributeError):
  3633. pass
  3634. else:
  3635. self.fail("shouldn't be able to delete .__bases__")
  3636. try:
  3637. D.__bases__ = ()
  3638. except TypeError, msg:
  3639. if str(msg) == "a new-style class can't have only classic bases":
  3640. self.fail("wrong error message for .__bases__ = ()")
  3641. else:
  3642. self.fail("shouldn't be able to set .__bases__ to ()")
  3643. try:
  3644. D.__bases__ = (D,)
  3645. except TypeError:
  3646. pass
  3647. else:
  3648. # actually, we'll have crashed by here...
  3649. self.fail("shouldn't be able to create inheritance cycles")
  3650. try:
  3651. D.__bases__ = (C, C)
  3652. except TypeError:
  3653. pass
  3654. else:
  3655. self.fail("didn't detect repeated base classes")
  3656. try:
  3657. D.__bases__ = (E,)
  3658. except TypeError:
  3659. pass
  3660. else:
  3661. self.fail("shouldn't be able to create inheritance cycles")
  3662. # let's throw a classic class into the mix:
  3663. class Classic:
  3664. def meth2(self):
  3665. return 3
  3666. D.__bases__ = (C, Classic)
  3667. self.assertEqual(d.meth2(), 3)
  3668. self.assertEqual(e.meth2(), 3)
  3669. try:
  3670. d.a
  3671. except AttributeError:
  3672. pass
  3673. else:
  3674. self.fail("attribute should have vanished")
  3675. try:
  3676. D.__bases__ = (Classic,)
  3677. except TypeError:
  3678. pass
  3679. else:
  3680. self.fail("new-style class must have a new-style base")
  3681. def test_builtin_bases(self):
  3682. # Make sure all the builtin types can have their base queried without
  3683. # segfaulting. See issue #5787.
  3684. builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
  3685. if isinstance(tp, type)]
  3686. for tp in builtin_types:
  3687. object.__getattribute__(tp, "__bases__")
  3688. if tp is not object:
  3689. self.assertEqual(len(tp.__bases__), 1, tp)
  3690. class L(list):
  3691. pass
  3692. class C(object):
  3693. pass
  3694. class D(C):
  3695. pass
  3696. try:
  3697. L.__bases__ = (dict,)
  3698. except TypeError:
  3699. pass
  3700. else:
  3701. self.fail("shouldn't turn list subclass into dict subclass")
  3702. try:
  3703. list.__bases__ = (dict,)
  3704. except TypeError:
  3705. pass
  3706. else:
  3707. self.fail("shouldn't be able to assign to list.__bases__")
  3708. try:
  3709. D.__bases__ = (C, list)
  3710. except TypeError:
  3711. pass
  3712. else:
  3713. assert 0, "best_base calculation found wanting"
  3714. def test_unsubclassable_types(self):
  3715. with self.assertRaises(TypeError):
  3716. class X(types.NoneType):
  3717. pass
  3718. with self.assertRaises(TypeError):
  3719. class X(object, types.NoneType):
  3720. pass
  3721. with self.assertRaises(TypeError):
  3722. class X(types.NoneType, object):
  3723. pass
  3724. class O(object):
  3725. pass
  3726. with self.assertRaises(TypeError):
  3727. class X(O, types.NoneType):
  3728. pass
  3729. with self.assertRaises(TypeError):
  3730. class X(types.NoneType, O):
  3731. pass
  3732. class X(object):
  3733. pass
  3734. with self.assertRaises(TypeError):
  3735. X.__bases__ = types.NoneType,
  3736. with self.assertRaises(TypeError):
  3737. X.__bases__ = object, types.NoneType
  3738. with self.assertRaises(TypeError):
  3739. X.__bases__ = types.NoneType, object
  3740. with self.assertRaises(TypeError):
  3741. X.__bases__ = O, types.NoneType
  3742. with self.assertRaises(TypeError):
  3743. X.__bases__ = types.NoneType, O
  3744. def test_mutable_bases_with_failing_mro(self):
  3745. # Testing mutable bases with failing mro...
  3746. class WorkOnce(type):
  3747. def __new__(self, name, bases, ns):
  3748. self.flag = 0
  3749. return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
  3750. def mro(self):
  3751. if self.flag > 0:
  3752. raise RuntimeError, "bozo"
  3753. else:
  3754. self.flag += 1
  3755. return type.mro(self)
  3756. class WorkAlways(type):
  3757. def mro(self):
  3758. # this is here to make sure that .mro()s aren't called
  3759. # with an exception set (which was possible at one point).
  3760. # An error message will be printed in a debug build.
  3761. # What's a good way to test for this?
  3762. return type.mro(self)
  3763. class C(object):
  3764. pass
  3765. class C2(object):
  3766. pass
  3767. class D(C):
  3768. pass
  3769. class E(D):
  3770. pass
  3771. class F(D):
  3772. __metaclass__ = WorkOnce
  3773. class G(D):
  3774. __metaclass__ = WorkAlways
  3775. # Immediate subclasses have their mro's adjusted in alphabetical
  3776. # order, so E's will get adjusted before adjusting F's fails. We
  3777. # check here that E's gets restored.
  3778. E_mro_before = E.__mro__
  3779. D_mro_before = D.__mro__
  3780. try:
  3781. D.__bases__ = (C2,)
  3782. except RuntimeError:
  3783. self.assertEqual(E.__mro__, E_mro_before)
  3784. self.assertEqual(D.__mro__, D_mro_before)
  3785. else:
  3786. self.fail("exception not propagated")
  3787. def test_mutable_bases_catch_mro_conflict(self):
  3788. # Testing mutable bases catch mro conflict...
  3789. class A(object):
  3790. pass
  3791. class B(object):
  3792. pass
  3793. class C(A, B):
  3794. pass
  3795. class D(A, B):
  3796. pass
  3797. class E(C, D):
  3798. pass
  3799. try:
  3800. C.__bases__ = (B, A)
  3801. except TypeError:
  3802. pass
  3803. else:
  3804. self.fail("didn't catch MRO conflict")
  3805. def test_mutable_names(self):
  3806. # Testing mutable names...
  3807. class C(object):
  3808. pass
  3809. # C.__module__ could be 'test_descr' or '__main__'
  3810. mod = C.__module__
  3811. C.__name__ = 'D'
  3812. self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
  3813. C.__name__ = 'D.E'
  3814. self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
  3815. def test_evil_type_name(self):
  3816. # A badly placed Py_DECREF in type_set_name led to arbitrary code
  3817. # execution while the type structure was not in a sane state, and a
  3818. # possible segmentation fault as a result. See bug #16447.
  3819. class Nasty(str):
  3820. def __del__(self):
  3821. C.__name__ = "other"
  3822. class C(object):
  3823. pass
  3824. C.__name__ = Nasty("abc")
  3825. C.__name__ = "normal"
  3826. def test_subclass_right_op(self):
  3827. # Testing correct dispatch of subclass overloading __r<op>__...
  3828. # This code tests various cases where right-dispatch of a subclass
  3829. # should be preferred over left-dispatch of a base class.
  3830. # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
  3831. class B(int):
  3832. def __floordiv__(self, other):
  3833. return "B.__floordiv__"
  3834. def __rfloordiv__(self, other):
  3835. return "B.__rfloordiv__"
  3836. self.assertEqual(B(1) // 1, "B.__floordiv__")
  3837. self.assertEqual(1 // B(1), "B.__rfloordiv__")
  3838. # Case 2: subclass of object; this is just the baseline for case 3
  3839. class C(object):
  3840. def __floordiv__(self, other):
  3841. return "C.__floordiv__"
  3842. def __rfloordiv__(self, other):
  3843. return "C.__rfloordiv__"
  3844. self.assertEqual(C() // 1, "C.__floordiv__")
  3845. self.assertEqual(1 // C(), "C.__rfloordiv__")
  3846. # Case 3: subclass of new-style class; here it gets interesting
  3847. class D(C):
  3848. def __floordiv__(self, other):
  3849. return "D.__floordiv__"
  3850. def __rfloordiv__(self, other):
  3851. return "D.__rfloordiv__"
  3852. self.assertEqual(D() // C(), "D.__floordiv__")
  3853. self.assertEqual(C() // D(), "D.__rfloordiv__")
  3854. # Case 4: this didn't work right in 2.2.2 and 2.3a1
  3855. class E(C):
  3856. pass
  3857. self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
  3858. self.assertEqual(E() // 1, "C.__floordiv__")
  3859. self.assertEqual(1 // E(), "C.__rfloordiv__")
  3860. self.assertEqual(E() // C(), "C.__floordiv__")
  3861. self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
  3862. @test_support.impl_detail("testing an internal kind of method object")
  3863. def test_meth_class_get(self):
  3864. # Testing __get__ method of METH_CLASS C methods...
  3865. # Full coverage of descrobject.c::classmethod_get()
  3866. # Baseline
  3867. arg = [1, 2, 3]
  3868. res = {1: None, 2: None, 3: None}
  3869. self.assertEqual(dict.fromkeys(arg), res)
  3870. self.assertEqual({}.fromkeys(arg), res)
  3871. # Now get the descriptor
  3872. descr = dict.__dict__["fromkeys"]
  3873. # More baseline using the descriptor directly
  3874. self.assertEqual(descr.__get__(None, dict)(arg), res)
  3875. self.assertEqual(descr.__get__({})(arg), res)
  3876. # Now check various error cases
  3877. try:
  3878. descr.__get__(None, None)
  3879. except TypeError:
  3880. pass
  3881. else:
  3882. self.fail("shouldn't have allowed descr.__get__(None, None)")
  3883. try:
  3884. descr.__get__(42)
  3885. except TypeError:
  3886. pass
  3887. else:
  3888. self.fail("shouldn't have allowed descr.__get__(42)")
  3889. try:
  3890. descr.__get__(None, 42)
  3891. except TypeError:
  3892. pass
  3893. else:
  3894. self.fail("shouldn't have allowed descr.__get__(None, 42)")
  3895. try:
  3896. descr.__get__(None, int)
  3897. except TypeError:
  3898. pass
  3899. else:
  3900. self.fail("shouldn't have allowed descr.__get__(None, int)")
  3901. def test_isinst_isclass(self):
  3902. # Testing proxy isinstance() and isclass()...
  3903. class Proxy(object):
  3904. def __init__(self, obj):
  3905. self.__obj = obj
  3906. def __getattribute__(self, name):
  3907. if name.startswith("_Proxy__"):
  3908. return object.__getattribute__(self, name)
  3909. else:
  3910. return getattr(self.__obj, name)
  3911. # Test with a classic class
  3912. class C:
  3913. pass
  3914. a = C()
  3915. pa = Proxy(a)
  3916. self.assertIsInstance(a, C) # Baseline
  3917. self.assertIsInstance(pa, C) # Test
  3918. # Test with a classic subclass
  3919. class D(C):
  3920. pass
  3921. a = D()
  3922. pa = Proxy(a)
  3923. self.assertIsInstance(a, C) # Baseline
  3924. self.assertIsInstance(pa, C) # Test
  3925. # Test with a new-style class
  3926. class C(object):
  3927. pass
  3928. a = C()
  3929. pa = Proxy(a)
  3930. self.assertIsInstance(a, C) # Baseline
  3931. self.assertIsInstance(pa, C) # Test
  3932. # Test with a new-style subclass
  3933. class D(C):
  3934. pass
  3935. a = D()
  3936. pa = Proxy(a)
  3937. self.assertIsInstance(a, C) # Baseline
  3938. self.assertIsInstance(pa, C) # Test
  3939. def test_proxy_super(self):
  3940. # Testing super() for a proxy object...
  3941. class Proxy(object):
  3942. def __init__(self, obj):
  3943. self.__obj = obj
  3944. def __getattribute__(self, name):
  3945. if name.startswith("_Proxy__"):
  3946. return object.__getattribute__(self, name)
  3947. else:
  3948. return getattr(self.__obj, name)
  3949. class B(object):
  3950. def f(self):
  3951. return "B.f"
  3952. class C(B):
  3953. def f(self):
  3954. return super(C, self).f() + "->C.f"
  3955. obj = C()
  3956. p = Proxy(obj)
  3957. self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
  3958. def test_carloverre(self):
  3959. # Testing prohibition of Carlo Verre's hack...
  3960. try:
  3961. object.__setattr__(str, "foo", 42)
  3962. except TypeError:
  3963. pass
  3964. else:
  3965. self.fail("Carlo Verre __setattr__ succeeded!")
  3966. try:
  3967. object.__delattr__(str, "lower")
  3968. except TypeError:
  3969. pass
  3970. else:
  3971. self.fail("Carlo Verre __delattr__ succeeded!")
  3972. def test_weakref_segfault(self):
  3973. # Testing weakref segfault...
  3974. # SF 742911
  3975. import weakref
  3976. class Provoker:
  3977. def __init__(self, referrent):
  3978. self.ref = weakref.ref(referrent)
  3979. def __del__(self):
  3980. x = self.ref()
  3981. class Oops(object):
  3982. pass
  3983. o = Oops()
  3984. o.whatever = Provoker(o)
  3985. del o
  3986. def test_wrapper_segfault(self):
  3987. # SF 927248: deeply nested wrappers could cause stack overflow
  3988. f = lambda:None
  3989. for i in xrange(1000000):
  3990. f = f.__call__
  3991. f = None
  3992. def test_file_fault(self):
  3993. # Testing sys.stdout is changed in getattr...
  3994. test_stdout = sys.stdout
  3995. class StdoutGuard:
  3996. def __getattr__(self, attr):
  3997. sys.stdout = sys.__stdout__
  3998. raise RuntimeError("Premature access to sys.stdout.%s" % attr)
  3999. sys.stdout = StdoutGuard()
  4000. try:
  4001. print "Oops!"
  4002. except RuntimeError:
  4003. pass
  4004. finally:
  4005. sys.stdout = test_stdout
  4006. def test_vicious_descriptor_nonsense(self):
  4007. # Testing vicious_descriptor_nonsense...
  4008. # A potential segfault spotted by Thomas Wouters in mail to
  4009. # python-dev 2003-04-17, turned into an example & fixed by Michael
  4010. # Hudson just less than four months later...
  4011. class Evil(object):
  4012. def __hash__(self):
  4013. return hash('attr')
  4014. def __eq__(self, other):
  4015. del C.attr
  4016. return 0
  4017. class Descr(object):
  4018. def __get__(self, ob, type=None):
  4019. return 1
  4020. class C(object):
  4021. attr = Descr()
  4022. c = C()
  4023. c.__dict__[Evil()] = 0
  4024. self.assertEqual(c.attr, 1)
  4025. # this makes a crash more likely:
  4026. test_support.gc_collect()
  4027. self.assertNotHasAttr(c, 'attr')
  4028. def test_init(self):
  4029. # SF 1155938
  4030. class Foo(object):
  4031. def __init__(self):
  4032. return 10
  4033. try:
  4034. Foo()
  4035. except TypeError:
  4036. pass
  4037. else:
  4038. self.fail("did not test __init__() for None return")
  4039. def test_method_wrapper(self):
  4040. # Testing method-wrapper objects...
  4041. # <type 'method-wrapper'> did not support any reflection before 2.5
  4042. l = []
  4043. self.assertEqual(l.__add__, l.__add__)
  4044. self.assertEqual(l.__add__, [].__add__)
  4045. self.assertNotEqual(l.__add__, [5].__add__)
  4046. self.assertNotEqual(l.__add__, l.__mul__)
  4047. self.assertEqual(l.__add__.__name__, '__add__')
  4048. if hasattr(l.__add__, '__self__'):
  4049. # CPython
  4050. self.assertIs(l.__add__.__self__, l)
  4051. self.assertIs(l.__add__.__objclass__, list)
  4052. else:
  4053. # Python implementations where [].__add__ is a normal bound method
  4054. self.assertIs(l.__add__.im_self, l)
  4055. self.assertIs(l.__add__.im_class, list)
  4056. self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
  4057. try:
  4058. hash(l.__add__)
  4059. except TypeError:
  4060. pass
  4061. else:
  4062. self.fail("no TypeError from hash([].__add__)")
  4063. t = ()
  4064. t += (7,)
  4065. self.assertEqual(t.__add__, (7,).__add__)
  4066. self.assertEqual(hash(t.__add__), hash((7,).__add__))
  4067. def test_not_implemented(self):
  4068. # Testing NotImplemented...
  4069. # all binary methods should be able to return a NotImplemented
  4070. import operator
  4071. def specialmethod(self, other):
  4072. return NotImplemented
  4073. def check(expr, x, y):
  4074. try:
  4075. exec expr in {'x': x, 'y': y, 'operator': operator}
  4076. except TypeError:
  4077. pass
  4078. else:
  4079. self.fail("no TypeError from %r" % (expr,))
  4080. N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
  4081. # TypeErrors
  4082. N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
  4083. # ValueErrors instead of TypeErrors
  4084. for metaclass in [type, types.ClassType]:
  4085. for name, expr, iexpr in [
  4086. ('__add__', 'x + y', 'x += y'),
  4087. ('__sub__', 'x - y', 'x -= y'),
  4088. ('__mul__', 'x * y', 'x *= y'),
  4089. ('__truediv__', 'operator.truediv(x, y)', None),
  4090. ('__floordiv__', 'operator.floordiv(x, y)', None),
  4091. ('__div__', 'x / y', 'x /= y'),
  4092. ('__mod__', 'x % y', 'x %= y'),
  4093. ('__divmod__', 'divmod(x, y)', None),
  4094. ('__pow__', 'x ** y', 'x **= y'),
  4095. ('__lshift__', 'x << y', 'x <<= y'),
  4096. ('__rshift__', 'x >> y', 'x >>= y'),
  4097. ('__and__', 'x & y', 'x &= y'),
  4098. ('__or__', 'x | y', 'x |= y'),
  4099. ('__xor__', 'x ^ y', 'x ^= y'),
  4100. ('__coerce__', 'coerce(x, y)', None)]:
  4101. if name == '__coerce__':
  4102. rname = name
  4103. else:
  4104. rname = '__r' + name[2:]
  4105. A = metaclass('A', (), {name: specialmethod})
  4106. B = metaclass('B', (), {rname: specialmethod})
  4107. a = A()
  4108. b = B()
  4109. check(expr, a, a)
  4110. check(expr, a, b)
  4111. check(expr, b, a)
  4112. check(expr, b, b)
  4113. check(expr, a, N1)
  4114. check(expr, a, N2)
  4115. check(expr, N1, b)
  4116. check(expr, N2, b)
  4117. if iexpr:
  4118. check(iexpr, a, a)
  4119. check(iexpr, a, b)
  4120. check(iexpr, b, a)
  4121. check(iexpr, b, b)
  4122. check(iexpr, a, N1)
  4123. check(iexpr, a, N2)
  4124. iname = '__i' + name[2:]
  4125. C = metaclass('C', (), {iname: specialmethod})
  4126. c = C()
  4127. check(iexpr, c, a)
  4128. check(iexpr, c, b)
  4129. check(iexpr, c, N1)
  4130. check(iexpr, c, N2)
  4131. def test_assign_slice(self):
  4132. # ceval.c's assign_slice used to check for
  4133. # tp->tp_as_sequence->sq_slice instead of
  4134. # tp->tp_as_sequence->sq_ass_slice
  4135. class C(object):
  4136. def __setslice__(self, start, stop, value):
  4137. self.value = value
  4138. c = C()
  4139. c[1:2] = 3
  4140. self.assertEqual(c.value, 3)
  4141. def test_set_and_no_get(self):
  4142. # See
  4143. # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
  4144. class Descr(object):
  4145. def __init__(self, name):
  4146. self.name = name
  4147. def __set__(self, obj, value):
  4148. obj.__dict__[self.name] = value
  4149. descr = Descr("a")
  4150. class X(object):
  4151. a = descr
  4152. x = X()
  4153. self.assertIs(x.a, descr)
  4154. x.a = 42
  4155. self.assertEqual(x.a, 42)
  4156. # Also check type_getattro for correctness.
  4157. class Meta(type):
  4158. pass
  4159. class X(object):
  4160. __metaclass__ = Meta
  4161. X.a = 42
  4162. Meta.a = Descr("a")
  4163. self.assertEqual(X.a, 42)
  4164. def test_getattr_hooks(self):
  4165. # issue 4230
  4166. class Descriptor(object):
  4167. counter = 0
  4168. def __get__(self, obj, objtype=None):
  4169. def getter(name):
  4170. self.counter += 1
  4171. raise AttributeError(name)
  4172. return getter
  4173. descr = Descriptor()
  4174. class A(object):
  4175. __getattribute__ = descr
  4176. class B(object):
  4177. __getattr__ = descr
  4178. class C(object):
  4179. __getattribute__ = descr
  4180. __getattr__ = descr
  4181. self.assertRaises(AttributeError, getattr, A(), "attr")
  4182. self.assertEqual(descr.counter, 1)
  4183. self.assertRaises(AttributeError, getattr, B(), "attr")
  4184. self.assertEqual(descr.counter, 2)
  4185. self.assertRaises(AttributeError, getattr, C(), "attr")
  4186. self.assertEqual(descr.counter, 4)
  4187. class EvilGetattribute(object):
  4188. # This used to segfault
  4189. def __getattr__(self, name):
  4190. raise AttributeError(name)
  4191. def __getattribute__(self, name):
  4192. del EvilGetattribute.__getattr__
  4193. for i in range(5):
  4194. gc.collect()
  4195. raise AttributeError(name)
  4196. self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
  4197. def test_type___getattribute__(self):
  4198. self.assertRaises(TypeError, type.__getattribute__, list, type)
  4199. def test_abstractmethods(self):
  4200. # type pretends not to have __abstractmethods__.
  4201. self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
  4202. class meta(type):
  4203. pass
  4204. self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
  4205. class X(object):
  4206. pass
  4207. with self.assertRaises(AttributeError):
  4208. del X.__abstractmethods__
  4209. def test_proxy_call(self):
  4210. class FakeStr(object):
  4211. __class__ = str
  4212. fake_str = FakeStr()
  4213. # isinstance() reads __class__ on new style classes
  4214. self.assertIsInstance(fake_str, str)
  4215. # call a method descriptor
  4216. with self.assertRaises(TypeError):
  4217. str.split(fake_str)
  4218. # call a slot wrapper descriptor
  4219. with self.assertRaises(TypeError):
  4220. str.__add__(fake_str, "abc")
  4221. def test_repr_as_str(self):
  4222. # Issue #11603: crash or infinite loop when rebinding __str__ as
  4223. # __repr__.
  4224. class Foo(object):
  4225. pass
  4226. Foo.__repr__ = Foo.__str__
  4227. foo = Foo()
  4228. self.assertRaises(RuntimeError, str, foo)
  4229. self.assertRaises(RuntimeError, repr, foo)
  4230. def test_mixing_slot_wrappers(self):
  4231. class X(dict):
  4232. __setattr__ = dict.__setitem__
  4233. x = X()
  4234. x.y = 42
  4235. self.assertEqual(x["y"], 42)
  4236. def test_cycle_through_dict(self):
  4237. # See bug #1469629
  4238. class X(dict):
  4239. def __init__(self):
  4240. dict.__init__(self)
  4241. self.__dict__ = self
  4242. x = X()
  4243. x.attr = 42
  4244. wr = weakref.ref(x)
  4245. del x
  4246. test_support.gc_collect()
  4247. self.assertIsNone(wr())
  4248. for o in gc.get_objects():
  4249. self.assertIsNot(type(o), X)
  4250. class DictProxyTests(unittest.TestCase):
  4251. def setUp(self):
  4252. class C(object):
  4253. def meth(self):
  4254. pass
  4255. self.C = C
  4256. def test_repr(self):
  4257. self.assertIn('dict_proxy({', repr(vars(self.C)))
  4258. self.assertIn("'meth':", repr(vars(self.C)))
  4259. def test_iter_keys(self):
  4260. # Testing dict-proxy iterkeys...
  4261. keys = [ key for key in self.C.__dict__.iterkeys() ]
  4262. keys.sort()
  4263. self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
  4264. '__weakref__', 'meth'])
  4265. def test_iter_values(self):
  4266. # Testing dict-proxy itervalues...
  4267. values = [ values for values in self.C.__dict__.itervalues() ]
  4268. self.assertEqual(len(values), 5)
  4269. def test_iter_items(self):
  4270. # Testing dict-proxy iteritems...
  4271. keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
  4272. keys.sort()
  4273. self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
  4274. '__weakref__', 'meth'])
  4275. def test_dict_type_with_metaclass(self):
  4276. # Testing type of __dict__ when __metaclass__ set...
  4277. class B(object):
  4278. pass
  4279. class M(type):
  4280. pass
  4281. class C:
  4282. # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
  4283. __metaclass__ = M
  4284. self.assertEqual(type(C.__dict__), type(B.__dict__))
  4285. class PTypesLongInitTest(unittest.TestCase):
  4286. # This is in its own TestCase so that it can be run before any other tests.
  4287. def test_pytype_long_ready(self):
  4288. # Testing SF bug 551412 ...
  4289. # This dumps core when SF bug 551412 isn't fixed --
  4290. # but only when test_descr.py is run separately.
  4291. # (That can't be helped -- as soon as PyType_Ready()
  4292. # is called for PyLong_Type, the bug is gone.)
  4293. class UserLong(object):
  4294. def __pow__(self, *args):
  4295. pass
  4296. try:
  4297. pow(0L, UserLong(), 0L)
  4298. except:
  4299. pass
  4300. # Another segfault only when run early
  4301. # (before PyType_Ready(tuple) is called)
  4302. type.mro(tuple)
  4303. class PicklingTests(unittest.TestCase):
  4304. def test_issue24097(self):
  4305. # Slot name is freed inside __getattr__ and is later used.
  4306. class S(str): # Not interned
  4307. pass
  4308. class A(object):
  4309. __slotnames__ = [S('spam')]
  4310. def __getattr__(self, attr):
  4311. if attr == 'spam':
  4312. A.__slotnames__[:] = [S('spam')]
  4313. return 42
  4314. else:
  4315. raise AttributeError
  4316. import copy_reg
  4317. expected = (copy_reg.__newobj__, (A,), ({}, {'spam': 42}), None, None)
  4318. self.assertEqual(A().__reduce__(2), expected)
  4319. def test_main():
  4320. deprecations = [(r'complex divmod\(\), // and % are deprecated$',
  4321. DeprecationWarning)]
  4322. if sys.py3kwarning:
  4323. deprecations += [
  4324. ("classic (int|long) division", DeprecationWarning),
  4325. ("coerce.. not supported", DeprecationWarning),
  4326. (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
  4327. with test_support.check_warnings(*deprecations):
  4328. # Run all local test cases, with PTypesLongInitTest first.
  4329. test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
  4330. ClassPropertiesAndMethods, DictProxyTests,
  4331. PicklingTests)
  4332. if __name__ == "__main__":
  4333. test_main()