test_descr.py 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825
  1. import builtins
  2. import copyreg
  3. import gc
  4. import itertools
  5. import math
  6. import pickle
  7. import random
  8. import string
  9. import sys
  10. import types
  11. import unittest
  12. import warnings
  13. import weakref
  14. from copy import deepcopy
  15. from contextlib import redirect_stdout
  16. from test import support
  17. try:
  18. import _testcapi
  19. except ImportError:
  20. _testcapi = None
  21. class OperatorsTest(unittest.TestCase):
  22. def __init__(self, *args, **kwargs):
  23. unittest.TestCase.__init__(self, *args, **kwargs)
  24. self.binops = {
  25. 'add': '+',
  26. 'sub': '-',
  27. 'mul': '*',
  28. 'matmul': '@',
  29. 'truediv': '/',
  30. 'floordiv': '//',
  31. 'divmod': 'divmod',
  32. 'pow': '**',
  33. 'lshift': '<<',
  34. 'rshift': '>>',
  35. 'and': '&',
  36. 'xor': '^',
  37. 'or': '|',
  38. 'cmp': 'cmp',
  39. 'lt': '<',
  40. 'le': '<=',
  41. 'eq': '==',
  42. 'ne': '!=',
  43. 'gt': '>',
  44. 'ge': '>=',
  45. }
  46. for name, expr in list(self.binops.items()):
  47. if expr.islower():
  48. expr = expr + "(a, b)"
  49. else:
  50. expr = 'a %s b' % expr
  51. self.binops[name] = expr
  52. self.unops = {
  53. 'pos': '+',
  54. 'neg': '-',
  55. 'abs': 'abs',
  56. 'invert': '~',
  57. 'int': 'int',
  58. 'float': 'float',
  59. }
  60. for name, expr in list(self.unops.items()):
  61. if expr.islower():
  62. expr = expr + "(a)"
  63. else:
  64. expr = '%s a' % expr
  65. self.unops[name] = expr
  66. def unop_test(self, a, res, expr="len(a)", meth="__len__"):
  67. d = {'a': a}
  68. self.assertEqual(eval(expr, d), res)
  69. t = type(a)
  70. m = getattr(t, meth)
  71. # Find method in parent class
  72. while meth not in t.__dict__:
  73. t = t.__bases__[0]
  74. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  75. # method object; the getattr() below obtains its underlying function.
  76. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  77. self.assertEqual(m(a), res)
  78. bm = getattr(a, meth)
  79. self.assertEqual(bm(), res)
  80. def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
  81. d = {'a': a, 'b': b}
  82. self.assertEqual(eval(expr, d), res)
  83. t = type(a)
  84. m = getattr(t, meth)
  85. while meth not in t.__dict__:
  86. t = t.__bases__[0]
  87. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  88. # method object; the getattr() below obtains its underlying function.
  89. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  90. self.assertEqual(m(a, b), res)
  91. bm = getattr(a, meth)
  92. self.assertEqual(bm(b), res)
  93. def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
  94. d = {'a': a, 'b': b, 'c': c}
  95. self.assertEqual(eval(expr, d), res)
  96. t = type(a)
  97. m = getattr(t, meth)
  98. while meth not in t.__dict__:
  99. t = t.__bases__[0]
  100. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  101. # method object; the getattr() below obtains its underlying function.
  102. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  103. self.assertEqual(m(a, slice(b, c)), res)
  104. bm = getattr(a, meth)
  105. self.assertEqual(bm(slice(b, c)), res)
  106. def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
  107. d = {'a': deepcopy(a), 'b': b}
  108. exec(stmt, d)
  109. self.assertEqual(d['a'], res)
  110. t = type(a)
  111. m = getattr(t, meth)
  112. while meth not in t.__dict__:
  113. t = t.__bases__[0]
  114. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  115. # method object; the getattr() below obtains its underlying function.
  116. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  117. d['a'] = deepcopy(a)
  118. m(d['a'], b)
  119. self.assertEqual(d['a'], res)
  120. d['a'] = deepcopy(a)
  121. bm = getattr(d['a'], meth)
  122. bm(b)
  123. self.assertEqual(d['a'], res)
  124. def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
  125. d = {'a': deepcopy(a), 'b': b, 'c': c}
  126. exec(stmt, d)
  127. self.assertEqual(d['a'], res)
  128. t = type(a)
  129. m = getattr(t, meth)
  130. while meth not in t.__dict__:
  131. t = t.__bases__[0]
  132. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  133. # method object; the getattr() below obtains its underlying function.
  134. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  135. d['a'] = deepcopy(a)
  136. m(d['a'], b, c)
  137. self.assertEqual(d['a'], res)
  138. d['a'] = deepcopy(a)
  139. bm = getattr(d['a'], meth)
  140. bm(b, c)
  141. self.assertEqual(d['a'], res)
  142. def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
  143. dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
  144. exec(stmt, dictionary)
  145. self.assertEqual(dictionary['a'], res)
  146. t = type(a)
  147. while meth not in t.__dict__:
  148. t = t.__bases__[0]
  149. m = getattr(t, meth)
  150. # in some implementations (e.g. PyPy), 'm' can be a regular unbound
  151. # method object; the getattr() below obtains its underlying function.
  152. self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
  153. dictionary['a'] = deepcopy(a)
  154. m(dictionary['a'], slice(b, c), d)
  155. self.assertEqual(dictionary['a'], res)
  156. dictionary['a'] = deepcopy(a)
  157. bm = getattr(dictionary['a'], meth)
  158. bm(slice(b, c), d)
  159. self.assertEqual(dictionary['a'], res)
  160. def test_lists(self):
  161. # Testing list operations...
  162. # Asserts are within individual test methods
  163. self.binop_test([1], [2], [1,2], "a+b", "__add__")
  164. self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
  165. self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
  166. self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
  167. self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
  168. self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
  169. self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
  170. self.unop_test([1,2,3], 3, "len(a)", "__len__")
  171. self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
  172. self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
  173. self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
  174. self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
  175. "__setitem__")
  176. def test_dicts(self):
  177. # Testing dict operations...
  178. self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
  179. self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
  180. self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
  181. d = {1:2, 3:4}
  182. l1 = []
  183. for i in list(d.keys()):
  184. l1.append(i)
  185. l = []
  186. for i in iter(d):
  187. l.append(i)
  188. self.assertEqual(l, l1)
  189. l = []
  190. for i in d.__iter__():
  191. l.append(i)
  192. self.assertEqual(l, l1)
  193. l = []
  194. for i in dict.__iter__(d):
  195. l.append(i)
  196. self.assertEqual(l, l1)
  197. d = {1:2, 3:4}
  198. self.unop_test(d, 2, "len(a)", "__len__")
  199. self.assertEqual(eval(repr(d), {}), d)
  200. self.assertEqual(eval(d.__repr__(), {}), d)
  201. self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
  202. "__setitem__")
  203. # Tests for unary and binary operators
  204. def number_operators(self, a, b, skip=[]):
  205. dict = {'a': a, 'b': b}
  206. for name, expr in self.binops.items():
  207. if name not in skip:
  208. name = "__%s__" % name
  209. if hasattr(a, name):
  210. res = eval(expr, dict)
  211. self.binop_test(a, b, res, expr, name)
  212. for name, expr in list(self.unops.items()):
  213. if name not in skip:
  214. name = "__%s__" % name
  215. if hasattr(a, name):
  216. res = eval(expr, dict)
  217. self.unop_test(a, res, expr, name)
  218. def test_ints(self):
  219. # Testing int operations...
  220. self.number_operators(100, 3)
  221. # The following crashes in Python 2.2
  222. self.assertEqual((1).__bool__(), 1)
  223. self.assertEqual((0).__bool__(), 0)
  224. # This returns 'NotImplemented' in Python 2.2
  225. class C(int):
  226. def __add__(self, other):
  227. return NotImplemented
  228. self.assertEqual(C(5), 5)
  229. try:
  230. C() + ""
  231. except TypeError:
  232. pass
  233. else:
  234. self.fail("NotImplemented should have caused TypeError")
  235. def test_floats(self):
  236. # Testing float operations...
  237. self.number_operators(100.0, 3.0)
  238. def test_complexes(self):
  239. # Testing complex operations...
  240. self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
  241. 'int', 'float',
  242. 'floordiv', 'divmod', 'mod'])
  243. class Number(complex):
  244. __slots__ = ['prec']
  245. def __new__(cls, *args, **kwds):
  246. result = complex.__new__(cls, *args)
  247. result.prec = kwds.get('prec', 12)
  248. return result
  249. def __repr__(self):
  250. prec = self.prec
  251. if self.imag == 0.0:
  252. return "%.*g" % (prec, self.real)
  253. if self.real == 0.0:
  254. return "%.*gj" % (prec, self.imag)
  255. return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
  256. __str__ = __repr__
  257. a = Number(3.14, prec=6)
  258. self.assertEqual(repr(a), "3.14")
  259. self.assertEqual(a.prec, 6)
  260. a = Number(a, prec=2)
  261. self.assertEqual(repr(a), "3.1")
  262. self.assertEqual(a.prec, 2)
  263. a = Number(234.5)
  264. self.assertEqual(repr(a), "234.5")
  265. self.assertEqual(a.prec, 12)
  266. def test_explicit_reverse_methods(self):
  267. # see issue 9930
  268. self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
  269. self.assertEqual(float.__rsub__(3.0, 1), -2.0)
  270. @support.impl_detail("the module 'xxsubtype' is internal")
  271. def test_spam_lists(self):
  272. # Testing spamlist operations...
  273. import copy, xxsubtype as spam
  274. def spamlist(l, memo=None):
  275. import xxsubtype as spam
  276. return spam.spamlist(l)
  277. # This is an ugly hack:
  278. copy._deepcopy_dispatch[spam.spamlist] = spamlist
  279. self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
  280. "__add__")
  281. self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
  282. self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
  283. self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
  284. self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
  285. "__getitem__")
  286. self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
  287. "__iadd__")
  288. self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
  289. "__imul__")
  290. self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
  291. self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
  292. "__mul__")
  293. self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
  294. "__rmul__")
  295. self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
  296. "__setitem__")
  297. self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
  298. spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
  299. # Test subclassing
  300. class C(spam.spamlist):
  301. def foo(self): return 1
  302. a = C()
  303. self.assertEqual(a, [])
  304. self.assertEqual(a.foo(), 1)
  305. a.append(100)
  306. self.assertEqual(a, [100])
  307. self.assertEqual(a.getstate(), 0)
  308. a.setstate(42)
  309. self.assertEqual(a.getstate(), 42)
  310. @support.impl_detail("the module 'xxsubtype' is internal")
  311. def test_spam_dicts(self):
  312. # Testing spamdict operations...
  313. import copy, xxsubtype as spam
  314. def spamdict(d, memo=None):
  315. import xxsubtype as spam
  316. sd = spam.spamdict()
  317. for k, v in list(d.items()):
  318. sd[k] = v
  319. return sd
  320. # This is an ugly hack:
  321. copy._deepcopy_dispatch[spam.spamdict] = spamdict
  322. self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
  323. self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
  324. self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
  325. d = spamdict({1:2,3:4})
  326. l1 = []
  327. for i in list(d.keys()):
  328. l1.append(i)
  329. l = []
  330. for i in iter(d):
  331. l.append(i)
  332. self.assertEqual(l, l1)
  333. l = []
  334. for i in d.__iter__():
  335. l.append(i)
  336. self.assertEqual(l, l1)
  337. l = []
  338. for i in type(spamdict({})).__iter__(d):
  339. l.append(i)
  340. self.assertEqual(l, l1)
  341. straightd = {1:2, 3:4}
  342. spamd = spamdict(straightd)
  343. self.unop_test(spamd, 2, "len(a)", "__len__")
  344. self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
  345. self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
  346. "a[b]=c", "__setitem__")
  347. # Test subclassing
  348. class C(spam.spamdict):
  349. def foo(self): return 1
  350. a = C()
  351. self.assertEqual(list(a.items()), [])
  352. self.assertEqual(a.foo(), 1)
  353. a['foo'] = 'bar'
  354. self.assertEqual(list(a.items()), [('foo', 'bar')])
  355. self.assertEqual(a.getstate(), 0)
  356. a.setstate(100)
  357. self.assertEqual(a.getstate(), 100)
  358. def test_wrap_lenfunc_bad_cast(self):
  359. self.assertEqual(range(sys.maxsize).__len__(), sys.maxsize)
  360. class ClassPropertiesAndMethods(unittest.TestCase):
  361. def assertHasAttr(self, obj, name):
  362. self.assertTrue(hasattr(obj, name),
  363. '%r has no attribute %r' % (obj, name))
  364. def assertNotHasAttr(self, obj, name):
  365. self.assertFalse(hasattr(obj, name),
  366. '%r has unexpected attribute %r' % (obj, name))
  367. def test_python_dicts(self):
  368. # Testing Python subclass of dict...
  369. self.assertTrue(issubclass(dict, dict))
  370. self.assertIsInstance({}, dict)
  371. d = dict()
  372. self.assertEqual(d, {})
  373. self.assertIs(d.__class__, dict)
  374. self.assertIsInstance(d, dict)
  375. class C(dict):
  376. state = -1
  377. def __init__(self_local, *a, **kw):
  378. if a:
  379. self.assertEqual(len(a), 1)
  380. self_local.state = a[0]
  381. if kw:
  382. for k, v in list(kw.items()):
  383. self_local[v] = k
  384. def __getitem__(self, key):
  385. return self.get(key, 0)
  386. def __setitem__(self_local, key, value):
  387. self.assertIsInstance(key, type(0))
  388. dict.__setitem__(self_local, key, value)
  389. def setstate(self, state):
  390. self.state = state
  391. def getstate(self):
  392. return self.state
  393. self.assertTrue(issubclass(C, dict))
  394. a1 = C(12)
  395. self.assertEqual(a1.state, 12)
  396. a2 = C(foo=1, bar=2)
  397. self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
  398. a = C()
  399. self.assertEqual(a.state, -1)
  400. self.assertEqual(a.getstate(), -1)
  401. a.setstate(0)
  402. self.assertEqual(a.state, 0)
  403. self.assertEqual(a.getstate(), 0)
  404. a.setstate(10)
  405. self.assertEqual(a.state, 10)
  406. self.assertEqual(a.getstate(), 10)
  407. self.assertEqual(a[42], 0)
  408. a[42] = 24
  409. self.assertEqual(a[42], 24)
  410. N = 50
  411. for i in range(N):
  412. a[i] = C()
  413. for j in range(N):
  414. a[i][j] = i*j
  415. for i in range(N):
  416. for j in range(N):
  417. self.assertEqual(a[i][j], i*j)
  418. def test_python_lists(self):
  419. # Testing Python subclass of list...
  420. class C(list):
  421. def __getitem__(self, i):
  422. if isinstance(i, slice):
  423. return i.start, i.stop
  424. return list.__getitem__(self, i) + 100
  425. a = C()
  426. a.extend([0,1,2])
  427. self.assertEqual(a[0], 100)
  428. self.assertEqual(a[1], 101)
  429. self.assertEqual(a[2], 102)
  430. self.assertEqual(a[100:200], (100,200))
  431. def test_metaclass(self):
  432. # Testing metaclasses...
  433. class C(metaclass=type):
  434. def __init__(self):
  435. self.__state = 0
  436. def getstate(self):
  437. return self.__state
  438. def setstate(self, state):
  439. self.__state = state
  440. a = C()
  441. self.assertEqual(a.getstate(), 0)
  442. a.setstate(10)
  443. self.assertEqual(a.getstate(), 10)
  444. class _metaclass(type):
  445. def myself(cls): return cls
  446. class D(metaclass=_metaclass):
  447. pass
  448. self.assertEqual(D.myself(), D)
  449. d = D()
  450. self.assertEqual(d.__class__, D)
  451. class M1(type):
  452. def __new__(cls, name, bases, dict):
  453. dict['__spam__'] = 1
  454. return type.__new__(cls, name, bases, dict)
  455. class C(metaclass=M1):
  456. pass
  457. self.assertEqual(C.__spam__, 1)
  458. c = C()
  459. self.assertEqual(c.__spam__, 1)
  460. class _instance(object):
  461. pass
  462. class M2(object):
  463. @staticmethod
  464. def __new__(cls, name, bases, dict):
  465. self = object.__new__(cls)
  466. self.name = name
  467. self.bases = bases
  468. self.dict = dict
  469. return self
  470. def __call__(self):
  471. it = _instance()
  472. # Early binding of methods
  473. for key in self.dict:
  474. if key.startswith("__"):
  475. continue
  476. setattr(it, key, self.dict[key].__get__(it, self))
  477. return it
  478. class C(metaclass=M2):
  479. def spam(self):
  480. return 42
  481. self.assertEqual(C.name, 'C')
  482. self.assertEqual(C.bases, ())
  483. self.assertIn('spam', C.dict)
  484. c = C()
  485. self.assertEqual(c.spam(), 42)
  486. # More metaclass examples
  487. class autosuper(type):
  488. # Automatically add __super to the class
  489. # This trick only works for dynamic classes
  490. def __new__(metaclass, name, bases, dict):
  491. cls = super(autosuper, metaclass).__new__(metaclass,
  492. name, bases, dict)
  493. # Name mangling for __super removes leading underscores
  494. while name[:1] == "_":
  495. name = name[1:]
  496. if name:
  497. name = "_%s__super" % name
  498. else:
  499. name = "__super"
  500. setattr(cls, name, super(cls))
  501. return cls
  502. class A(metaclass=autosuper):
  503. def meth(self):
  504. return "A"
  505. class B(A):
  506. def meth(self):
  507. return "B" + self.__super.meth()
  508. class C(A):
  509. def meth(self):
  510. return "C" + self.__super.meth()
  511. class D(C, B):
  512. def meth(self):
  513. return "D" + self.__super.meth()
  514. self.assertEqual(D().meth(), "DCBA")
  515. class E(B, C):
  516. def meth(self):
  517. return "E" + self.__super.meth()
  518. self.assertEqual(E().meth(), "EBCA")
  519. class autoproperty(type):
  520. # Automatically create property attributes when methods
  521. # named _get_x and/or _set_x are found
  522. def __new__(metaclass, name, bases, dict):
  523. hits = {}
  524. for key, val in dict.items():
  525. if key.startswith("_get_"):
  526. key = key[5:]
  527. get, set = hits.get(key, (None, None))
  528. get = val
  529. hits[key] = get, set
  530. elif key.startswith("_set_"):
  531. key = key[5:]
  532. get, set = hits.get(key, (None, None))
  533. set = val
  534. hits[key] = get, set
  535. for key, (get, set) in hits.items():
  536. dict[key] = property(get, set)
  537. return super(autoproperty, metaclass).__new__(metaclass,
  538. name, bases, dict)
  539. class A(metaclass=autoproperty):
  540. def _get_x(self):
  541. return -self.__x
  542. def _set_x(self, x):
  543. self.__x = -x
  544. a = A()
  545. self.assertNotHasAttr(a, "x")
  546. a.x = 12
  547. self.assertEqual(a.x, 12)
  548. self.assertEqual(a._A__x, -12)
  549. class multimetaclass(autoproperty, autosuper):
  550. # Merge of multiple cooperating metaclasses
  551. pass
  552. class A(metaclass=multimetaclass):
  553. def _get_x(self):
  554. return "A"
  555. class B(A):
  556. def _get_x(self):
  557. return "B" + self.__super._get_x()
  558. class C(A):
  559. def _get_x(self):
  560. return "C" + self.__super._get_x()
  561. class D(C, B):
  562. def _get_x(self):
  563. return "D" + self.__super._get_x()
  564. self.assertEqual(D().x, "DCBA")
  565. # Make sure type(x) doesn't call x.__class__.__init__
  566. class T(type):
  567. counter = 0
  568. def __init__(self, *args):
  569. T.counter += 1
  570. class C(metaclass=T):
  571. pass
  572. self.assertEqual(T.counter, 1)
  573. a = C()
  574. self.assertEqual(type(a), C)
  575. self.assertEqual(T.counter, 1)
  576. class C(object): pass
  577. c = C()
  578. try: c()
  579. except TypeError: pass
  580. else: self.fail("calling object w/o call method should raise "
  581. "TypeError")
  582. # Testing code to find most derived baseclass
  583. class A(type):
  584. def __new__(*args, **kwargs):
  585. return type.__new__(*args, **kwargs)
  586. class B(object):
  587. pass
  588. class C(object, metaclass=A):
  589. pass
  590. # The most derived metaclass of D is A rather than type.
  591. class D(B, C):
  592. pass
  593. self.assertIs(A, type(D))
  594. # issue1294232: correct metaclass calculation
  595. new_calls = [] # to check the order of __new__ calls
  596. class AMeta(type):
  597. @staticmethod
  598. def __new__(mcls, name, bases, ns):
  599. new_calls.append('AMeta')
  600. return super().__new__(mcls, name, bases, ns)
  601. @classmethod
  602. def __prepare__(mcls, name, bases):
  603. return {}
  604. class BMeta(AMeta):
  605. @staticmethod
  606. def __new__(mcls, name, bases, ns):
  607. new_calls.append('BMeta')
  608. return super().__new__(mcls, name, bases, ns)
  609. @classmethod
  610. def __prepare__(mcls, name, bases):
  611. ns = super().__prepare__(name, bases)
  612. ns['BMeta_was_here'] = True
  613. return ns
  614. class A(metaclass=AMeta):
  615. pass
  616. self.assertEqual(['AMeta'], new_calls)
  617. new_calls.clear()
  618. class B(metaclass=BMeta):
  619. pass
  620. # BMeta.__new__ calls AMeta.__new__ with super:
  621. self.assertEqual(['BMeta', 'AMeta'], new_calls)
  622. new_calls.clear()
  623. class C(A, B):
  624. pass
  625. # The most derived metaclass is BMeta:
  626. self.assertEqual(['BMeta', 'AMeta'], new_calls)
  627. new_calls.clear()
  628. # BMeta.__prepare__ should've been called:
  629. self.assertIn('BMeta_was_here', C.__dict__)
  630. # The order of the bases shouldn't matter:
  631. class C2(B, A):
  632. pass
  633. self.assertEqual(['BMeta', 'AMeta'], new_calls)
  634. new_calls.clear()
  635. self.assertIn('BMeta_was_here', C2.__dict__)
  636. # Check correct metaclass calculation when a metaclass is declared:
  637. class D(C, metaclass=type):
  638. pass
  639. self.assertEqual(['BMeta', 'AMeta'], new_calls)
  640. new_calls.clear()
  641. self.assertIn('BMeta_was_here', D.__dict__)
  642. class E(C, metaclass=AMeta):
  643. pass
  644. self.assertEqual(['BMeta', 'AMeta'], new_calls)
  645. new_calls.clear()
  646. self.assertIn('BMeta_was_here', E.__dict__)
  647. # Special case: the given metaclass isn't a class,
  648. # so there is no metaclass calculation.
  649. marker = object()
  650. def func(*args, **kwargs):
  651. return marker
  652. class X(metaclass=func):
  653. pass
  654. class Y(object, metaclass=func):
  655. pass
  656. class Z(D, metaclass=func):
  657. pass
  658. self.assertIs(marker, X)
  659. self.assertIs(marker, Y)
  660. self.assertIs(marker, Z)
  661. # The given metaclass is a class,
  662. # but not a descendant of type.
  663. prepare_calls = [] # to track __prepare__ calls
  664. class ANotMeta:
  665. def __new__(mcls, *args, **kwargs):
  666. new_calls.append('ANotMeta')
  667. return super().__new__(mcls)
  668. @classmethod
  669. def __prepare__(mcls, name, bases):
  670. prepare_calls.append('ANotMeta')
  671. return {}
  672. class BNotMeta(ANotMeta):
  673. def __new__(mcls, *args, **kwargs):
  674. new_calls.append('BNotMeta')
  675. return super().__new__(mcls)
  676. @classmethod
  677. def __prepare__(mcls, name, bases):
  678. prepare_calls.append('BNotMeta')
  679. return super().__prepare__(name, bases)
  680. class A(metaclass=ANotMeta):
  681. pass
  682. self.assertIs(ANotMeta, type(A))
  683. self.assertEqual(['ANotMeta'], prepare_calls)
  684. prepare_calls.clear()
  685. self.assertEqual(['ANotMeta'], new_calls)
  686. new_calls.clear()
  687. class B(metaclass=BNotMeta):
  688. pass
  689. self.assertIs(BNotMeta, type(B))
  690. self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
  691. prepare_calls.clear()
  692. self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
  693. new_calls.clear()
  694. class C(A, B):
  695. pass
  696. self.assertIs(BNotMeta, type(C))
  697. self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
  698. new_calls.clear()
  699. self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
  700. prepare_calls.clear()
  701. class C2(B, A):
  702. pass
  703. self.assertIs(BNotMeta, type(C2))
  704. self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
  705. new_calls.clear()
  706. self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
  707. prepare_calls.clear()
  708. # This is a TypeError, because of a metaclass conflict:
  709. # BNotMeta is neither a subclass, nor a superclass of type
  710. with self.assertRaises(TypeError):
  711. class D(C, metaclass=type):
  712. pass
  713. class E(C, metaclass=ANotMeta):
  714. pass
  715. self.assertIs(BNotMeta, type(E))
  716. self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
  717. new_calls.clear()
  718. self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
  719. prepare_calls.clear()
  720. class F(object(), C):
  721. pass
  722. self.assertIs(BNotMeta, type(F))
  723. self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
  724. new_calls.clear()
  725. self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
  726. prepare_calls.clear()
  727. class F2(C, object()):
  728. pass
  729. self.assertIs(BNotMeta, type(F2))
  730. self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
  731. new_calls.clear()
  732. self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
  733. prepare_calls.clear()
  734. # TypeError: BNotMeta is neither a
  735. # subclass, nor a superclass of int
  736. with self.assertRaises(TypeError):
  737. class X(C, int()):
  738. pass
  739. with self.assertRaises(TypeError):
  740. class X(int(), C):
  741. pass
  742. def test_module_subclasses(self):
  743. # Testing Python subclass of module...
  744. log = []
  745. MT = type(sys)
  746. class MM(MT):
  747. def __init__(self, name):
  748. MT.__init__(self, name)
  749. def __getattribute__(self, name):
  750. log.append(("getattr", name))
  751. return MT.__getattribute__(self, name)
  752. def __setattr__(self, name, value):
  753. log.append(("setattr", name, value))
  754. MT.__setattr__(self, name, value)
  755. def __delattr__(self, name):
  756. log.append(("delattr", name))
  757. MT.__delattr__(self, name)
  758. a = MM("a")
  759. a.foo = 12
  760. x = a.foo
  761. del a.foo
  762. self.assertEqual(log, [("setattr", "foo", 12),
  763. ("getattr", "foo"),
  764. ("delattr", "foo")])
  765. # http://python.org/sf/1174712
  766. try:
  767. class Module(types.ModuleType, str):
  768. pass
  769. except TypeError:
  770. pass
  771. else:
  772. self.fail("inheriting from ModuleType and str at the same time "
  773. "should fail")
  774. # Issue 34805: Verify that definition order is retained
  775. def random_name():
  776. return ''.join(random.choices(string.ascii_letters, k=10))
  777. class A:
  778. pass
  779. subclasses = [type(random_name(), (A,), {}) for i in range(100)]
  780. self.assertEqual(A.__subclasses__(), subclasses)
  781. def test_multiple_inheritance(self):
  782. # Testing multiple inheritance...
  783. class C(object):
  784. def __init__(self):
  785. self.__state = 0
  786. def getstate(self):
  787. return self.__state
  788. def setstate(self, state):
  789. self.__state = state
  790. a = C()
  791. self.assertEqual(a.getstate(), 0)
  792. a.setstate(10)
  793. self.assertEqual(a.getstate(), 10)
  794. class D(dict, C):
  795. def __init__(self):
  796. type({}).__init__(self)
  797. C.__init__(self)
  798. d = D()
  799. self.assertEqual(list(d.keys()), [])
  800. d["hello"] = "world"
  801. self.assertEqual(list(d.items()), [("hello", "world")])
  802. self.assertEqual(d["hello"], "world")
  803. self.assertEqual(d.getstate(), 0)
  804. d.setstate(10)
  805. self.assertEqual(d.getstate(), 10)
  806. self.assertEqual(D.__mro__, (D, dict, C, object))
  807. # SF bug #442833
  808. class Node(object):
  809. def __int__(self):
  810. return int(self.foo())
  811. def foo(self):
  812. return "23"
  813. class Frag(Node, list):
  814. def foo(self):
  815. return "42"
  816. self.assertEqual(Node().__int__(), 23)
  817. self.assertEqual(int(Node()), 23)
  818. self.assertEqual(Frag().__int__(), 42)
  819. self.assertEqual(int(Frag()), 42)
  820. def test_diamond_inheritance(self):
  821. # Testing multiple inheritance special cases...
  822. class A(object):
  823. def spam(self): return "A"
  824. self.assertEqual(A().spam(), "A")
  825. class B(A):
  826. def boo(self): return "B"
  827. def spam(self): return "B"
  828. self.assertEqual(B().spam(), "B")
  829. self.assertEqual(B().boo(), "B")
  830. class C(A):
  831. def boo(self): return "C"
  832. self.assertEqual(C().spam(), "A")
  833. self.assertEqual(C().boo(), "C")
  834. class D(B, C): pass
  835. self.assertEqual(D().spam(), "B")
  836. self.assertEqual(D().boo(), "B")
  837. self.assertEqual(D.__mro__, (D, B, C, A, object))
  838. class E(C, B): pass
  839. self.assertEqual(E().spam(), "B")
  840. self.assertEqual(E().boo(), "C")
  841. self.assertEqual(E.__mro__, (E, C, B, A, object))
  842. # MRO order disagreement
  843. try:
  844. class F(D, E): pass
  845. except TypeError:
  846. pass
  847. else:
  848. self.fail("expected MRO order disagreement (F)")
  849. try:
  850. class G(E, D): pass
  851. except TypeError:
  852. pass
  853. else:
  854. self.fail("expected MRO order disagreement (G)")
  855. # see thread python-dev/2002-October/029035.html
  856. def test_ex5_from_c3_switch(self):
  857. # Testing ex5 from C3 switch discussion...
  858. class A(object): pass
  859. class B(object): pass
  860. class C(object): pass
  861. class X(A): pass
  862. class Y(A): pass
  863. class Z(X,B,Y,C): pass
  864. self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
  865. # see "A Monotonic Superclass Linearization for Dylan",
  866. # by Kim Barrett et al. (OOPSLA 1996)
  867. def test_monotonicity(self):
  868. # Testing MRO monotonicity...
  869. class Boat(object): pass
  870. class DayBoat(Boat): pass
  871. class WheelBoat(Boat): pass
  872. class EngineLess(DayBoat): pass
  873. class SmallMultihull(DayBoat): pass
  874. class PedalWheelBoat(EngineLess,WheelBoat): pass
  875. class SmallCatamaran(SmallMultihull): pass
  876. class Pedalo(PedalWheelBoat,SmallCatamaran): pass
  877. self.assertEqual(PedalWheelBoat.__mro__,
  878. (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
  879. self.assertEqual(SmallCatamaran.__mro__,
  880. (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
  881. self.assertEqual(Pedalo.__mro__,
  882. (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
  883. SmallMultihull, DayBoat, WheelBoat, Boat, object))
  884. # see "A Monotonic Superclass Linearization for Dylan",
  885. # by Kim Barrett et al. (OOPSLA 1996)
  886. def test_consistency_with_epg(self):
  887. # Testing consistency with EPG...
  888. class Pane(object): pass
  889. class ScrollingMixin(object): pass
  890. class EditingMixin(object): pass
  891. class ScrollablePane(Pane,ScrollingMixin): pass
  892. class EditablePane(Pane,EditingMixin): pass
  893. class EditableScrollablePane(ScrollablePane,EditablePane): pass
  894. self.assertEqual(EditableScrollablePane.__mro__,
  895. (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
  896. ScrollingMixin, EditingMixin, object))
  897. def test_mro_disagreement(self):
  898. # Testing error messages for MRO disagreement...
  899. mro_err_msg = """Cannot create a consistent method resolution
  900. order (MRO) for bases """
  901. def raises(exc, expected, callable, *args):
  902. try:
  903. callable(*args)
  904. except exc as msg:
  905. # the exact msg is generally considered an impl detail
  906. if support.check_impl_detail():
  907. if not str(msg).startswith(expected):
  908. self.fail("Message %r, expected %r" %
  909. (str(msg), expected))
  910. else:
  911. self.fail("Expected %s" % exc)
  912. class A(object): pass
  913. class B(A): pass
  914. class C(object): pass
  915. # Test some very simple errors
  916. raises(TypeError, "duplicate base class A",
  917. type, "X", (A, A), {})
  918. raises(TypeError, mro_err_msg,
  919. type, "X", (A, B), {})
  920. raises(TypeError, mro_err_msg,
  921. type, "X", (A, C, B), {})
  922. # Test a slightly more complex error
  923. class GridLayout(object): pass
  924. class HorizontalGrid(GridLayout): pass
  925. class VerticalGrid(GridLayout): pass
  926. class HVGrid(HorizontalGrid, VerticalGrid): pass
  927. class VHGrid(VerticalGrid, HorizontalGrid): pass
  928. raises(TypeError, mro_err_msg,
  929. type, "ConfusedGrid", (HVGrid, VHGrid), {})
  930. def test_object_class(self):
  931. # Testing object class...
  932. a = object()
  933. self.assertEqual(a.__class__, object)
  934. self.assertEqual(type(a), object)
  935. b = object()
  936. self.assertNotEqual(a, b)
  937. self.assertNotHasAttr(a, "foo")
  938. try:
  939. a.foo = 12
  940. except (AttributeError, TypeError):
  941. pass
  942. else:
  943. self.fail("object() should not allow setting a foo attribute")
  944. self.assertNotHasAttr(object(), "__dict__")
  945. class Cdict(object):
  946. pass
  947. x = Cdict()
  948. self.assertEqual(x.__dict__, {})
  949. x.foo = 1
  950. self.assertEqual(x.foo, 1)
  951. self.assertEqual(x.__dict__, {'foo': 1})
  952. def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
  953. class SubType(types.ModuleType):
  954. a = 1
  955. m = types.ModuleType("m")
  956. self.assertTrue(m.__class__ is types.ModuleType)
  957. self.assertFalse(hasattr(m, "a"))
  958. m.__class__ = SubType
  959. self.assertTrue(m.__class__ is SubType)
  960. self.assertTrue(hasattr(m, "a"))
  961. m.__class__ = types.ModuleType
  962. self.assertTrue(m.__class__ is types.ModuleType)
  963. self.assertFalse(hasattr(m, "a"))
  964. # Make sure that builtin immutable objects don't support __class__
  965. # assignment, because the object instances may be interned.
  966. # We set __slots__ = () to ensure that the subclasses are
  967. # memory-layout compatible, and thus otherwise reasonable candidates
  968. # for __class__ assignment.
  969. # The following types have immutable instances, but are not
  970. # subclassable and thus don't need to be checked:
  971. # NoneType, bool
  972. class MyInt(int):
  973. __slots__ = ()
  974. with self.assertRaises(TypeError):
  975. (1).__class__ = MyInt
  976. class MyFloat(float):
  977. __slots__ = ()
  978. with self.assertRaises(TypeError):
  979. (1.0).__class__ = MyFloat
  980. class MyComplex(complex):
  981. __slots__ = ()
  982. with self.assertRaises(TypeError):
  983. (1 + 2j).__class__ = MyComplex
  984. class MyStr(str):
  985. __slots__ = ()
  986. with self.assertRaises(TypeError):
  987. "a".__class__ = MyStr
  988. class MyBytes(bytes):
  989. __slots__ = ()
  990. with self.assertRaises(TypeError):
  991. b"a".__class__ = MyBytes
  992. class MyTuple(tuple):
  993. __slots__ = ()
  994. with self.assertRaises(TypeError):
  995. ().__class__ = MyTuple
  996. class MyFrozenSet(frozenset):
  997. __slots__ = ()
  998. with self.assertRaises(TypeError):
  999. frozenset().__class__ = MyFrozenSet
  1000. def test_slots(self):
  1001. # Testing __slots__...
  1002. class C0(object):
  1003. __slots__ = []
  1004. x = C0()
  1005. self.assertNotHasAttr(x, "__dict__")
  1006. self.assertNotHasAttr(x, "foo")
  1007. class C1(object):
  1008. __slots__ = ['a']
  1009. x = C1()
  1010. self.assertNotHasAttr(x, "__dict__")
  1011. self.assertNotHasAttr(x, "a")
  1012. x.a = 1
  1013. self.assertEqual(x.a, 1)
  1014. x.a = None
  1015. self.assertEqual(x.a, None)
  1016. del x.a
  1017. self.assertNotHasAttr(x, "a")
  1018. class C3(object):
  1019. __slots__ = ['a', 'b', 'c']
  1020. x = C3()
  1021. self.assertNotHasAttr(x, "__dict__")
  1022. self.assertNotHasAttr(x, 'a')
  1023. self.assertNotHasAttr(x, 'b')
  1024. self.assertNotHasAttr(x, 'c')
  1025. x.a = 1
  1026. x.b = 2
  1027. x.c = 3
  1028. self.assertEqual(x.a, 1)
  1029. self.assertEqual(x.b, 2)
  1030. self.assertEqual(x.c, 3)
  1031. class C4(object):
  1032. """Validate name mangling"""
  1033. __slots__ = ['__a']
  1034. def __init__(self, value):
  1035. self.__a = value
  1036. def get(self):
  1037. return self.__a
  1038. x = C4(5)
  1039. self.assertNotHasAttr(x, '__dict__')
  1040. self.assertNotHasAttr(x, '__a')
  1041. self.assertEqual(x.get(), 5)
  1042. try:
  1043. x.__a = 6
  1044. except AttributeError:
  1045. pass
  1046. else:
  1047. self.fail("Double underscored names not mangled")
  1048. # Make sure slot names are proper identifiers
  1049. try:
  1050. class C(object):
  1051. __slots__ = [None]
  1052. except TypeError:
  1053. pass
  1054. else:
  1055. self.fail("[None] slots not caught")
  1056. try:
  1057. class C(object):
  1058. __slots__ = ["foo bar"]
  1059. except TypeError:
  1060. pass
  1061. else:
  1062. self.fail("['foo bar'] slots not caught")
  1063. try:
  1064. class C(object):
  1065. __slots__ = ["foo\0bar"]
  1066. except TypeError:
  1067. pass
  1068. else:
  1069. self.fail("['foo\\0bar'] slots not caught")
  1070. try:
  1071. class C(object):
  1072. __slots__ = ["1"]
  1073. except TypeError:
  1074. pass
  1075. else:
  1076. self.fail("['1'] slots not caught")
  1077. try:
  1078. class C(object):
  1079. __slots__ = [""]
  1080. except TypeError:
  1081. pass
  1082. else:
  1083. self.fail("[''] slots not caught")
  1084. class C(object):
  1085. __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
  1086. # XXX(nnorwitz): was there supposed to be something tested
  1087. # from the class above?
  1088. # Test a single string is not expanded as a sequence.
  1089. class C(object):
  1090. __slots__ = "abc"
  1091. c = C()
  1092. c.abc = 5
  1093. self.assertEqual(c.abc, 5)
  1094. # Test unicode slot names
  1095. # Test a single unicode string is not expanded as a sequence.
  1096. class C(object):
  1097. __slots__ = "abc"
  1098. c = C()
  1099. c.abc = 5
  1100. self.assertEqual(c.abc, 5)
  1101. # _unicode_to_string used to modify slots in certain circumstances
  1102. slots = ("foo", "bar")
  1103. class C(object):
  1104. __slots__ = slots
  1105. x = C()
  1106. x.foo = 5
  1107. self.assertEqual(x.foo, 5)
  1108. self.assertIs(type(slots[0]), str)
  1109. # this used to leak references
  1110. try:
  1111. class C(object):
  1112. __slots__ = [chr(128)]
  1113. except (TypeError, UnicodeEncodeError):
  1114. pass
  1115. else:
  1116. self.fail("[chr(128)] slots not caught")
  1117. # Test leaks
  1118. class Counted(object):
  1119. counter = 0 # counts the number of instances alive
  1120. def __init__(self):
  1121. Counted.counter += 1
  1122. def __del__(self):
  1123. Counted.counter -= 1
  1124. class C(object):
  1125. __slots__ = ['a', 'b', 'c']
  1126. x = C()
  1127. x.a = Counted()
  1128. x.b = Counted()
  1129. x.c = Counted()
  1130. self.assertEqual(Counted.counter, 3)
  1131. del x
  1132. support.gc_collect()
  1133. self.assertEqual(Counted.counter, 0)
  1134. class D(C):
  1135. pass
  1136. x = D()
  1137. x.a = Counted()
  1138. x.z = Counted()
  1139. self.assertEqual(Counted.counter, 2)
  1140. del x
  1141. support.gc_collect()
  1142. self.assertEqual(Counted.counter, 0)
  1143. class E(D):
  1144. __slots__ = ['e']
  1145. x = E()
  1146. x.a = Counted()
  1147. x.z = Counted()
  1148. x.e = Counted()
  1149. self.assertEqual(Counted.counter, 3)
  1150. del x
  1151. support.gc_collect()
  1152. self.assertEqual(Counted.counter, 0)
  1153. # Test cyclical leaks [SF bug 519621]
  1154. class F(object):
  1155. __slots__ = ['a', 'b']
  1156. s = F()
  1157. s.a = [Counted(), s]
  1158. self.assertEqual(Counted.counter, 1)
  1159. s = None
  1160. support.gc_collect()
  1161. self.assertEqual(Counted.counter, 0)
  1162. # Test lookup leaks [SF bug 572567]
  1163. if hasattr(gc, 'get_objects'):
  1164. class G(object):
  1165. def __eq__(self, other):
  1166. return False
  1167. g = G()
  1168. orig_objects = len(gc.get_objects())
  1169. for i in range(10):
  1170. g==g
  1171. new_objects = len(gc.get_objects())
  1172. self.assertEqual(orig_objects, new_objects)
  1173. class H(object):
  1174. __slots__ = ['a', 'b']
  1175. def __init__(self):
  1176. self.a = 1
  1177. self.b = 2
  1178. def __del__(self_):
  1179. self.assertEqual(self_.a, 1)
  1180. self.assertEqual(self_.b, 2)
  1181. with support.captured_output('stderr') as s:
  1182. h = H()
  1183. del h
  1184. self.assertEqual(s.getvalue(), '')
  1185. class X(object):
  1186. __slots__ = "a"
  1187. with self.assertRaises(AttributeError):
  1188. del X().a
  1189. # Inherit from object on purpose to check some backwards compatibility paths
  1190. class X(object):
  1191. __slots__ = "a"
  1192. with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"):
  1193. X().a
  1194. # Test string subclass in `__slots__`, see gh-98783
  1195. class SubStr(str):
  1196. pass
  1197. class X(object):
  1198. __slots__ = (SubStr('x'),)
  1199. X().x = 1
  1200. with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"):
  1201. X().a
  1202. def test_slots_special(self):
  1203. # Testing __dict__ and __weakref__ in __slots__...
  1204. class D(object):
  1205. __slots__ = ["__dict__"]
  1206. a = D()
  1207. self.assertHasAttr(a, "__dict__")
  1208. self.assertNotHasAttr(a, "__weakref__")
  1209. a.foo = 42
  1210. self.assertEqual(a.__dict__, {"foo": 42})
  1211. class W(object):
  1212. __slots__ = ["__weakref__"]
  1213. a = W()
  1214. self.assertHasAttr(a, "__weakref__")
  1215. self.assertNotHasAttr(a, "__dict__")
  1216. try:
  1217. a.foo = 42
  1218. except AttributeError:
  1219. pass
  1220. else:
  1221. self.fail("shouldn't be allowed to set a.foo")
  1222. class C1(W, D):
  1223. __slots__ = []
  1224. a = C1()
  1225. self.assertHasAttr(a, "__dict__")
  1226. self.assertHasAttr(a, "__weakref__")
  1227. a.foo = 42
  1228. self.assertEqual(a.__dict__, {"foo": 42})
  1229. class C2(D, W):
  1230. __slots__ = []
  1231. a = C2()
  1232. self.assertHasAttr(a, "__dict__")
  1233. self.assertHasAttr(a, "__weakref__")
  1234. a.foo = 42
  1235. self.assertEqual(a.__dict__, {"foo": 42})
  1236. def test_slots_special2(self):
  1237. # Testing __qualname__ and __classcell__ in __slots__
  1238. class Meta(type):
  1239. def __new__(cls, name, bases, namespace, attr):
  1240. self.assertIn(attr, namespace)
  1241. return super().__new__(cls, name, bases, namespace)
  1242. class C1:
  1243. def __init__(self):
  1244. self.b = 42
  1245. class C2(C1, metaclass=Meta, attr="__classcell__"):
  1246. __slots__ = ["__classcell__"]
  1247. def __init__(self):
  1248. super().__init__()
  1249. self.assertIsInstance(C2.__dict__["__classcell__"],
  1250. types.MemberDescriptorType)
  1251. c = C2()
  1252. self.assertEqual(c.b, 42)
  1253. self.assertNotHasAttr(c, "__classcell__")
  1254. c.__classcell__ = 42
  1255. self.assertEqual(c.__classcell__, 42)
  1256. with self.assertRaises(TypeError):
  1257. class C3:
  1258. __classcell__ = 42
  1259. __slots__ = ["__classcell__"]
  1260. class Q1(metaclass=Meta, attr="__qualname__"):
  1261. __slots__ = ["__qualname__"]
  1262. self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
  1263. self.assertIsInstance(Q1.__dict__["__qualname__"],
  1264. types.MemberDescriptorType)
  1265. q = Q1()
  1266. self.assertNotHasAttr(q, "__qualname__")
  1267. q.__qualname__ = "q"
  1268. self.assertEqual(q.__qualname__, "q")
  1269. with self.assertRaises(TypeError):
  1270. class Q2:
  1271. __qualname__ = object()
  1272. __slots__ = ["__qualname__"]
  1273. def test_slots_descriptor(self):
  1274. # Issue2115: slot descriptors did not correctly check
  1275. # the type of the given object
  1276. import abc
  1277. class MyABC(metaclass=abc.ABCMeta):
  1278. __slots__ = "a"
  1279. class Unrelated(object):
  1280. pass
  1281. MyABC.register(Unrelated)
  1282. u = Unrelated()
  1283. self.assertIsInstance(u, MyABC)
  1284. # This used to crash
  1285. self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
  1286. def test_dynamics(self):
  1287. # Testing class attribute propagation...
  1288. class D(object):
  1289. pass
  1290. class E(D):
  1291. pass
  1292. class F(D):
  1293. pass
  1294. D.foo = 1
  1295. self.assertEqual(D.foo, 1)
  1296. # Test that dynamic attributes are inherited
  1297. self.assertEqual(E.foo, 1)
  1298. self.assertEqual(F.foo, 1)
  1299. # Test dynamic instances
  1300. class C(object):
  1301. pass
  1302. a = C()
  1303. self.assertNotHasAttr(a, "foobar")
  1304. C.foobar = 2
  1305. self.assertEqual(a.foobar, 2)
  1306. C.method = lambda self: 42
  1307. self.assertEqual(a.method(), 42)
  1308. C.__repr__ = lambda self: "C()"
  1309. self.assertEqual(repr(a), "C()")
  1310. C.__int__ = lambda self: 100
  1311. self.assertEqual(int(a), 100)
  1312. self.assertEqual(a.foobar, 2)
  1313. self.assertNotHasAttr(a, "spam")
  1314. def mygetattr(self, name):
  1315. if name == "spam":
  1316. return "spam"
  1317. raise AttributeError
  1318. C.__getattr__ = mygetattr
  1319. self.assertEqual(a.spam, "spam")
  1320. a.new = 12
  1321. self.assertEqual(a.new, 12)
  1322. def mysetattr(self, name, value):
  1323. if name == "spam":
  1324. raise AttributeError
  1325. return object.__setattr__(self, name, value)
  1326. C.__setattr__ = mysetattr
  1327. with self.assertRaises(AttributeError):
  1328. a.spam = "not spam"
  1329. self.assertEqual(a.spam, "spam")
  1330. class D(C):
  1331. pass
  1332. d = D()
  1333. d.foo = 1
  1334. self.assertEqual(d.foo, 1)
  1335. # Test handling of int*seq and seq*int
  1336. class I(int):
  1337. pass
  1338. self.assertEqual("a"*I(2), "aa")
  1339. self.assertEqual(I(2)*"a", "aa")
  1340. self.assertEqual(2*I(3), 6)
  1341. self.assertEqual(I(3)*2, 6)
  1342. self.assertEqual(I(3)*I(2), 6)
  1343. # Test comparison of classes with dynamic metaclasses
  1344. class dynamicmetaclass(type):
  1345. pass
  1346. class someclass(metaclass=dynamicmetaclass):
  1347. pass
  1348. self.assertNotEqual(someclass, object)
  1349. def test_errors(self):
  1350. # Testing errors...
  1351. try:
  1352. class C(list, dict):
  1353. pass
  1354. except TypeError:
  1355. pass
  1356. else:
  1357. self.fail("inheritance from both list and dict should be illegal")
  1358. try:
  1359. class C(object, None):
  1360. pass
  1361. except TypeError:
  1362. pass
  1363. else:
  1364. self.fail("inheritance from non-type should be illegal")
  1365. class Classic:
  1366. pass
  1367. try:
  1368. class C(type(len)):
  1369. pass
  1370. except TypeError:
  1371. pass
  1372. else:
  1373. self.fail("inheritance from CFunction should be illegal")
  1374. try:
  1375. class C(object):
  1376. __slots__ = 1
  1377. except TypeError:
  1378. pass
  1379. else:
  1380. self.fail("__slots__ = 1 should be illegal")
  1381. try:
  1382. class C(object):
  1383. __slots__ = [1]
  1384. except TypeError:
  1385. pass
  1386. else:
  1387. self.fail("__slots__ = [1] should be illegal")
  1388. class M1(type):
  1389. pass
  1390. class M2(type):
  1391. pass
  1392. class A1(object, metaclass=M1):
  1393. pass
  1394. class A2(object, metaclass=M2):
  1395. pass
  1396. try:
  1397. class B(A1, A2):
  1398. pass
  1399. except TypeError:
  1400. pass
  1401. else:
  1402. self.fail("finding the most derived metaclass should have failed")
  1403. def test_classmethods(self):
  1404. # Testing class methods...
  1405. class C(object):
  1406. def foo(*a): return a
  1407. goo = classmethod(foo)
  1408. c = C()
  1409. self.assertEqual(C.goo(1), (C, 1))
  1410. self.assertEqual(c.goo(1), (C, 1))
  1411. self.assertEqual(c.foo(1), (c, 1))
  1412. class D(C):
  1413. pass
  1414. d = D()
  1415. self.assertEqual(D.goo(1), (D, 1))
  1416. self.assertEqual(d.goo(1), (D, 1))
  1417. self.assertEqual(d.foo(1), (d, 1))
  1418. self.assertEqual(D.foo(d, 1), (d, 1))
  1419. # Test for a specific crash (SF bug 528132)
  1420. def f(cls, arg):
  1421. "f docstring"
  1422. return (cls, arg)
  1423. ff = classmethod(f)
  1424. self.assertEqual(ff.__get__(0, int)(42), (int, 42))
  1425. self.assertEqual(ff.__get__(0)(42), (int, 42))
  1426. # Test super() with classmethods (SF bug 535444)
  1427. self.assertEqual(C.goo.__self__, C)
  1428. self.assertEqual(D.goo.__self__, D)
  1429. self.assertEqual(super(D,D).goo.__self__, D)
  1430. self.assertEqual(super(D,d).goo.__self__, D)
  1431. self.assertEqual(super(D,D).goo(), (D,))
  1432. self.assertEqual(super(D,d).goo(), (D,))
  1433. # Verify that a non-callable will raise
  1434. meth = classmethod(1).__get__(1)
  1435. self.assertRaises(TypeError, meth)
  1436. # Verify that classmethod() doesn't allow keyword args
  1437. try:
  1438. classmethod(f, kw=1)
  1439. except TypeError:
  1440. pass
  1441. else:
  1442. self.fail("classmethod shouldn't accept keyword args")
  1443. cm = classmethod(f)
  1444. cm_dict = {'__annotations__': {},
  1445. '__doc__': "f docstring",
  1446. '__module__': __name__,
  1447. '__name__': 'f',
  1448. '__qualname__': f.__qualname__}
  1449. self.assertEqual(cm.__dict__, cm_dict)
  1450. cm.x = 42
  1451. self.assertEqual(cm.x, 42)
  1452. self.assertEqual(cm.__dict__, {"x" : 42, **cm_dict})
  1453. del cm.x
  1454. self.assertNotHasAttr(cm, "x")
  1455. @support.refcount_test
  1456. def test_refleaks_in_classmethod___init__(self):
  1457. gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
  1458. cm = classmethod(None)
  1459. refs_before = gettotalrefcount()
  1460. for i in range(100):
  1461. cm.__init__(None)
  1462. self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
  1463. @support.impl_detail("the module 'xxsubtype' is internal")
  1464. def test_classmethods_in_c(self):
  1465. # Testing C-based class methods...
  1466. import xxsubtype as spam
  1467. a = (1, 2, 3)
  1468. d = {'abc': 123}
  1469. x, a1, d1 = spam.spamlist.classmeth(*a, **d)
  1470. self.assertEqual(x, spam.spamlist)
  1471. self.assertEqual(a, a1)
  1472. self.assertEqual(d, d1)
  1473. x, a1, d1 = spam.spamlist().classmeth(*a, **d)
  1474. self.assertEqual(x, spam.spamlist)
  1475. self.assertEqual(a, a1)
  1476. self.assertEqual(d, d1)
  1477. spam_cm = spam.spamlist.__dict__['classmeth']
  1478. x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
  1479. self.assertEqual(x2, spam.spamlist)
  1480. self.assertEqual(a2, a1)
  1481. self.assertEqual(d2, d1)
  1482. class SubSpam(spam.spamlist): pass
  1483. x2, a2, d2 = spam_cm(SubSpam, *a, **d)
  1484. self.assertEqual(x2, SubSpam)
  1485. self.assertEqual(a2, a1)
  1486. self.assertEqual(d2, d1)
  1487. with self.assertRaises(TypeError) as cm:
  1488. spam_cm()
  1489. self.assertEqual(
  1490. str(cm.exception),
  1491. "descriptor 'classmeth' of 'xxsubtype.spamlist' "
  1492. "object needs an argument")
  1493. with self.assertRaises(TypeError) as cm:
  1494. spam_cm(spam.spamlist())
  1495. self.assertEqual(
  1496. str(cm.exception),
  1497. "descriptor 'classmeth' for type 'xxsubtype.spamlist' "
  1498. "needs a type, not a 'xxsubtype.spamlist' as arg 2")
  1499. with self.assertRaises(TypeError) as cm:
  1500. spam_cm(list)
  1501. expected_errmsg = (
  1502. "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
  1503. "but received 'list'")
  1504. self.assertEqual(str(cm.exception), expected_errmsg)
  1505. with self.assertRaises(TypeError) as cm:
  1506. spam_cm.__get__(None, list)
  1507. self.assertEqual(str(cm.exception), expected_errmsg)
  1508. def test_staticmethods(self):
  1509. # Testing static methods...
  1510. class C(object):
  1511. def foo(*a): return a
  1512. goo = staticmethod(foo)
  1513. c = C()
  1514. self.assertEqual(C.goo(1), (1,))
  1515. self.assertEqual(c.goo(1), (1,))
  1516. self.assertEqual(c.foo(1), (c, 1,))
  1517. class D(C):
  1518. pass
  1519. d = D()
  1520. self.assertEqual(D.goo(1), (1,))
  1521. self.assertEqual(d.goo(1), (1,))
  1522. self.assertEqual(d.foo(1), (d, 1))
  1523. self.assertEqual(D.foo(d, 1), (d, 1))
  1524. sm = staticmethod(None)
  1525. self.assertEqual(sm.__dict__, {'__doc__': None})
  1526. sm.x = 42
  1527. self.assertEqual(sm.x, 42)
  1528. self.assertEqual(sm.__dict__, {"x" : 42, '__doc__': None})
  1529. del sm.x
  1530. self.assertNotHasAttr(sm, "x")
  1531. @support.refcount_test
  1532. def test_refleaks_in_staticmethod___init__(self):
  1533. gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
  1534. sm = staticmethod(None)
  1535. refs_before = gettotalrefcount()
  1536. for i in range(100):
  1537. sm.__init__(None)
  1538. self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
  1539. @support.impl_detail("the module 'xxsubtype' is internal")
  1540. def test_staticmethods_in_c(self):
  1541. # Testing C-based static methods...
  1542. import xxsubtype as spam
  1543. a = (1, 2, 3)
  1544. d = {"abc": 123}
  1545. x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
  1546. self.assertEqual(x, None)
  1547. self.assertEqual(a, a1)
  1548. self.assertEqual(d, d1)
  1549. x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
  1550. self.assertEqual(x, None)
  1551. self.assertEqual(a, a1)
  1552. self.assertEqual(d, d1)
  1553. def test_classic(self):
  1554. # Testing classic classes...
  1555. class C:
  1556. def foo(*a): return a
  1557. goo = classmethod(foo)
  1558. c = C()
  1559. self.assertEqual(C.goo(1), (C, 1))
  1560. self.assertEqual(c.goo(1), (C, 1))
  1561. self.assertEqual(c.foo(1), (c, 1))
  1562. class D(C):
  1563. pass
  1564. d = D()
  1565. self.assertEqual(D.goo(1), (D, 1))
  1566. self.assertEqual(d.goo(1), (D, 1))
  1567. self.assertEqual(d.foo(1), (d, 1))
  1568. self.assertEqual(D.foo(d, 1), (d, 1))
  1569. class E: # *not* subclassing from C
  1570. foo = C.foo
  1571. self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
  1572. self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
  1573. def test_compattr(self):
  1574. # Testing computed attributes...
  1575. class C(object):
  1576. class computed_attribute(object):
  1577. def __init__(self, get, set=None, delete=None):
  1578. self.__get = get
  1579. self.__set = set
  1580. self.__delete = delete
  1581. def __get__(self, obj, type=None):
  1582. return self.__get(obj)
  1583. def __set__(self, obj, value):
  1584. return self.__set(obj, value)
  1585. def __delete__(self, obj):
  1586. return self.__delete(obj)
  1587. def __init__(self):
  1588. self.__x = 0
  1589. def __get_x(self):
  1590. x = self.__x
  1591. self.__x = x+1
  1592. return x
  1593. def __set_x(self, x):
  1594. self.__x = x
  1595. def __delete_x(self):
  1596. del self.__x
  1597. x = computed_attribute(__get_x, __set_x, __delete_x)
  1598. a = C()
  1599. self.assertEqual(a.x, 0)
  1600. self.assertEqual(a.x, 1)
  1601. a.x = 10
  1602. self.assertEqual(a.x, 10)
  1603. self.assertEqual(a.x, 11)
  1604. del a.x
  1605. self.assertNotHasAttr(a, 'x')
  1606. def test_newslots(self):
  1607. # Testing __new__ slot override...
  1608. class C(list):
  1609. def __new__(cls):
  1610. self = list.__new__(cls)
  1611. self.foo = 1
  1612. return self
  1613. def __init__(self):
  1614. self.foo = self.foo + 2
  1615. a = C()
  1616. self.assertEqual(a.foo, 3)
  1617. self.assertEqual(a.__class__, C)
  1618. class D(C):
  1619. pass
  1620. b = D()
  1621. self.assertEqual(b.foo, 3)
  1622. self.assertEqual(b.__class__, D)
  1623. @unittest.expectedFailure
  1624. def test_bad_new(self):
  1625. self.assertRaises(TypeError, object.__new__)
  1626. self.assertRaises(TypeError, object.__new__, '')
  1627. self.assertRaises(TypeError, list.__new__, object)
  1628. self.assertRaises(TypeError, object.__new__, list)
  1629. class C(object):
  1630. __new__ = list.__new__
  1631. self.assertRaises(TypeError, C)
  1632. class C(list):
  1633. __new__ = object.__new__
  1634. self.assertRaises(TypeError, C)
  1635. def test_object_new(self):
  1636. class A(object):
  1637. pass
  1638. object.__new__(A)
  1639. self.assertRaises(TypeError, object.__new__, A, 5)
  1640. object.__init__(A())
  1641. self.assertRaises(TypeError, object.__init__, A(), 5)
  1642. class A(object):
  1643. def __init__(self, foo):
  1644. self.foo = foo
  1645. object.__new__(A)
  1646. object.__new__(A, 5)
  1647. object.__init__(A(3))
  1648. self.assertRaises(TypeError, object.__init__, A(3), 5)
  1649. class A(object):
  1650. def __new__(cls, foo):
  1651. return object.__new__(cls)
  1652. object.__new__(A)
  1653. self.assertRaises(TypeError, object.__new__, A, 5)
  1654. object.__init__(A(3))
  1655. object.__init__(A(3), 5)
  1656. class A(object):
  1657. def __new__(cls, foo):
  1658. return object.__new__(cls)
  1659. def __init__(self, foo):
  1660. self.foo = foo
  1661. object.__new__(A)
  1662. self.assertRaises(TypeError, object.__new__, A, 5)
  1663. object.__init__(A(3))
  1664. self.assertRaises(TypeError, object.__init__, A(3), 5)
  1665. @unittest.expectedFailure
  1666. def test_restored_object_new(self):
  1667. class A(object):
  1668. def __new__(cls, *args, **kwargs):
  1669. raise AssertionError
  1670. self.assertRaises(AssertionError, A)
  1671. class B(A):
  1672. __new__ = object.__new__
  1673. def __init__(self, foo):
  1674. self.foo = foo
  1675. with warnings.catch_warnings():
  1676. warnings.simplefilter('error', DeprecationWarning)
  1677. b = B(3)
  1678. self.assertEqual(b.foo, 3)
  1679. self.assertEqual(b.__class__, B)
  1680. del B.__new__
  1681. self.assertRaises(AssertionError, B)
  1682. del A.__new__
  1683. with warnings.catch_warnings():
  1684. warnings.simplefilter('error', DeprecationWarning)
  1685. b = B(3)
  1686. self.assertEqual(b.foo, 3)
  1687. self.assertEqual(b.__class__, B)
  1688. def test_altmro(self):
  1689. # Testing mro() and overriding it...
  1690. class A(object):
  1691. def f(self): return "A"
  1692. class B(A):
  1693. pass
  1694. class C(A):
  1695. def f(self): return "C"
  1696. class D(B, C):
  1697. pass
  1698. self.assertEqual(A.mro(), [A, object])
  1699. self.assertEqual(A.__mro__, (A, object))
  1700. self.assertEqual(B.mro(), [B, A, object])
  1701. self.assertEqual(B.__mro__, (B, A, object))
  1702. self.assertEqual(C.mro(), [C, A, object])
  1703. self.assertEqual(C.__mro__, (C, A, object))
  1704. self.assertEqual(D.mro(), [D, B, C, A, object])
  1705. self.assertEqual(D.__mro__, (D, B, C, A, object))
  1706. self.assertEqual(D().f(), "C")
  1707. class PerverseMetaType(type):
  1708. def mro(cls):
  1709. L = type.mro(cls)
  1710. L.reverse()
  1711. return L
  1712. class X(D,B,C,A, metaclass=PerverseMetaType):
  1713. pass
  1714. self.assertEqual(X.__mro__, (object, A, C, B, D, X))
  1715. self.assertEqual(X().f(), "A")
  1716. try:
  1717. class _metaclass(type):
  1718. def mro(self):
  1719. return [self, dict, object]
  1720. class X(object, metaclass=_metaclass):
  1721. pass
  1722. # In CPython, the class creation above already raises
  1723. # TypeError, as a protection against the fact that
  1724. # instances of X would segfault it. In other Python
  1725. # implementations it would be ok to let the class X
  1726. # be created, but instead get a clean TypeError on the
  1727. # __setitem__ below.
  1728. x = object.__new__(X)
  1729. x[5] = 6
  1730. except TypeError:
  1731. pass
  1732. else:
  1733. self.fail("devious mro() return not caught")
  1734. try:
  1735. class _metaclass(type):
  1736. def mro(self):
  1737. return [1]
  1738. class X(object, metaclass=_metaclass):
  1739. pass
  1740. except TypeError:
  1741. pass
  1742. else:
  1743. self.fail("non-class mro() return not caught")
  1744. try:
  1745. class _metaclass(type):
  1746. def mro(self):
  1747. return 1
  1748. class X(object, metaclass=_metaclass):
  1749. pass
  1750. except TypeError:
  1751. pass
  1752. else:
  1753. self.fail("non-sequence mro() return not caught")
  1754. def test_overloading(self):
  1755. # Testing operator overloading...
  1756. class B(object):
  1757. "Intermediate class because object doesn't have a __setattr__"
  1758. class C(B):
  1759. def __getattr__(self, name):
  1760. if name == "foo":
  1761. return ("getattr", name)
  1762. else:
  1763. raise AttributeError
  1764. def __setattr__(self, name, value):
  1765. if name == "foo":
  1766. self.setattr = (name, value)
  1767. else:
  1768. return B.__setattr__(self, name, value)
  1769. def __delattr__(self, name):
  1770. if name == "foo":
  1771. self.delattr = name
  1772. else:
  1773. return B.__delattr__(self, name)
  1774. def __getitem__(self, key):
  1775. return ("getitem", key)
  1776. def __setitem__(self, key, value):
  1777. self.setitem = (key, value)
  1778. def __delitem__(self, key):
  1779. self.delitem = key
  1780. a = C()
  1781. self.assertEqual(a.foo, ("getattr", "foo"))
  1782. a.foo = 12
  1783. self.assertEqual(a.setattr, ("foo", 12))
  1784. del a.foo
  1785. self.assertEqual(a.delattr, "foo")
  1786. self.assertEqual(a[12], ("getitem", 12))
  1787. a[12] = 21
  1788. self.assertEqual(a.setitem, (12, 21))
  1789. del a[12]
  1790. self.assertEqual(a.delitem, 12)
  1791. self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
  1792. a[0:10] = "foo"
  1793. self.assertEqual(a.setitem, (slice(0, 10), "foo"))
  1794. del a[0:10]
  1795. self.assertEqual(a.delitem, (slice(0, 10)))
  1796. def test_load_attr_extended_arg(self):
  1797. # https://github.com/python/cpython/issues/91625
  1798. class Numbers:
  1799. def __getattr__(self, attr):
  1800. return int(attr.lstrip("_"))
  1801. attrs = ", ".join(f"Z._{n:03d}" for n in range(280))
  1802. code = f"def number_attrs(Z):\n return [ {attrs} ]"
  1803. ns = {}
  1804. exec(code, ns)
  1805. number_attrs = ns["number_attrs"]
  1806. # Warm up the the function for quickening (PEP 659)
  1807. for _ in range(30):
  1808. self.assertEqual(number_attrs(Numbers()), list(range(280)))
  1809. def test_methods(self):
  1810. # Testing methods...
  1811. class C(object):
  1812. def __init__(self, x):
  1813. self.x = x
  1814. def foo(self):
  1815. return self.x
  1816. c1 = C(1)
  1817. self.assertEqual(c1.foo(), 1)
  1818. class D(C):
  1819. boo = C.foo
  1820. goo = c1.foo
  1821. d2 = D(2)
  1822. self.assertEqual(d2.foo(), 2)
  1823. self.assertEqual(d2.boo(), 2)
  1824. self.assertEqual(d2.goo(), 1)
  1825. class E(object):
  1826. foo = C.foo
  1827. self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
  1828. self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
  1829. @support.impl_detail("testing error message from implementation")
  1830. def test_methods_in_c(self):
  1831. # This test checks error messages in builtin method descriptor.
  1832. # It is allowed that other Python implementations use
  1833. # different error messages.
  1834. set_add = set.add
  1835. expected_errmsg = "unbound method set.add() needs an argument"
  1836. with self.assertRaises(TypeError) as cm:
  1837. set_add()
  1838. self.assertEqual(cm.exception.args[0], expected_errmsg)
  1839. expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"
  1840. with self.assertRaises(TypeError) as cm:
  1841. set_add(0)
  1842. self.assertEqual(cm.exception.args[0], expected_errmsg)
  1843. with self.assertRaises(TypeError) as cm:
  1844. set_add.__get__(0)
  1845. self.assertEqual(cm.exception.args[0], expected_errmsg)
  1846. def test_special_method_lookup(self):
  1847. # The lookup of special methods bypasses __getattr__ and
  1848. # __getattribute__, but they still can be descriptors.
  1849. def run_context(manager):
  1850. with manager:
  1851. pass
  1852. def iden(self):
  1853. return self
  1854. def hello(self):
  1855. return b"hello"
  1856. def empty_seq(self):
  1857. return []
  1858. def zero(self):
  1859. return 0
  1860. def complex_num(self):
  1861. return 1j
  1862. def stop(self):
  1863. raise StopIteration
  1864. def return_true(self, thing=None):
  1865. return True
  1866. def do_isinstance(obj):
  1867. return isinstance(int, obj)
  1868. def do_issubclass(obj):
  1869. return issubclass(int, obj)
  1870. def do_dict_missing(checker):
  1871. class DictSub(checker.__class__, dict):
  1872. pass
  1873. self.assertEqual(DictSub()["hi"], 4)
  1874. def some_number(self_, key):
  1875. self.assertEqual(key, "hi")
  1876. return 4
  1877. def swallow(*args): pass
  1878. def format_impl(self, spec):
  1879. return "hello"
  1880. # It would be nice to have every special method tested here, but I'm
  1881. # only listing the ones I can remember outside of typeobject.c, since it
  1882. # does it right.
  1883. specials = [
  1884. ("__bytes__", bytes, hello, set(), {}),
  1885. ("__reversed__", reversed, empty_seq, set(), {}),
  1886. ("__length_hint__", list, zero, set(),
  1887. {"__iter__" : iden, "__next__" : stop}),
  1888. ("__sizeof__", sys.getsizeof, zero, set(), {}),
  1889. ("__instancecheck__", do_isinstance, return_true, set(), {}),
  1890. ("__missing__", do_dict_missing, some_number,
  1891. set(("__class__",)), {}),
  1892. ("__subclasscheck__", do_issubclass, return_true,
  1893. set(("__bases__",)), {}),
  1894. ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
  1895. ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
  1896. ("__complex__", complex, complex_num, set(), {}),
  1897. ("__format__", format, format_impl, set(), {}),
  1898. ("__floor__", math.floor, zero, set(), {}),
  1899. ("__trunc__", math.trunc, zero, set(), {}),
  1900. ("__ceil__", math.ceil, zero, set(), {}),
  1901. ("__dir__", dir, empty_seq, set(), {}),
  1902. ("__round__", round, zero, set(), {}),
  1903. ]
  1904. class Checker(object):
  1905. def __getattr__(self, attr, test=self):
  1906. test.fail("__getattr__ called with {0}".format(attr))
  1907. def __getattribute__(self, attr, test=self):
  1908. if attr not in ok:
  1909. test.fail("__getattribute__ called with {0}".format(attr))
  1910. return object.__getattribute__(self, attr)
  1911. class SpecialDescr(object):
  1912. def __init__(self, impl):
  1913. self.impl = impl
  1914. def __get__(self, obj, owner):
  1915. record.append(1)
  1916. return self.impl.__get__(obj, owner)
  1917. class MyException(Exception):
  1918. pass
  1919. class ErrDescr(object):
  1920. def __get__(self, obj, owner):
  1921. raise MyException
  1922. for name, runner, meth_impl, ok, env in specials:
  1923. class X(Checker):
  1924. pass
  1925. for attr, obj in env.items():
  1926. setattr(X, attr, obj)
  1927. setattr(X, name, meth_impl)
  1928. runner(X())
  1929. record = []
  1930. class X(Checker):
  1931. pass
  1932. for attr, obj in env.items():
  1933. setattr(X, attr, obj)
  1934. setattr(X, name, SpecialDescr(meth_impl))
  1935. runner(X())
  1936. self.assertEqual(record, [1], name)
  1937. class X(Checker):
  1938. pass
  1939. for attr, obj in env.items():
  1940. setattr(X, attr, obj)
  1941. setattr(X, name, ErrDescr())
  1942. self.assertRaises(MyException, runner, X())
  1943. def test_specials(self):
  1944. # Testing special operators...
  1945. # Test operators like __hash__ for which a built-in default exists
  1946. # Test the default behavior for static classes
  1947. class C(object):
  1948. def __getitem__(self, i):
  1949. if 0 <= i < 10: return i
  1950. raise IndexError
  1951. c1 = C()
  1952. c2 = C()
  1953. self.assertFalse(not c1)
  1954. self.assertNotEqual(id(c1), id(c2))
  1955. hash(c1)
  1956. hash(c2)
  1957. self.assertEqual(c1, c1)
  1958. self.assertTrue(c1 != c2)
  1959. self.assertFalse(c1 != c1)
  1960. self.assertFalse(c1 == c2)
  1961. # Note that the module name appears in str/repr, and that varies
  1962. # depending on whether this test is run standalone or from a framework.
  1963. self.assertGreaterEqual(str(c1).find('C object at '), 0)
  1964. self.assertEqual(str(c1), repr(c1))
  1965. self.assertNotIn(-1, c1)
  1966. for i in range(10):
  1967. self.assertIn(i, c1)
  1968. self.assertNotIn(10, c1)
  1969. # Test the default behavior for dynamic classes
  1970. class D(object):
  1971. def __getitem__(self, i):
  1972. if 0 <= i < 10: return i
  1973. raise IndexError
  1974. d1 = D()
  1975. d2 = D()
  1976. self.assertFalse(not d1)
  1977. self.assertNotEqual(id(d1), id(d2))
  1978. hash(d1)
  1979. hash(d2)
  1980. self.assertEqual(d1, d1)
  1981. self.assertNotEqual(d1, d2)
  1982. self.assertFalse(d1 != d1)
  1983. self.assertFalse(d1 == d2)
  1984. # Note that the module name appears in str/repr, and that varies
  1985. # depending on whether this test is run standalone or from a framework.
  1986. self.assertGreaterEqual(str(d1).find('D object at '), 0)
  1987. self.assertEqual(str(d1), repr(d1))
  1988. self.assertNotIn(-1, d1)
  1989. for i in range(10):
  1990. self.assertIn(i, d1)
  1991. self.assertNotIn(10, d1)
  1992. # Test overridden behavior
  1993. class Proxy(object):
  1994. def __init__(self, x):
  1995. self.x = x
  1996. def __bool__(self):
  1997. return not not self.x
  1998. def __hash__(self):
  1999. return hash(self.x)
  2000. def __eq__(self, other):
  2001. return self.x == other
  2002. def __ne__(self, other):
  2003. return self.x != other
  2004. def __ge__(self, other):
  2005. return self.x >= other
  2006. def __gt__(self, other):
  2007. return self.x > other
  2008. def __le__(self, other):
  2009. return self.x <= other
  2010. def __lt__(self, other):
  2011. return self.x < other
  2012. def __str__(self):
  2013. return "Proxy:%s" % self.x
  2014. def __repr__(self):
  2015. return "Proxy(%r)" % self.x
  2016. def __contains__(self, value):
  2017. return value in self.x
  2018. p0 = Proxy(0)
  2019. p1 = Proxy(1)
  2020. p_1 = Proxy(-1)
  2021. self.assertFalse(p0)
  2022. self.assertFalse(not p1)
  2023. self.assertEqual(hash(p0), hash(0))
  2024. self.assertEqual(p0, p0)
  2025. self.assertNotEqual(p0, p1)
  2026. self.assertFalse(p0 != p0)
  2027. self.assertEqual(not p0, p1)
  2028. self.assertTrue(p0 < p1)
  2029. self.assertTrue(p0 <= p1)
  2030. self.assertTrue(p1 > p0)
  2031. self.assertTrue(p1 >= p0)
  2032. self.assertEqual(str(p0), "Proxy:0")
  2033. self.assertEqual(repr(p0), "Proxy(0)")
  2034. p10 = Proxy(range(10))
  2035. self.assertNotIn(-1, p10)
  2036. for i in range(10):
  2037. self.assertIn(i, p10)
  2038. self.assertNotIn(10, p10)
  2039. def test_weakrefs(self):
  2040. # Testing weak references...
  2041. import weakref
  2042. class C(object):
  2043. pass
  2044. c = C()
  2045. r = weakref.ref(c)
  2046. self.assertEqual(r(), c)
  2047. del c
  2048. support.gc_collect()
  2049. self.assertEqual(r(), None)
  2050. del r
  2051. class NoWeak(object):
  2052. __slots__ = ['foo']
  2053. no = NoWeak()
  2054. try:
  2055. weakref.ref(no)
  2056. except TypeError as msg:
  2057. self.assertIn("weak reference", str(msg))
  2058. else:
  2059. self.fail("weakref.ref(no) should be illegal")
  2060. class Weak(object):
  2061. __slots__ = ['foo', '__weakref__']
  2062. yes = Weak()
  2063. r = weakref.ref(yes)
  2064. self.assertEqual(r(), yes)
  2065. del yes
  2066. support.gc_collect()
  2067. self.assertEqual(r(), None)
  2068. del r
  2069. def test_properties(self):
  2070. # Testing property...
  2071. class C(object):
  2072. def getx(self):
  2073. return self.__x
  2074. def setx(self, value):
  2075. self.__x = value
  2076. def delx(self):
  2077. del self.__x
  2078. x = property(getx, setx, delx, doc="I'm the x property.")
  2079. a = C()
  2080. self.assertNotHasAttr(a, "x")
  2081. a.x = 42
  2082. self.assertEqual(a._C__x, 42)
  2083. self.assertEqual(a.x, 42)
  2084. del a.x
  2085. self.assertNotHasAttr(a, "x")
  2086. self.assertNotHasAttr(a, "_C__x")
  2087. C.x.__set__(a, 100)
  2088. self.assertEqual(C.x.__get__(a), 100)
  2089. C.x.__delete__(a)
  2090. self.assertNotHasAttr(a, "x")
  2091. raw = C.__dict__['x']
  2092. self.assertIsInstance(raw, property)
  2093. attrs = dir(raw)
  2094. self.assertIn("__doc__", attrs)
  2095. self.assertIn("fget", attrs)
  2096. self.assertIn("fset", attrs)
  2097. self.assertIn("fdel", attrs)
  2098. self.assertEqual(raw.__doc__, "I'm the x property.")
  2099. self.assertIs(raw.fget, C.__dict__['getx'])
  2100. self.assertIs(raw.fset, C.__dict__['setx'])
  2101. self.assertIs(raw.fdel, C.__dict__['delx'])
  2102. for attr in "fget", "fset", "fdel":
  2103. try:
  2104. setattr(raw, attr, 42)
  2105. except AttributeError as msg:
  2106. if str(msg).find('readonly') < 0:
  2107. self.fail("when setting readonly attr %r on a property, "
  2108. "got unexpected AttributeError msg %r" % (attr, str(msg)))
  2109. else:
  2110. self.fail("expected AttributeError from trying to set readonly %r "
  2111. "attr on a property" % attr)
  2112. raw.__doc__ = 42
  2113. self.assertEqual(raw.__doc__, 42)
  2114. class D(object):
  2115. __getitem__ = property(lambda s: 1/0)
  2116. d = D()
  2117. try:
  2118. for i in d:
  2119. str(i)
  2120. except ZeroDivisionError:
  2121. pass
  2122. else:
  2123. self.fail("expected ZeroDivisionError from bad property")
  2124. @unittest.skipIf(sys.flags.optimize >= 2,
  2125. "Docstrings are omitted with -O2 and above")
  2126. def test_properties_doc_attrib(self):
  2127. class E(object):
  2128. def getter(self):
  2129. "getter method"
  2130. return 0
  2131. def setter(self_, value):
  2132. "setter method"
  2133. pass
  2134. prop = property(getter)
  2135. self.assertEqual(prop.__doc__, "getter method")
  2136. prop2 = property(fset=setter)
  2137. self.assertEqual(prop2.__doc__, None)
  2138. @support.cpython_only
  2139. def test_testcapi_no_segfault(self):
  2140. # this segfaulted in 2.5b2
  2141. try:
  2142. import _testcapi
  2143. except ImportError:
  2144. pass
  2145. else:
  2146. class X(object):
  2147. p = property(_testcapi.test_with_docstring)
  2148. def test_properties_plus(self):
  2149. class C(object):
  2150. foo = property(doc="hello")
  2151. @foo.getter
  2152. def foo(self):
  2153. return self._foo
  2154. @foo.setter
  2155. def foo(self, value):
  2156. self._foo = abs(value)
  2157. @foo.deleter
  2158. def foo(self):
  2159. del self._foo
  2160. c = C()
  2161. self.assertEqual(C.foo.__doc__, "hello")
  2162. self.assertNotHasAttr(c, "foo")
  2163. c.foo = -42
  2164. self.assertHasAttr(c, '_foo')
  2165. self.assertEqual(c._foo, 42)
  2166. self.assertEqual(c.foo, 42)
  2167. del c.foo
  2168. self.assertNotHasAttr(c, '_foo')
  2169. self.assertNotHasAttr(c, "foo")
  2170. class D(C):
  2171. @C.foo.deleter
  2172. def foo(self):
  2173. try:
  2174. del self._foo
  2175. except AttributeError:
  2176. pass
  2177. d = D()
  2178. d.foo = 24
  2179. self.assertEqual(d.foo, 24)
  2180. del d.foo
  2181. del d.foo
  2182. class E(object):
  2183. @property
  2184. def foo(self):
  2185. return self._foo
  2186. @foo.setter
  2187. def foo(self, value):
  2188. raise RuntimeError
  2189. @foo.setter
  2190. def foo(self, value):
  2191. self._foo = abs(value)
  2192. @foo.deleter
  2193. def foo(self, value=None):
  2194. del self._foo
  2195. e = E()
  2196. e.foo = -42
  2197. self.assertEqual(e.foo, 42)
  2198. del e.foo
  2199. class F(E):
  2200. @E.foo.deleter
  2201. def foo(self):
  2202. del self._foo
  2203. @foo.setter
  2204. def foo(self, value):
  2205. self._foo = max(0, value)
  2206. f = F()
  2207. f.foo = -10
  2208. self.assertEqual(f.foo, 0)
  2209. del f.foo
  2210. def test_dict_constructors(self):
  2211. # Testing dict constructor ...
  2212. d = dict()
  2213. self.assertEqual(d, {})
  2214. d = dict({})
  2215. self.assertEqual(d, {})
  2216. d = dict({1: 2, 'a': 'b'})
  2217. self.assertEqual(d, {1: 2, 'a': 'b'})
  2218. self.assertEqual(d, dict(list(d.items())))
  2219. self.assertEqual(d, dict(iter(d.items())))
  2220. d = dict({'one':1, 'two':2})
  2221. self.assertEqual(d, dict(one=1, two=2))
  2222. self.assertEqual(d, dict(**d))
  2223. self.assertEqual(d, dict({"one": 1}, two=2))
  2224. self.assertEqual(d, dict([("two", 2)], one=1))
  2225. self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
  2226. self.assertEqual(d, dict(**d))
  2227. for badarg in 0, 0, 0j, "0", [0], (0,):
  2228. try:
  2229. dict(badarg)
  2230. except TypeError:
  2231. pass
  2232. except ValueError:
  2233. if badarg == "0":
  2234. # It's a sequence, and its elements are also sequences (gotta
  2235. # love strings <wink>), but they aren't of length 2, so this
  2236. # one seemed better as a ValueError than a TypeError.
  2237. pass
  2238. else:
  2239. self.fail("no TypeError from dict(%r)" % badarg)
  2240. else:
  2241. self.fail("no TypeError from dict(%r)" % badarg)
  2242. with self.assertRaises(TypeError):
  2243. dict({}, {})
  2244. class Mapping:
  2245. # Lacks a .keys() method; will be added later.
  2246. dict = {1:2, 3:4, 'a':1j}
  2247. try:
  2248. dict(Mapping())
  2249. except TypeError:
  2250. pass
  2251. else:
  2252. self.fail("no TypeError from dict(incomplete mapping)")
  2253. Mapping.keys = lambda self: list(self.dict.keys())
  2254. Mapping.__getitem__ = lambda self, i: self.dict[i]
  2255. d = dict(Mapping())
  2256. self.assertEqual(d, Mapping.dict)
  2257. # Init from sequence of iterable objects, each producing a 2-sequence.
  2258. class AddressBookEntry:
  2259. def __init__(self, first, last):
  2260. self.first = first
  2261. self.last = last
  2262. def __iter__(self):
  2263. return iter([self.first, self.last])
  2264. d = dict([AddressBookEntry('Tim', 'Warsaw'),
  2265. AddressBookEntry('Barry', 'Peters'),
  2266. AddressBookEntry('Tim', 'Peters'),
  2267. AddressBookEntry('Barry', 'Warsaw')])
  2268. self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
  2269. d = dict(zip(range(4), range(1, 5)))
  2270. self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
  2271. # Bad sequence lengths.
  2272. for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
  2273. try:
  2274. dict(bad)
  2275. except ValueError:
  2276. pass
  2277. else:
  2278. self.fail("no ValueError from dict(%r)" % bad)
  2279. def test_dir(self):
  2280. # Testing dir() ...
  2281. junk = 12
  2282. self.assertEqual(dir(), ['junk', 'self'])
  2283. del junk
  2284. # Just make sure these don't blow up!
  2285. for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
  2286. dir(arg)
  2287. # Test dir on new-style classes. Since these have object as a
  2288. # base class, a lot more gets sucked in.
  2289. def interesting(strings):
  2290. return [s for s in strings if not s.startswith('_')]
  2291. class C(object):
  2292. Cdata = 1
  2293. def Cmethod(self): pass
  2294. cstuff = ['Cdata', 'Cmethod']
  2295. self.assertEqual(interesting(dir(C)), cstuff)
  2296. c = C()
  2297. self.assertEqual(interesting(dir(c)), cstuff)
  2298. ## self.assertIn('__self__', dir(C.Cmethod))
  2299. c.cdata = 2
  2300. c.cmethod = lambda self: 0
  2301. self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
  2302. ## self.assertIn('__self__', dir(c.Cmethod))
  2303. class A(C):
  2304. Adata = 1
  2305. def Amethod(self): pass
  2306. astuff = ['Adata', 'Amethod'] + cstuff
  2307. self.assertEqual(interesting(dir(A)), astuff)
  2308. ## self.assertIn('__self__', dir(A.Amethod))
  2309. a = A()
  2310. self.assertEqual(interesting(dir(a)), astuff)
  2311. a.adata = 42
  2312. a.amethod = lambda self: 3
  2313. self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
  2314. ## self.assertIn('__self__', dir(a.Amethod))
  2315. # Try a module subclass.
  2316. class M(type(sys)):
  2317. pass
  2318. minstance = M("m")
  2319. minstance.b = 2
  2320. minstance.a = 1
  2321. default_attributes = ['__name__', '__doc__', '__package__',
  2322. '__loader__', '__spec__']
  2323. names = [x for x in dir(minstance) if x not in default_attributes]
  2324. self.assertEqual(names, ['a', 'b'])
  2325. class M2(M):
  2326. def getdict(self):
  2327. return "Not a dict!"
  2328. __dict__ = property(getdict)
  2329. m2instance = M2("m2")
  2330. m2instance.b = 2
  2331. m2instance.a = 1
  2332. self.assertEqual(m2instance.__dict__, "Not a dict!")
  2333. with self.assertRaises(TypeError):
  2334. dir(m2instance)
  2335. # Two essentially featureless objects, (Ellipsis just inherits stuff
  2336. # from object.
  2337. self.assertEqual(dir(object()), dir(Ellipsis))
  2338. # Nasty test case for proxied objects
  2339. class Wrapper(object):
  2340. def __init__(self, obj):
  2341. self.__obj = obj
  2342. def __repr__(self):
  2343. return "Wrapper(%s)" % repr(self.__obj)
  2344. def __getitem__(self, key):
  2345. return Wrapper(self.__obj[key])
  2346. def __len__(self):
  2347. return len(self.__obj)
  2348. def __getattr__(self, name):
  2349. return Wrapper(getattr(self.__obj, name))
  2350. class C(object):
  2351. def __getclass(self):
  2352. return Wrapper(type(self))
  2353. __class__ = property(__getclass)
  2354. dir(C()) # This used to segfault
  2355. def test_supers(self):
  2356. # Testing super...
  2357. class A(object):
  2358. def meth(self, a):
  2359. return "A(%r)" % a
  2360. self.assertEqual(A().meth(1), "A(1)")
  2361. class B(A):
  2362. def __init__(self):
  2363. self.__super = super(B, self)
  2364. def meth(self, a):
  2365. return "B(%r)" % a + self.__super.meth(a)
  2366. self.assertEqual(B().meth(2), "B(2)A(2)")
  2367. class C(A):
  2368. def meth(self, a):
  2369. return "C(%r)" % a + self.__super.meth(a)
  2370. C._C__super = super(C)
  2371. self.assertEqual(C().meth(3), "C(3)A(3)")
  2372. class D(C, B):
  2373. def meth(self, a):
  2374. return "D(%r)" % a + super(D, self).meth(a)
  2375. self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
  2376. # Test for subclassing super
  2377. class mysuper(super):
  2378. def __init__(self, *args):
  2379. return super(mysuper, self).__init__(*args)
  2380. class E(D):
  2381. def meth(self, a):
  2382. return "E(%r)" % a + mysuper(E, self).meth(a)
  2383. self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
  2384. class F(E):
  2385. def meth(self, a):
  2386. s = self.__super # == mysuper(F, self)
  2387. return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
  2388. F._F__super = mysuper(F)
  2389. self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
  2390. # Make sure certain errors are raised
  2391. try:
  2392. super(D, 42)
  2393. except TypeError:
  2394. pass
  2395. else:
  2396. self.fail("shouldn't allow super(D, 42)")
  2397. try:
  2398. super(D, C())
  2399. except TypeError:
  2400. pass
  2401. else:
  2402. self.fail("shouldn't allow super(D, C())")
  2403. try:
  2404. super(D).__get__(12)
  2405. except TypeError:
  2406. pass
  2407. else:
  2408. self.fail("shouldn't allow super(D).__get__(12)")
  2409. try:
  2410. super(D).__get__(C())
  2411. except TypeError:
  2412. pass
  2413. else:
  2414. self.fail("shouldn't allow super(D).__get__(C())")
  2415. # Make sure data descriptors can be overridden and accessed via super
  2416. # (new feature in Python 2.3)
  2417. class DDbase(object):
  2418. def getx(self): return 42
  2419. x = property(getx)
  2420. class DDsub(DDbase):
  2421. def getx(self): return "hello"
  2422. x = property(getx)
  2423. dd = DDsub()
  2424. self.assertEqual(dd.x, "hello")
  2425. self.assertEqual(super(DDsub, dd).x, 42)
  2426. # Ensure that super() lookup of descriptor from classmethod
  2427. # works (SF ID# 743627)
  2428. class Base(object):
  2429. aProp = property(lambda self: "foo")
  2430. class Sub(Base):
  2431. @classmethod
  2432. def test(klass):
  2433. return super(Sub,klass).aProp
  2434. self.assertEqual(Sub.test(), Base.aProp)
  2435. # Verify that super() doesn't allow keyword args
  2436. with self.assertRaises(TypeError):
  2437. super(Base, kw=1)
  2438. def test_basic_inheritance(self):
  2439. # Testing inheritance from basic types...
  2440. class hexint(int):
  2441. def __repr__(self):
  2442. return hex(self)
  2443. def __add__(self, other):
  2444. return hexint(int.__add__(self, other))
  2445. # (Note that overriding __radd__ doesn't work,
  2446. # because the int type gets first dibs.)
  2447. self.assertEqual(repr(hexint(7) + 9), "0x10")
  2448. self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
  2449. a = hexint(12345)
  2450. self.assertEqual(a, 12345)
  2451. self.assertEqual(int(a), 12345)
  2452. self.assertIs(int(a).__class__, int)
  2453. self.assertEqual(hash(a), hash(12345))
  2454. self.assertIs((+a).__class__, int)
  2455. self.assertIs((a >> 0).__class__, int)
  2456. self.assertIs((a << 0).__class__, int)
  2457. self.assertIs((hexint(0) << 12).__class__, int)
  2458. self.assertIs((hexint(0) >> 12).__class__, int)
  2459. class octlong(int):
  2460. __slots__ = []
  2461. def __str__(self):
  2462. return oct(self)
  2463. def __add__(self, other):
  2464. return self.__class__(super(octlong, self).__add__(other))
  2465. __radd__ = __add__
  2466. self.assertEqual(str(octlong(3) + 5), "0o10")
  2467. # (Note that overriding __radd__ here only seems to work
  2468. # because the example uses a short int left argument.)
  2469. self.assertEqual(str(5 + octlong(3000)), "0o5675")
  2470. a = octlong(12345)
  2471. self.assertEqual(a, 12345)
  2472. self.assertEqual(int(a), 12345)
  2473. self.assertEqual(hash(a), hash(12345))
  2474. self.assertIs(int(a).__class__, int)
  2475. self.assertIs((+a).__class__, int)
  2476. self.assertIs((-a).__class__, int)
  2477. self.assertIs((-octlong(0)).__class__, int)
  2478. self.assertIs((a >> 0).__class__, int)
  2479. self.assertIs((a << 0).__class__, int)
  2480. self.assertIs((a - 0).__class__, int)
  2481. self.assertIs((a * 1).__class__, int)
  2482. self.assertIs((a ** 1).__class__, int)
  2483. self.assertIs((a // 1).__class__, int)
  2484. self.assertIs((1 * a).__class__, int)
  2485. self.assertIs((a | 0).__class__, int)
  2486. self.assertIs((a ^ 0).__class__, int)
  2487. self.assertIs((a & -1).__class__, int)
  2488. self.assertIs((octlong(0) << 12).__class__, int)
  2489. self.assertIs((octlong(0) >> 12).__class__, int)
  2490. self.assertIs(abs(octlong(0)).__class__, int)
  2491. # Because octlong overrides __add__, we can't check the absence of +0
  2492. # optimizations using octlong.
  2493. class longclone(int):
  2494. pass
  2495. a = longclone(1)
  2496. self.assertIs((a + 0).__class__, int)
  2497. self.assertIs((0 + a).__class__, int)
  2498. # Check that negative clones don't segfault
  2499. a = longclone(-1)
  2500. self.assertEqual(a.__dict__, {})
  2501. self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
  2502. class precfloat(float):
  2503. __slots__ = ['prec']
  2504. def __init__(self, value=0.0, prec=12):
  2505. self.prec = int(prec)
  2506. def __repr__(self):
  2507. return "%.*g" % (self.prec, self)
  2508. self.assertEqual(repr(precfloat(1.1)), "1.1")
  2509. a = precfloat(12345)
  2510. self.assertEqual(a, 12345.0)
  2511. self.assertEqual(float(a), 12345.0)
  2512. self.assertIs(float(a).__class__, float)
  2513. self.assertEqual(hash(a), hash(12345.0))
  2514. self.assertIs((+a).__class__, float)
  2515. class madcomplex(complex):
  2516. def __repr__(self):
  2517. return "%.17gj%+.17g" % (self.imag, self.real)
  2518. a = madcomplex(-3, 4)
  2519. self.assertEqual(repr(a), "4j-3")
  2520. base = complex(-3, 4)
  2521. self.assertEqual(base.__class__, complex)
  2522. self.assertEqual(a, base)
  2523. self.assertEqual(complex(a), base)
  2524. self.assertEqual(complex(a).__class__, complex)
  2525. a = madcomplex(a) # just trying another form of the constructor
  2526. self.assertEqual(repr(a), "4j-3")
  2527. self.assertEqual(a, base)
  2528. self.assertEqual(complex(a), base)
  2529. self.assertEqual(complex(a).__class__, complex)
  2530. self.assertEqual(hash(a), hash(base))
  2531. self.assertEqual((+a).__class__, complex)
  2532. self.assertEqual((a + 0).__class__, complex)
  2533. self.assertEqual(a + 0, base)
  2534. self.assertEqual((a - 0).__class__, complex)
  2535. self.assertEqual(a - 0, base)
  2536. self.assertEqual((a * 1).__class__, complex)
  2537. self.assertEqual(a * 1, base)
  2538. self.assertEqual((a / 1).__class__, complex)
  2539. self.assertEqual(a / 1, base)
  2540. class madtuple(tuple):
  2541. _rev = None
  2542. def rev(self):
  2543. if self._rev is not None:
  2544. return self._rev
  2545. L = list(self)
  2546. L.reverse()
  2547. self._rev = self.__class__(L)
  2548. return self._rev
  2549. a = madtuple((1,2,3,4,5,6,7,8,9,0))
  2550. self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
  2551. self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
  2552. self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
  2553. for i in range(512):
  2554. t = madtuple(range(i))
  2555. u = t.rev()
  2556. v = u.rev()
  2557. self.assertEqual(v, t)
  2558. a = madtuple((1,2,3,4,5))
  2559. self.assertEqual(tuple(a), (1,2,3,4,5))
  2560. self.assertIs(tuple(a).__class__, tuple)
  2561. self.assertEqual(hash(a), hash((1,2,3,4,5)))
  2562. self.assertIs(a[:].__class__, tuple)
  2563. self.assertIs((a * 1).__class__, tuple)
  2564. self.assertIs((a * 0).__class__, tuple)
  2565. self.assertIs((a + ()).__class__, tuple)
  2566. a = madtuple(())
  2567. self.assertEqual(tuple(a), ())
  2568. self.assertIs(tuple(a).__class__, tuple)
  2569. self.assertIs((a + a).__class__, tuple)
  2570. self.assertIs((a * 0).__class__, tuple)
  2571. self.assertIs((a * 1).__class__, tuple)
  2572. self.assertIs((a * 2).__class__, tuple)
  2573. self.assertIs(a[:].__class__, tuple)
  2574. class madstring(str):
  2575. _rev = None
  2576. def rev(self):
  2577. if self._rev is not None:
  2578. return self._rev
  2579. L = list(self)
  2580. L.reverse()
  2581. self._rev = self.__class__("".join(L))
  2582. return self._rev
  2583. s = madstring("abcdefghijklmnopqrstuvwxyz")
  2584. self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
  2585. self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
  2586. self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
  2587. for i in range(256):
  2588. s = madstring("".join(map(chr, range(i))))
  2589. t = s.rev()
  2590. u = t.rev()
  2591. self.assertEqual(u, s)
  2592. s = madstring("12345")
  2593. self.assertEqual(str(s), "12345")
  2594. self.assertIs(str(s).__class__, str)
  2595. base = "\x00" * 5
  2596. s = madstring(base)
  2597. self.assertEqual(s, base)
  2598. self.assertEqual(str(s), base)
  2599. self.assertIs(str(s).__class__, str)
  2600. self.assertEqual(hash(s), hash(base))
  2601. self.assertEqual({s: 1}[base], 1)
  2602. self.assertEqual({base: 1}[s], 1)
  2603. self.assertIs((s + "").__class__, str)
  2604. self.assertEqual(s + "", base)
  2605. self.assertIs(("" + s).__class__, str)
  2606. self.assertEqual("" + s, base)
  2607. self.assertIs((s * 0).__class__, str)
  2608. self.assertEqual(s * 0, "")
  2609. self.assertIs((s * 1).__class__, str)
  2610. self.assertEqual(s * 1, base)
  2611. self.assertIs((s * 2).__class__, str)
  2612. self.assertEqual(s * 2, base + base)
  2613. self.assertIs(s[:].__class__, str)
  2614. self.assertEqual(s[:], base)
  2615. self.assertIs(s[0:0].__class__, str)
  2616. self.assertEqual(s[0:0], "")
  2617. self.assertIs(s.strip().__class__, str)
  2618. self.assertEqual(s.strip(), base)
  2619. self.assertIs(s.lstrip().__class__, str)
  2620. self.assertEqual(s.lstrip(), base)
  2621. self.assertIs(s.rstrip().__class__, str)
  2622. self.assertEqual(s.rstrip(), base)
  2623. identitytab = {}
  2624. self.assertIs(s.translate(identitytab).__class__, str)
  2625. self.assertEqual(s.translate(identitytab), base)
  2626. self.assertIs(s.replace("x", "x").__class__, str)
  2627. self.assertEqual(s.replace("x", "x"), base)
  2628. self.assertIs(s.ljust(len(s)).__class__, str)
  2629. self.assertEqual(s.ljust(len(s)), base)
  2630. self.assertIs(s.rjust(len(s)).__class__, str)
  2631. self.assertEqual(s.rjust(len(s)), base)
  2632. self.assertIs(s.center(len(s)).__class__, str)
  2633. self.assertEqual(s.center(len(s)), base)
  2634. self.assertIs(s.lower().__class__, str)
  2635. self.assertEqual(s.lower(), base)
  2636. class madunicode(str):
  2637. _rev = None
  2638. def rev(self):
  2639. if self._rev is not None:
  2640. return self._rev
  2641. L = list(self)
  2642. L.reverse()
  2643. self._rev = self.__class__("".join(L))
  2644. return self._rev
  2645. u = madunicode("ABCDEF")
  2646. self.assertEqual(u, "ABCDEF")
  2647. self.assertEqual(u.rev(), madunicode("FEDCBA"))
  2648. self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
  2649. base = "12345"
  2650. u = madunicode(base)
  2651. self.assertEqual(str(u), base)
  2652. self.assertIs(str(u).__class__, str)
  2653. self.assertEqual(hash(u), hash(base))
  2654. self.assertEqual({u: 1}[base], 1)
  2655. self.assertEqual({base: 1}[u], 1)
  2656. self.assertIs(u.strip().__class__, str)
  2657. self.assertEqual(u.strip(), base)
  2658. self.assertIs(u.lstrip().__class__, str)
  2659. self.assertEqual(u.lstrip(), base)
  2660. self.assertIs(u.rstrip().__class__, str)
  2661. self.assertEqual(u.rstrip(), base)
  2662. self.assertIs(u.replace("x", "x").__class__, str)
  2663. self.assertEqual(u.replace("x", "x"), base)
  2664. self.assertIs(u.replace("xy", "xy").__class__, str)
  2665. self.assertEqual(u.replace("xy", "xy"), base)
  2666. self.assertIs(u.center(len(u)).__class__, str)
  2667. self.assertEqual(u.center(len(u)), base)
  2668. self.assertIs(u.ljust(len(u)).__class__, str)
  2669. self.assertEqual(u.ljust(len(u)), base)
  2670. self.assertIs(u.rjust(len(u)).__class__, str)
  2671. self.assertEqual(u.rjust(len(u)), base)
  2672. self.assertIs(u.lower().__class__, str)
  2673. self.assertEqual(u.lower(), base)
  2674. self.assertIs(u.upper().__class__, str)
  2675. self.assertEqual(u.upper(), base)
  2676. self.assertIs(u.capitalize().__class__, str)
  2677. self.assertEqual(u.capitalize(), base)
  2678. self.assertIs(u.title().__class__, str)
  2679. self.assertEqual(u.title(), base)
  2680. self.assertIs((u + "").__class__, str)
  2681. self.assertEqual(u + "", base)
  2682. self.assertIs(("" + u).__class__, str)
  2683. self.assertEqual("" + u, base)
  2684. self.assertIs((u * 0).__class__, str)
  2685. self.assertEqual(u * 0, "")
  2686. self.assertIs((u * 1).__class__, str)
  2687. self.assertEqual(u * 1, base)
  2688. self.assertIs((u * 2).__class__, str)
  2689. self.assertEqual(u * 2, base + base)
  2690. self.assertIs(u[:].__class__, str)
  2691. self.assertEqual(u[:], base)
  2692. self.assertIs(u[0:0].__class__, str)
  2693. self.assertEqual(u[0:0], "")
  2694. class sublist(list):
  2695. pass
  2696. a = sublist(range(5))
  2697. self.assertEqual(a, list(range(5)))
  2698. a.append("hello")
  2699. self.assertEqual(a, list(range(5)) + ["hello"])
  2700. a[5] = 5
  2701. self.assertEqual(a, list(range(6)))
  2702. a.extend(range(6, 20))
  2703. self.assertEqual(a, list(range(20)))
  2704. a[-5:] = []
  2705. self.assertEqual(a, list(range(15)))
  2706. del a[10:15]
  2707. self.assertEqual(len(a), 10)
  2708. self.assertEqual(a, list(range(10)))
  2709. self.assertEqual(list(a), list(range(10)))
  2710. self.assertEqual(a[0], 0)
  2711. self.assertEqual(a[9], 9)
  2712. self.assertEqual(a[-10], 0)
  2713. self.assertEqual(a[-1], 9)
  2714. self.assertEqual(a[:5], list(range(5)))
  2715. ## class CountedInput(file):
  2716. ## """Counts lines read by self.readline().
  2717. ##
  2718. ## self.lineno is the 0-based ordinal of the last line read, up to
  2719. ## a maximum of one greater than the number of lines in the file.
  2720. ##
  2721. ## self.ateof is true if and only if the final "" line has been read,
  2722. ## at which point self.lineno stops incrementing, and further calls
  2723. ## to readline() continue to return "".
  2724. ## """
  2725. ##
  2726. ## lineno = 0
  2727. ## ateof = 0
  2728. ## def readline(self):
  2729. ## if self.ateof:
  2730. ## return ""
  2731. ## s = file.readline(self)
  2732. ## # Next line works too.
  2733. ## # s = super(CountedInput, self).readline()
  2734. ## self.lineno += 1
  2735. ## if s == "":
  2736. ## self.ateof = 1
  2737. ## return s
  2738. ##
  2739. ## f = file(name=os_helper.TESTFN, mode='w')
  2740. ## lines = ['a\n', 'b\n', 'c\n']
  2741. ## try:
  2742. ## f.writelines(lines)
  2743. ## f.close()
  2744. ## f = CountedInput(os_helper.TESTFN)
  2745. ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
  2746. ## got = f.readline()
  2747. ## self.assertEqual(expected, got)
  2748. ## self.assertEqual(f.lineno, i)
  2749. ## self.assertEqual(f.ateof, (i > len(lines)))
  2750. ## f.close()
  2751. ## finally:
  2752. ## try:
  2753. ## f.close()
  2754. ## except:
  2755. ## pass
  2756. ## os_helper.unlink(os_helper.TESTFN)
  2757. def test_keywords(self):
  2758. # Testing keyword args to basic type constructors ...
  2759. with self.assertRaisesRegex(TypeError, 'keyword argument'):
  2760. int(x=1)
  2761. with self.assertRaisesRegex(TypeError, 'keyword argument'):
  2762. float(x=2)
  2763. with self.assertRaisesRegex(TypeError, 'keyword argument'):
  2764. bool(x=2)
  2765. self.assertEqual(complex(imag=42, real=666), complex(666, 42))
  2766. self.assertEqual(str(object=500), '500')
  2767. self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
  2768. with self.assertRaisesRegex(TypeError, 'keyword argument'):
  2769. tuple(sequence=range(3))
  2770. with self.assertRaisesRegex(TypeError, 'keyword argument'):
  2771. list(sequence=(0, 1, 2))
  2772. # note: as of Python 2.3, dict() no longer has an "items" keyword arg
  2773. for constructor in (int, float, int, complex, str, str,
  2774. tuple, list):
  2775. try:
  2776. constructor(bogus_keyword_arg=1)
  2777. except TypeError:
  2778. pass
  2779. else:
  2780. self.fail("expected TypeError from bogus keyword argument to %r"
  2781. % constructor)
  2782. def test_str_subclass_as_dict_key(self):
  2783. # Testing a str subclass used as dict key ..
  2784. class cistr(str):
  2785. """Subclass of str that computes __eq__ case-insensitively.
  2786. Also computes a hash code of the string in canonical form.
  2787. """
  2788. def __init__(self, value):
  2789. self.canonical = value.lower()
  2790. self.hashcode = hash(self.canonical)
  2791. def __eq__(self, other):
  2792. if not isinstance(other, cistr):
  2793. other = cistr(other)
  2794. return self.canonical == other.canonical
  2795. def __hash__(self):
  2796. return self.hashcode
  2797. self.assertEqual(cistr('ABC'), 'abc')
  2798. self.assertEqual('aBc', cistr('ABC'))
  2799. self.assertEqual(str(cistr('ABC')), 'ABC')
  2800. d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
  2801. self.assertEqual(d[cistr('one')], 1)
  2802. self.assertEqual(d[cistr('tWo')], 2)
  2803. self.assertEqual(d[cistr('THrEE')], 3)
  2804. self.assertIn(cistr('ONe'), d)
  2805. self.assertEqual(d.get(cistr('thrEE')), 3)
  2806. def test_classic_comparisons(self):
  2807. # Testing classic comparisons...
  2808. class classic:
  2809. pass
  2810. for base in (classic, int, object):
  2811. class C(base):
  2812. def __init__(self, value):
  2813. self.value = int(value)
  2814. def __eq__(self, other):
  2815. if isinstance(other, C):
  2816. return self.value == other.value
  2817. if isinstance(other, int) or isinstance(other, int):
  2818. return self.value == other
  2819. return NotImplemented
  2820. def __ne__(self, other):
  2821. if isinstance(other, C):
  2822. return self.value != other.value
  2823. if isinstance(other, int) or isinstance(other, int):
  2824. return self.value != other
  2825. return NotImplemented
  2826. def __lt__(self, other):
  2827. if isinstance(other, C):
  2828. return self.value < other.value
  2829. if isinstance(other, int) or isinstance(other, int):
  2830. return self.value < other
  2831. return NotImplemented
  2832. def __le__(self, other):
  2833. if isinstance(other, C):
  2834. return self.value <= other.value
  2835. if isinstance(other, int) or isinstance(other, int):
  2836. return self.value <= other
  2837. return NotImplemented
  2838. def __gt__(self, other):
  2839. if isinstance(other, C):
  2840. return self.value > other.value
  2841. if isinstance(other, int) or isinstance(other, int):
  2842. return self.value > other
  2843. return NotImplemented
  2844. def __ge__(self, other):
  2845. if isinstance(other, C):
  2846. return self.value >= other.value
  2847. if isinstance(other, int) or isinstance(other, int):
  2848. return self.value >= other
  2849. return NotImplemented
  2850. c1 = C(1)
  2851. c2 = C(2)
  2852. c3 = C(3)
  2853. self.assertEqual(c1, 1)
  2854. c = {1: c1, 2: c2, 3: c3}
  2855. for x in 1, 2, 3:
  2856. for y in 1, 2, 3:
  2857. for op in "<", "<=", "==", "!=", ">", ">=":
  2858. self.assertEqual(eval("c[x] %s c[y]" % op),
  2859. eval("x %s y" % op),
  2860. "x=%d, y=%d" % (x, y))
  2861. self.assertEqual(eval("c[x] %s y" % op),
  2862. eval("x %s y" % op),
  2863. "x=%d, y=%d" % (x, y))
  2864. self.assertEqual(eval("x %s c[y]" % op),
  2865. eval("x %s y" % op),
  2866. "x=%d, y=%d" % (x, y))
  2867. def test_rich_comparisons(self):
  2868. # Testing rich comparisons...
  2869. class Z(complex):
  2870. pass
  2871. z = Z(1)
  2872. self.assertEqual(z, 1+0j)
  2873. self.assertEqual(1+0j, z)
  2874. class ZZ(complex):
  2875. def __eq__(self, other):
  2876. try:
  2877. return abs(self - other) <= 1e-6
  2878. except:
  2879. return NotImplemented
  2880. zz = ZZ(1.0000003)
  2881. self.assertEqual(zz, 1+0j)
  2882. self.assertEqual(1+0j, zz)
  2883. class classic:
  2884. pass
  2885. for base in (classic, int, object, list):
  2886. class C(base):
  2887. def __init__(self, value):
  2888. self.value = int(value)
  2889. def __cmp__(self_, other):
  2890. self.fail("shouldn't call __cmp__")
  2891. def __eq__(self, other):
  2892. if isinstance(other, C):
  2893. return self.value == other.value
  2894. if isinstance(other, int) or isinstance(other, int):
  2895. return self.value == other
  2896. return NotImplemented
  2897. def __ne__(self, other):
  2898. if isinstance(other, C):
  2899. return self.value != other.value
  2900. if isinstance(other, int) or isinstance(other, int):
  2901. return self.value != other
  2902. return NotImplemented
  2903. def __lt__(self, other):
  2904. if isinstance(other, C):
  2905. return self.value < other.value
  2906. if isinstance(other, int) or isinstance(other, int):
  2907. return self.value < other
  2908. return NotImplemented
  2909. def __le__(self, other):
  2910. if isinstance(other, C):
  2911. return self.value <= other.value
  2912. if isinstance(other, int) or isinstance(other, int):
  2913. return self.value <= other
  2914. return NotImplemented
  2915. def __gt__(self, other):
  2916. if isinstance(other, C):
  2917. return self.value > other.value
  2918. if isinstance(other, int) or isinstance(other, int):
  2919. return self.value > other
  2920. return NotImplemented
  2921. def __ge__(self, other):
  2922. if isinstance(other, C):
  2923. return self.value >= other.value
  2924. if isinstance(other, int) or isinstance(other, int):
  2925. return self.value >= other
  2926. return NotImplemented
  2927. c1 = C(1)
  2928. c2 = C(2)
  2929. c3 = C(3)
  2930. self.assertEqual(c1, 1)
  2931. c = {1: c1, 2: c2, 3: c3}
  2932. for x in 1, 2, 3:
  2933. for y in 1, 2, 3:
  2934. for op in "<", "<=", "==", "!=", ">", ">=":
  2935. self.assertEqual(eval("c[x] %s c[y]" % op),
  2936. eval("x %s y" % op),
  2937. "x=%d, y=%d" % (x, y))
  2938. self.assertEqual(eval("c[x] %s y" % op),
  2939. eval("x %s y" % op),
  2940. "x=%d, y=%d" % (x, y))
  2941. self.assertEqual(eval("x %s c[y]" % op),
  2942. eval("x %s y" % op),
  2943. "x=%d, y=%d" % (x, y))
  2944. def test_descrdoc(self):
  2945. # Testing descriptor doc strings...
  2946. from _io import FileIO
  2947. def check(descr, what):
  2948. self.assertEqual(descr.__doc__, what)
  2949. check(FileIO.closed, "True if the file is closed") # getset descriptor
  2950. check(complex.real, "the real part of a complex number") # member descriptor
  2951. def test_doc_descriptor(self):
  2952. # Testing __doc__ descriptor...
  2953. # SF bug 542984
  2954. class DocDescr(object):
  2955. def __get__(self, object, otype):
  2956. if object:
  2957. object = object.__class__.__name__ + ' instance'
  2958. if otype:
  2959. otype = otype.__name__
  2960. return 'object=%s; type=%s' % (object, otype)
  2961. class OldClass:
  2962. __doc__ = DocDescr()
  2963. class NewClass(object):
  2964. __doc__ = DocDescr()
  2965. self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
  2966. self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
  2967. self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
  2968. self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
  2969. def test_set_class(self):
  2970. # Testing __class__ assignment...
  2971. class C(object): pass
  2972. class D(object): pass
  2973. class E(object): pass
  2974. class F(D, E): pass
  2975. for cls in C, D, E, F:
  2976. for cls2 in C, D, E, F:
  2977. x = cls()
  2978. x.__class__ = cls2
  2979. self.assertIs(x.__class__, cls2)
  2980. x.__class__ = cls
  2981. self.assertIs(x.__class__, cls)
  2982. def cant(x, C):
  2983. try:
  2984. x.__class__ = C
  2985. except TypeError:
  2986. pass
  2987. else:
  2988. self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
  2989. try:
  2990. delattr(x, "__class__")
  2991. except (TypeError, AttributeError):
  2992. pass
  2993. else:
  2994. self.fail("shouldn't allow del %r.__class__" % x)
  2995. cant(C(), list)
  2996. cant(list(), C)
  2997. cant(C(), 1)
  2998. cant(C(), object)
  2999. cant(object(), list)
  3000. cant(list(), object)
  3001. class Int(int): __slots__ = []
  3002. cant(True, int)
  3003. cant(2, bool)
  3004. o = object()
  3005. cant(o, type(1))
  3006. cant(o, type(None))
  3007. del o
  3008. class G(object):
  3009. __slots__ = ["a", "b"]
  3010. class H(object):
  3011. __slots__ = ["b", "a"]
  3012. class I(object):
  3013. __slots__ = ["a", "b"]
  3014. class J(object):
  3015. __slots__ = ["c", "b"]
  3016. class K(object):
  3017. __slots__ = ["a", "b", "d"]
  3018. class L(H):
  3019. __slots__ = ["e"]
  3020. class M(I):
  3021. __slots__ = ["e"]
  3022. class N(J):
  3023. __slots__ = ["__weakref__"]
  3024. class P(J):
  3025. __slots__ = ["__dict__"]
  3026. class Q(J):
  3027. pass
  3028. class R(J):
  3029. __slots__ = ["__dict__", "__weakref__"]
  3030. for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
  3031. x = cls()
  3032. x.a = 1
  3033. x.__class__ = cls2
  3034. self.assertIs(x.__class__, cls2,
  3035. "assigning %r as __class__ for %r silently failed" % (cls2, x))
  3036. self.assertEqual(x.a, 1)
  3037. x.__class__ = cls
  3038. self.assertIs(x.__class__, cls,
  3039. "assigning %r as __class__ for %r silently failed" % (cls, x))
  3040. self.assertEqual(x.a, 1)
  3041. for cls in G, J, K, L, M, N, P, R, list, Int:
  3042. for cls2 in G, J, K, L, M, N, P, R, list, Int:
  3043. if cls is cls2:
  3044. continue
  3045. cant(cls(), cls2)
  3046. # Issue5283: when __class__ changes in __del__, the wrong
  3047. # type gets DECREF'd.
  3048. class O(object):
  3049. pass
  3050. class A(object):
  3051. def __del__(self):
  3052. self.__class__ = O
  3053. l = [A() for x in range(100)]
  3054. del l
  3055. def test_set_dict(self):
  3056. # Testing __dict__ assignment...
  3057. class C(object): pass
  3058. a = C()
  3059. a.__dict__ = {'b': 1}
  3060. self.assertEqual(a.b, 1)
  3061. def cant(x, dict):
  3062. try:
  3063. x.__dict__ = dict
  3064. except (AttributeError, TypeError):
  3065. pass
  3066. else:
  3067. self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
  3068. cant(a, None)
  3069. cant(a, [])
  3070. cant(a, 1)
  3071. del a.__dict__ # Deleting __dict__ is allowed
  3072. class Base(object):
  3073. pass
  3074. def verify_dict_readonly(x):
  3075. """
  3076. x has to be an instance of a class inheriting from Base.
  3077. """
  3078. cant(x, {})
  3079. try:
  3080. del x.__dict__
  3081. except (AttributeError, TypeError):
  3082. pass
  3083. else:
  3084. self.fail("shouldn't allow del %r.__dict__" % x)
  3085. dict_descr = Base.__dict__["__dict__"]
  3086. try:
  3087. dict_descr.__set__(x, {})
  3088. except (AttributeError, TypeError):
  3089. pass
  3090. else:
  3091. self.fail("dict_descr allowed access to %r's dict" % x)
  3092. # Classes don't allow __dict__ assignment and have readonly dicts
  3093. class Meta1(type, Base):
  3094. pass
  3095. class Meta2(Base, type):
  3096. pass
  3097. class D(object, metaclass=Meta1):
  3098. pass
  3099. class E(object, metaclass=Meta2):
  3100. pass
  3101. for cls in C, D, E:
  3102. verify_dict_readonly(cls)
  3103. class_dict = cls.__dict__
  3104. try:
  3105. class_dict["spam"] = "eggs"
  3106. except TypeError:
  3107. pass
  3108. else:
  3109. self.fail("%r's __dict__ can be modified" % cls)
  3110. # Modules also disallow __dict__ assignment
  3111. class Module1(types.ModuleType, Base):
  3112. pass
  3113. class Module2(Base, types.ModuleType):
  3114. pass
  3115. for ModuleType in Module1, Module2:
  3116. mod = ModuleType("spam")
  3117. verify_dict_readonly(mod)
  3118. mod.__dict__["spam"] = "eggs"
  3119. # Exception's __dict__ can be replaced, but not deleted
  3120. # (at least not any more than regular exception's __dict__ can
  3121. # be deleted; on CPython it is not the case, whereas on PyPy they
  3122. # can, just like any other new-style instance's __dict__.)
  3123. def can_delete_dict(e):
  3124. try:
  3125. del e.__dict__
  3126. except (TypeError, AttributeError):
  3127. return False
  3128. else:
  3129. return True
  3130. class Exception1(Exception, Base):
  3131. pass
  3132. class Exception2(Base, Exception):
  3133. pass
  3134. for ExceptionType in Exception, Exception1, Exception2:
  3135. e = ExceptionType()
  3136. e.__dict__ = {"a": 1}
  3137. self.assertEqual(e.a, 1)
  3138. self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
  3139. def test_binary_operator_override(self):
  3140. # Testing overrides of binary operations...
  3141. class I(int):
  3142. def __repr__(self):
  3143. return "I(%r)" % int(self)
  3144. def __add__(self, other):
  3145. return I(int(self) + int(other))
  3146. __radd__ = __add__
  3147. def __pow__(self, other, mod=None):
  3148. if mod is None:
  3149. return I(pow(int(self), int(other)))
  3150. else:
  3151. return I(pow(int(self), int(other), int(mod)))
  3152. def __rpow__(self, other, mod=None):
  3153. if mod is None:
  3154. return I(pow(int(other), int(self), mod))
  3155. else:
  3156. return I(pow(int(other), int(self), int(mod)))
  3157. self.assertEqual(repr(I(1) + I(2)), "I(3)")
  3158. self.assertEqual(repr(I(1) + 2), "I(3)")
  3159. self.assertEqual(repr(1 + I(2)), "I(3)")
  3160. self.assertEqual(repr(I(2) ** I(3)), "I(8)")
  3161. self.assertEqual(repr(2 ** I(3)), "I(8)")
  3162. self.assertEqual(repr(I(2) ** 3), "I(8)")
  3163. self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
  3164. class S(str):
  3165. def __eq__(self, other):
  3166. return self.lower() == other.lower()
  3167. def test_subclass_propagation(self):
  3168. # Testing propagation of slot functions to subclasses...
  3169. class A(object):
  3170. pass
  3171. class B(A):
  3172. pass
  3173. class C(A):
  3174. pass
  3175. class D(B, C):
  3176. pass
  3177. d = D()
  3178. orig_hash = hash(d) # related to id(d) in platform-dependent ways
  3179. A.__hash__ = lambda self: 42
  3180. self.assertEqual(hash(d), 42)
  3181. C.__hash__ = lambda self: 314
  3182. self.assertEqual(hash(d), 314)
  3183. B.__hash__ = lambda self: 144
  3184. self.assertEqual(hash(d), 144)
  3185. D.__hash__ = lambda self: 100
  3186. self.assertEqual(hash(d), 100)
  3187. D.__hash__ = None
  3188. self.assertRaises(TypeError, hash, d)
  3189. del D.__hash__
  3190. self.assertEqual(hash(d), 144)
  3191. B.__hash__ = None
  3192. self.assertRaises(TypeError, hash, d)
  3193. del B.__hash__
  3194. self.assertEqual(hash(d), 314)
  3195. C.__hash__ = None
  3196. self.assertRaises(TypeError, hash, d)
  3197. del C.__hash__
  3198. self.assertEqual(hash(d), 42)
  3199. A.__hash__ = None
  3200. self.assertRaises(TypeError, hash, d)
  3201. del A.__hash__
  3202. self.assertEqual(hash(d), orig_hash)
  3203. d.foo = 42
  3204. d.bar = 42
  3205. self.assertEqual(d.foo, 42)
  3206. self.assertEqual(d.bar, 42)
  3207. def __getattribute__(self, name):
  3208. if name == "foo":
  3209. return 24
  3210. return object.__getattribute__(self, name)
  3211. A.__getattribute__ = __getattribute__
  3212. self.assertEqual(d.foo, 24)
  3213. self.assertEqual(d.bar, 42)
  3214. def __getattr__(self, name):
  3215. if name in ("spam", "foo", "bar"):
  3216. return "hello"
  3217. raise AttributeError(name)
  3218. B.__getattr__ = __getattr__
  3219. self.assertEqual(d.spam, "hello")
  3220. self.assertEqual(d.foo, 24)
  3221. self.assertEqual(d.bar, 42)
  3222. del A.__getattribute__
  3223. self.assertEqual(d.foo, 42)
  3224. del d.foo
  3225. self.assertEqual(d.foo, "hello")
  3226. self.assertEqual(d.bar, 42)
  3227. del B.__getattr__
  3228. try:
  3229. d.foo
  3230. except AttributeError:
  3231. pass
  3232. else:
  3233. self.fail("d.foo should be undefined now")
  3234. # Test a nasty bug in recurse_down_subclasses()
  3235. class A(object):
  3236. pass
  3237. class B(A):
  3238. pass
  3239. del B
  3240. support.gc_collect()
  3241. A.__setitem__ = lambda *a: None # crash
  3242. def test_buffer_inheritance(self):
  3243. # Testing that buffer interface is inherited ...
  3244. import binascii
  3245. # SF bug [#470040] ParseTuple t# vs subclasses.
  3246. class MyBytes(bytes):
  3247. pass
  3248. base = b'abc'
  3249. m = MyBytes(base)
  3250. # b2a_hex uses the buffer interface to get its argument's value, via
  3251. # PyArg_ParseTuple 't#' code.
  3252. self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
  3253. class MyInt(int):
  3254. pass
  3255. m = MyInt(42)
  3256. try:
  3257. binascii.b2a_hex(m)
  3258. self.fail('subclass of int should not have a buffer interface')
  3259. except TypeError:
  3260. pass
  3261. def test_str_of_str_subclass(self):
  3262. # Testing __str__ defined in subclass of str ...
  3263. import binascii
  3264. import io
  3265. class octetstring(str):
  3266. def __str__(self):
  3267. return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
  3268. def __repr__(self):
  3269. return self + " repr"
  3270. o = octetstring('A')
  3271. self.assertEqual(type(o), octetstring)
  3272. self.assertEqual(type(str(o)), str)
  3273. self.assertEqual(type(repr(o)), str)
  3274. self.assertEqual(ord(o), 0x41)
  3275. self.assertEqual(str(o), '41')
  3276. self.assertEqual(repr(o), 'A repr')
  3277. self.assertEqual(o.__str__(), '41')
  3278. self.assertEqual(o.__repr__(), 'A repr')
  3279. def test_repr_with_module_str_subclass(self):
  3280. # gh-98783
  3281. class StrSub(str):
  3282. pass
  3283. class Some:
  3284. pass
  3285. Some.__module__ = StrSub('example')
  3286. self.assertIsInstance(repr(Some), str) # should not crash
  3287. self.assertIsInstance(repr(Some()), str) # should not crash
  3288. def test_keyword_arguments(self):
  3289. # Testing keyword arguments to __init__, __call__...
  3290. def f(a): return a
  3291. self.assertEqual(f.__call__(a=42), 42)
  3292. ba = bytearray()
  3293. bytearray.__init__(ba, 'abc\xbd\u20ac',
  3294. encoding='latin1', errors='replace')
  3295. self.assertEqual(ba, b'abc\xbd?')
  3296. def test_recursive_call(self):
  3297. # Testing recursive __call__() by setting to instance of class...
  3298. class A(object):
  3299. pass
  3300. A.__call__ = A()
  3301. with self.assertRaises(RecursionError):
  3302. A()()
  3303. def test_delete_hook(self):
  3304. # Testing __del__ hook...
  3305. log = []
  3306. class C(object):
  3307. def __del__(self):
  3308. log.append(1)
  3309. c = C()
  3310. self.assertEqual(log, [])
  3311. del c
  3312. support.gc_collect()
  3313. self.assertEqual(log, [1])
  3314. class D(object): pass
  3315. d = D()
  3316. try: del d[0]
  3317. except TypeError: pass
  3318. else: self.fail("invalid del() didn't raise TypeError")
  3319. def test_hash_inheritance(self):
  3320. # Testing hash of mutable subclasses...
  3321. class mydict(dict):
  3322. pass
  3323. d = mydict()
  3324. try:
  3325. hash(d)
  3326. except TypeError:
  3327. pass
  3328. else:
  3329. self.fail("hash() of dict subclass should fail")
  3330. class mylist(list):
  3331. pass
  3332. d = mylist()
  3333. try:
  3334. hash(d)
  3335. except TypeError:
  3336. pass
  3337. else:
  3338. self.fail("hash() of list subclass should fail")
  3339. def test_str_operations(self):
  3340. try: 'a' + 5
  3341. except TypeError: pass
  3342. else: self.fail("'' + 5 doesn't raise TypeError")
  3343. try: ''.split('')
  3344. except ValueError: pass
  3345. else: self.fail("''.split('') doesn't raise ValueError")
  3346. try: ''.join([0])
  3347. except TypeError: pass
  3348. else: self.fail("''.join([0]) doesn't raise TypeError")
  3349. try: ''.rindex('5')
  3350. except ValueError: pass
  3351. else: self.fail("''.rindex('5') doesn't raise ValueError")
  3352. try: '%(n)s' % None
  3353. except TypeError: pass
  3354. else: self.fail("'%(n)s' % None doesn't raise TypeError")
  3355. try: '%(n' % {}
  3356. except ValueError: pass
  3357. else: self.fail("'%(n' % {} '' doesn't raise ValueError")
  3358. try: '%*s' % ('abc')
  3359. except TypeError: pass
  3360. else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
  3361. try: '%*.*s' % ('abc', 5)
  3362. except TypeError: pass
  3363. else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
  3364. try: '%s' % (1, 2)
  3365. except TypeError: pass
  3366. else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
  3367. try: '%' % None
  3368. except ValueError: pass
  3369. else: self.fail("'%' % None doesn't raise ValueError")
  3370. self.assertEqual('534253'.isdigit(), 1)
  3371. self.assertEqual('534253x'.isdigit(), 0)
  3372. self.assertEqual('%c' % 5, '\x05')
  3373. self.assertEqual('%c' % '5', '5')
  3374. def test_deepcopy_recursive(self):
  3375. # Testing deepcopy of recursive objects...
  3376. class Node:
  3377. pass
  3378. a = Node()
  3379. b = Node()
  3380. a.b = b
  3381. b.a = a
  3382. z = deepcopy(a) # This blew up before
  3383. def test_uninitialized_modules(self):
  3384. # Testing uninitialized module objects...
  3385. from types import ModuleType as M
  3386. m = M.__new__(M)
  3387. str(m)
  3388. self.assertNotHasAttr(m, "__name__")
  3389. self.assertNotHasAttr(m, "__file__")
  3390. self.assertNotHasAttr(m, "foo")
  3391. self.assertFalse(m.__dict__) # None or {} are both reasonable answers
  3392. m.foo = 1
  3393. self.assertEqual(m.__dict__, {"foo": 1})
  3394. def test_funny_new(self):
  3395. # Testing __new__ returning something unexpected...
  3396. class C(object):
  3397. def __new__(cls, arg):
  3398. if isinstance(arg, str): return [1, 2, 3]
  3399. elif isinstance(arg, int): return object.__new__(D)
  3400. else: return object.__new__(cls)
  3401. class D(C):
  3402. def __init__(self, arg):
  3403. self.foo = arg
  3404. self.assertEqual(C("1"), [1, 2, 3])
  3405. self.assertEqual(D("1"), [1, 2, 3])
  3406. d = D(None)
  3407. self.assertEqual(d.foo, None)
  3408. d = C(1)
  3409. self.assertIsInstance(d, D)
  3410. self.assertEqual(d.foo, 1)
  3411. d = D(1)
  3412. self.assertIsInstance(d, D)
  3413. self.assertEqual(d.foo, 1)
  3414. class C(object):
  3415. @staticmethod
  3416. def __new__(*args):
  3417. return args
  3418. self.assertEqual(C(1, 2), (C, 1, 2))
  3419. class D(C):
  3420. pass
  3421. self.assertEqual(D(1, 2), (D, 1, 2))
  3422. class C(object):
  3423. @classmethod
  3424. def __new__(*args):
  3425. return args
  3426. self.assertEqual(C(1, 2), (C, C, 1, 2))
  3427. class D(C):
  3428. pass
  3429. self.assertEqual(D(1, 2), (D, D, 1, 2))
  3430. def test_imul_bug(self):
  3431. # Testing for __imul__ problems...
  3432. # SF bug 544647
  3433. class C(object):
  3434. def __imul__(self, other):
  3435. return (self, other)
  3436. x = C()
  3437. y = x
  3438. y *= 1.0
  3439. self.assertEqual(y, (x, 1.0))
  3440. y = x
  3441. y *= 2
  3442. self.assertEqual(y, (x, 2))
  3443. y = x
  3444. y *= 3
  3445. self.assertEqual(y, (x, 3))
  3446. y = x
  3447. y *= 1<<100
  3448. self.assertEqual(y, (x, 1<<100))
  3449. y = x
  3450. y *= None
  3451. self.assertEqual(y, (x, None))
  3452. y = x
  3453. y *= "foo"
  3454. self.assertEqual(y, (x, "foo"))
  3455. def test_copy_setstate(self):
  3456. # Testing that copy.*copy() correctly uses __setstate__...
  3457. import copy
  3458. class C(object):
  3459. def __init__(self, foo=None):
  3460. self.foo = foo
  3461. self.__foo = foo
  3462. def setfoo(self, foo=None):
  3463. self.foo = foo
  3464. def getfoo(self):
  3465. return self.__foo
  3466. def __getstate__(self):
  3467. return [self.foo]
  3468. def __setstate__(self_, lst):
  3469. self.assertEqual(len(lst), 1)
  3470. self_.__foo = self_.foo = lst[0]
  3471. a = C(42)
  3472. a.setfoo(24)
  3473. self.assertEqual(a.foo, 24)
  3474. self.assertEqual(a.getfoo(), 42)
  3475. b = copy.copy(a)
  3476. self.assertEqual(b.foo, 24)
  3477. self.assertEqual(b.getfoo(), 24)
  3478. b = copy.deepcopy(a)
  3479. self.assertEqual(b.foo, 24)
  3480. self.assertEqual(b.getfoo(), 24)
  3481. def test_slices(self):
  3482. # Testing cases with slices and overridden __getitem__ ...
  3483. # Strings
  3484. self.assertEqual("hello"[:4], "hell")
  3485. self.assertEqual("hello"[slice(4)], "hell")
  3486. self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
  3487. class S(str):
  3488. def __getitem__(self, x):
  3489. return str.__getitem__(self, x)
  3490. self.assertEqual(S("hello")[:4], "hell")
  3491. self.assertEqual(S("hello")[slice(4)], "hell")
  3492. self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
  3493. # Tuples
  3494. self.assertEqual((1,2,3)[:2], (1,2))
  3495. self.assertEqual((1,2,3)[slice(2)], (1,2))
  3496. self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
  3497. class T(tuple):
  3498. def __getitem__(self, x):
  3499. return tuple.__getitem__(self, x)
  3500. self.assertEqual(T((1,2,3))[:2], (1,2))
  3501. self.assertEqual(T((1,2,3))[slice(2)], (1,2))
  3502. self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
  3503. # Lists
  3504. self.assertEqual([1,2,3][:2], [1,2])
  3505. self.assertEqual([1,2,3][slice(2)], [1,2])
  3506. self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
  3507. class L(list):
  3508. def __getitem__(self, x):
  3509. return list.__getitem__(self, x)
  3510. self.assertEqual(L([1,2,3])[:2], [1,2])
  3511. self.assertEqual(L([1,2,3])[slice(2)], [1,2])
  3512. self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
  3513. # Now do lists and __setitem__
  3514. a = L([1,2,3])
  3515. a[slice(1, 3)] = [3,2]
  3516. self.assertEqual(a, [1,3,2])
  3517. a[slice(0, 2, 1)] = [3,1]
  3518. self.assertEqual(a, [3,1,2])
  3519. a.__setitem__(slice(1, 3), [2,1])
  3520. self.assertEqual(a, [3,2,1])
  3521. a.__setitem__(slice(0, 2, 1), [2,3])
  3522. self.assertEqual(a, [2,3,1])
  3523. def test_subtype_resurrection(self):
  3524. # Testing resurrection of new-style instance...
  3525. class C(object):
  3526. container = []
  3527. def __del__(self):
  3528. # resurrect the instance
  3529. C.container.append(self)
  3530. c = C()
  3531. c.attr = 42
  3532. # The most interesting thing here is whether this blows up, due to
  3533. # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
  3534. # bug).
  3535. del c
  3536. support.gc_collect()
  3537. self.assertEqual(len(C.container), 1)
  3538. # Make c mortal again, so that the test framework with -l doesn't report
  3539. # it as a leak.
  3540. del C.__del__
  3541. def test_slots_trash(self):
  3542. # Testing slot trash...
  3543. # Deallocating deeply nested slotted trash caused stack overflows
  3544. class trash(object):
  3545. __slots__ = ['x']
  3546. def __init__(self, x):
  3547. self.x = x
  3548. o = None
  3549. for i in range(50000):
  3550. o = trash(o)
  3551. del o
  3552. def test_slots_multiple_inheritance(self):
  3553. # SF bug 575229, multiple inheritance w/ slots dumps core
  3554. class A(object):
  3555. __slots__=()
  3556. class B(object):
  3557. pass
  3558. class C(A,B) :
  3559. __slots__=()
  3560. if support.check_impl_detail():
  3561. self.assertEqual(C.__basicsize__, B.__basicsize__)
  3562. self.assertHasAttr(C, '__dict__')
  3563. self.assertHasAttr(C, '__weakref__')
  3564. C().x = 2
  3565. def test_rmul(self):
  3566. # Testing correct invocation of __rmul__...
  3567. # SF patch 592646
  3568. class C(object):
  3569. def __mul__(self, other):
  3570. return "mul"
  3571. def __rmul__(self, other):
  3572. return "rmul"
  3573. a = C()
  3574. self.assertEqual(a*2, "mul")
  3575. self.assertEqual(a*2.2, "mul")
  3576. self.assertEqual(2*a, "rmul")
  3577. self.assertEqual(2.2*a, "rmul")
  3578. def test_ipow(self):
  3579. # Testing correct invocation of __ipow__...
  3580. # [SF bug 620179]
  3581. class C(object):
  3582. def __ipow__(self, other):
  3583. pass
  3584. a = C()
  3585. a **= 2
  3586. def test_ipow_returns_not_implemented(self):
  3587. class A:
  3588. def __ipow__(self, other):
  3589. return NotImplemented
  3590. class B(A):
  3591. def __rpow__(self, other):
  3592. return 1
  3593. class C(A):
  3594. def __pow__(self, other):
  3595. return 2
  3596. a = A()
  3597. b = B()
  3598. c = C()
  3599. a **= b
  3600. self.assertEqual(a, 1)
  3601. c **= b
  3602. self.assertEqual(c, 2)
  3603. def test_no_ipow(self):
  3604. class B:
  3605. def __rpow__(self, other):
  3606. return 1
  3607. a = object()
  3608. b = B()
  3609. a **= b
  3610. self.assertEqual(a, 1)
  3611. def test_ipow_exception_text(self):
  3612. x = None
  3613. with self.assertRaises(TypeError) as cm:
  3614. x **= 2
  3615. self.assertIn('unsupported operand type(s) for **=', str(cm.exception))
  3616. with self.assertRaises(TypeError) as cm:
  3617. y = x ** 2
  3618. self.assertIn('unsupported operand type(s) for **', str(cm.exception))
  3619. def test_mutable_bases(self):
  3620. # Testing mutable bases...
  3621. # stuff that should work:
  3622. class C(object):
  3623. pass
  3624. class C2(object):
  3625. def __getattribute__(self, attr):
  3626. if attr == 'a':
  3627. return 2
  3628. else:
  3629. return super(C2, self).__getattribute__(attr)
  3630. def meth(self):
  3631. return 1
  3632. class D(C):
  3633. pass
  3634. class E(D):
  3635. pass
  3636. d = D()
  3637. e = E()
  3638. D.__bases__ = (C,)
  3639. D.__bases__ = (C2,)
  3640. self.assertEqual(d.meth(), 1)
  3641. self.assertEqual(e.meth(), 1)
  3642. self.assertEqual(d.a, 2)
  3643. self.assertEqual(e.a, 2)
  3644. self.assertEqual(C2.__subclasses__(), [D])
  3645. try:
  3646. del D.__bases__
  3647. except (TypeError, AttributeError):
  3648. pass
  3649. else:
  3650. self.fail("shouldn't be able to delete .__bases__")
  3651. try:
  3652. D.__bases__ = ()
  3653. except TypeError as msg:
  3654. if str(msg) == "a new-style class can't have only classic bases":
  3655. self.fail("wrong error message for .__bases__ = ()")
  3656. else:
  3657. self.fail("shouldn't be able to set .__bases__ to ()")
  3658. try:
  3659. D.__bases__ = (D,)
  3660. except TypeError:
  3661. pass
  3662. else:
  3663. # actually, we'll have crashed by here...
  3664. self.fail("shouldn't be able to create inheritance cycles")
  3665. try:
  3666. D.__bases__ = (C, C)
  3667. except TypeError:
  3668. pass
  3669. else:
  3670. self.fail("didn't detect repeated base classes")
  3671. try:
  3672. D.__bases__ = (E,)
  3673. except TypeError:
  3674. pass
  3675. else:
  3676. self.fail("shouldn't be able to create inheritance cycles")
  3677. def test_builtin_bases(self):
  3678. # Make sure all the builtin types can have their base queried without
  3679. # segfaulting. See issue #5787.
  3680. builtin_types = [tp for tp in builtins.__dict__.values()
  3681. if isinstance(tp, type)]
  3682. for tp in builtin_types:
  3683. object.__getattribute__(tp, "__bases__")
  3684. if tp is not object:
  3685. if tp is ExceptionGroup:
  3686. num_bases = 2
  3687. else:
  3688. num_bases = 1
  3689. self.assertEqual(len(tp.__bases__), num_bases, 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. self.fail("best_base calculation found wanting")
  3714. def test_unsubclassable_types(self):
  3715. with self.assertRaises(TypeError):
  3716. class X(type(None)):
  3717. pass
  3718. with self.assertRaises(TypeError):
  3719. class X(object, type(None)):
  3720. pass
  3721. with self.assertRaises(TypeError):
  3722. class X(type(None), object):
  3723. pass
  3724. class O(object):
  3725. pass
  3726. with self.assertRaises(TypeError):
  3727. class X(O, type(None)):
  3728. pass
  3729. with self.assertRaises(TypeError):
  3730. class X(type(None), O):
  3731. pass
  3732. class X(object):
  3733. pass
  3734. with self.assertRaises(TypeError):
  3735. X.__bases__ = type(None),
  3736. with self.assertRaises(TypeError):
  3737. X.__bases__ = object, type(None)
  3738. with self.assertRaises(TypeError):
  3739. X.__bases__ = type(None), object
  3740. with self.assertRaises(TypeError):
  3741. X.__bases__ = O, type(None)
  3742. with self.assertRaises(TypeError):
  3743. X.__bases__ = type(None), 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, metaclass=WorkOnce):
  3772. pass
  3773. class G(D, metaclass=WorkAlways):
  3774. pass
  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:
  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. @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_carloverre_multi_inherit_valid(self):
  3973. class A(type):
  3974. def __setattr__(cls, key, value):
  3975. type.__setattr__(cls, key, value)
  3976. class B:
  3977. pass
  3978. class C(B, A):
  3979. pass
  3980. obj = C('D', (object,), {})
  3981. try:
  3982. obj.test = True
  3983. except TypeError:
  3984. self.fail("setattr through direct base types should be legal")
  3985. def test_carloverre_multi_inherit_invalid(self):
  3986. class A(type):
  3987. def __setattr__(cls, key, value):
  3988. object.__setattr__(cls, key, value) # this should fail!
  3989. class B:
  3990. pass
  3991. class C(B, A):
  3992. pass
  3993. obj = C('D', (object,), {})
  3994. try:
  3995. obj.test = True
  3996. except TypeError:
  3997. pass
  3998. else:
  3999. self.fail("setattr through indirect base types should be rejected")
  4000. def test_weakref_segfault(self):
  4001. # Testing weakref segfault...
  4002. # SF 742911
  4003. import weakref
  4004. class Provoker:
  4005. def __init__(self, referrent):
  4006. self.ref = weakref.ref(referrent)
  4007. def __del__(self):
  4008. x = self.ref()
  4009. class Oops(object):
  4010. pass
  4011. o = Oops()
  4012. o.whatever = Provoker(o)
  4013. del o
  4014. def test_wrapper_segfault(self):
  4015. # SF 927248: deeply nested wrappers could cause stack overflow
  4016. f = lambda:None
  4017. for i in range(1000000):
  4018. f = f.__call__
  4019. f = None
  4020. def test_file_fault(self):
  4021. # Testing sys.stdout is changed in getattr...
  4022. class StdoutGuard:
  4023. def __getattr__(self, attr):
  4024. sys.stdout = sys.__stdout__
  4025. raise RuntimeError(f"Premature access to sys.stdout.{attr}")
  4026. with redirect_stdout(StdoutGuard()):
  4027. with self.assertRaises(RuntimeError):
  4028. print("Oops!")
  4029. def test_vicious_descriptor_nonsense(self):
  4030. # Testing vicious_descriptor_nonsense...
  4031. # A potential segfault spotted by Thomas Wouters in mail to
  4032. # python-dev 2003-04-17, turned into an example & fixed by Michael
  4033. # Hudson just less than four months later...
  4034. class Evil(object):
  4035. def __hash__(self):
  4036. return hash('attr')
  4037. def __eq__(self, other):
  4038. try:
  4039. del C.attr
  4040. except AttributeError:
  4041. # possible race condition
  4042. pass
  4043. return 0
  4044. class Descr(object):
  4045. def __get__(self, ob, type=None):
  4046. return 1
  4047. class C(object):
  4048. attr = Descr()
  4049. c = C()
  4050. c.__dict__[Evil()] = 0
  4051. self.assertEqual(c.attr, 1)
  4052. # this makes a crash more likely:
  4053. support.gc_collect()
  4054. self.assertNotHasAttr(c, 'attr')
  4055. def test_init(self):
  4056. # SF 1155938
  4057. class Foo(object):
  4058. def __init__(self):
  4059. return 10
  4060. try:
  4061. Foo()
  4062. except TypeError:
  4063. pass
  4064. else:
  4065. self.fail("did not test __init__() for None return")
  4066. def assertNotOrderable(self, a, b):
  4067. with self.assertRaises(TypeError):
  4068. a < b
  4069. with self.assertRaises(TypeError):
  4070. a > b
  4071. with self.assertRaises(TypeError):
  4072. a <= b
  4073. with self.assertRaises(TypeError):
  4074. a >= b
  4075. def test_method_wrapper(self):
  4076. # Testing method-wrapper objects...
  4077. # <type 'method-wrapper'> did not support any reflection before 2.5
  4078. l = []
  4079. self.assertTrue(l.__add__ == l.__add__)
  4080. self.assertFalse(l.__add__ != l.__add__)
  4081. self.assertFalse(l.__add__ == [].__add__)
  4082. self.assertTrue(l.__add__ != [].__add__)
  4083. self.assertFalse(l.__add__ == l.__mul__)
  4084. self.assertTrue(l.__add__ != l.__mul__)
  4085. self.assertNotOrderable(l.__add__, l.__add__)
  4086. self.assertEqual(l.__add__.__name__, '__add__')
  4087. self.assertIs(l.__add__.__self__, l)
  4088. self.assertIs(l.__add__.__objclass__, list)
  4089. self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
  4090. # hash([].__add__) should not be based on hash([])
  4091. hash(l.__add__)
  4092. def test_builtin_function_or_method(self):
  4093. # Not really belonging to test_descr, but introspection and
  4094. # comparison on <type 'builtin_function_or_method'> seems not
  4095. # to be tested elsewhere
  4096. l = []
  4097. self.assertTrue(l.append == l.append)
  4098. self.assertFalse(l.append != l.append)
  4099. self.assertFalse(l.append == [].append)
  4100. self.assertTrue(l.append != [].append)
  4101. self.assertFalse(l.append == l.pop)
  4102. self.assertTrue(l.append != l.pop)
  4103. self.assertNotOrderable(l.append, l.append)
  4104. self.assertEqual(l.append.__name__, 'append')
  4105. self.assertIs(l.append.__self__, l)
  4106. # self.assertIs(l.append.__objclass__, list) --- could be added?
  4107. self.assertEqual(l.append.__doc__, list.append.__doc__)
  4108. # hash([].append) should not be based on hash([])
  4109. hash(l.append)
  4110. def test_special_unbound_method_types(self):
  4111. # Testing objects of <type 'wrapper_descriptor'>...
  4112. self.assertTrue(list.__add__ == list.__add__)
  4113. self.assertFalse(list.__add__ != list.__add__)
  4114. self.assertFalse(list.__add__ == list.__mul__)
  4115. self.assertTrue(list.__add__ != list.__mul__)
  4116. self.assertNotOrderable(list.__add__, list.__add__)
  4117. self.assertEqual(list.__add__.__name__, '__add__')
  4118. self.assertIs(list.__add__.__objclass__, list)
  4119. # Testing objects of <type 'method_descriptor'>...
  4120. self.assertTrue(list.append == list.append)
  4121. self.assertFalse(list.append != list.append)
  4122. self.assertFalse(list.append == list.pop)
  4123. self.assertTrue(list.append != list.pop)
  4124. self.assertNotOrderable(list.append, list.append)
  4125. self.assertEqual(list.append.__name__, 'append')
  4126. self.assertIs(list.append.__objclass__, list)
  4127. def test_not_implemented(self):
  4128. # Testing NotImplemented...
  4129. # all binary methods should be able to return a NotImplemented
  4130. import operator
  4131. def specialmethod(self, other):
  4132. return NotImplemented
  4133. def check(expr, x, y):
  4134. try:
  4135. exec(expr, {'x': x, 'y': y, 'operator': operator})
  4136. except TypeError:
  4137. pass
  4138. else:
  4139. self.fail("no TypeError from %r" % (expr,))
  4140. N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
  4141. # TypeErrors
  4142. N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
  4143. # ValueErrors instead of TypeErrors
  4144. for name, expr, iexpr in [
  4145. ('__add__', 'x + y', 'x += y'),
  4146. ('__sub__', 'x - y', 'x -= y'),
  4147. ('__mul__', 'x * y', 'x *= y'),
  4148. ('__matmul__', 'x @ y', 'x @= y'),
  4149. ('__truediv__', 'x / y', 'x /= y'),
  4150. ('__floordiv__', 'x // y', 'x //= y'),
  4151. ('__mod__', 'x % y', 'x %= y'),
  4152. ('__divmod__', 'divmod(x, y)', None),
  4153. ('__pow__', 'x ** y', 'x **= y'),
  4154. ('__lshift__', 'x << y', 'x <<= y'),
  4155. ('__rshift__', 'x >> y', 'x >>= y'),
  4156. ('__and__', 'x & y', 'x &= y'),
  4157. ('__or__', 'x | y', 'x |= y'),
  4158. ('__xor__', 'x ^ y', 'x ^= y')]:
  4159. rname = '__r' + name[2:]
  4160. A = type('A', (), {name: specialmethod})
  4161. a = A()
  4162. check(expr, a, a)
  4163. check(expr, a, N1)
  4164. check(expr, a, N2)
  4165. if iexpr:
  4166. check(iexpr, a, a)
  4167. check(iexpr, a, N1)
  4168. check(iexpr, a, N2)
  4169. iname = '__i' + name[2:]
  4170. C = type('C', (), {iname: specialmethod})
  4171. c = C()
  4172. check(iexpr, c, a)
  4173. check(iexpr, c, N1)
  4174. check(iexpr, c, N2)
  4175. def test_assign_slice(self):
  4176. # ceval.c's assign_slice used to check for
  4177. # tp->tp_as_sequence->sq_slice instead of
  4178. # tp->tp_as_sequence->sq_ass_slice
  4179. class C(object):
  4180. def __setitem__(self, idx, value):
  4181. self.value = value
  4182. c = C()
  4183. c[1:2] = 3
  4184. self.assertEqual(c.value, 3)
  4185. def test_set_and_no_get(self):
  4186. # See
  4187. # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
  4188. class Descr(object):
  4189. def __init__(self, name):
  4190. self.name = name
  4191. def __set__(self, obj, value):
  4192. obj.__dict__[self.name] = value
  4193. descr = Descr("a")
  4194. class X(object):
  4195. a = descr
  4196. x = X()
  4197. self.assertIs(x.a, descr)
  4198. x.a = 42
  4199. self.assertEqual(x.a, 42)
  4200. # Also check type_getattro for correctness.
  4201. class Meta(type):
  4202. pass
  4203. class X(metaclass=Meta):
  4204. pass
  4205. X.a = 42
  4206. Meta.a = Descr("a")
  4207. self.assertEqual(X.a, 42)
  4208. def test_getattr_hooks(self):
  4209. # issue 4230
  4210. class Descriptor(object):
  4211. counter = 0
  4212. def __get__(self, obj, objtype=None):
  4213. def getter(name):
  4214. self.counter += 1
  4215. raise AttributeError(name)
  4216. return getter
  4217. descr = Descriptor()
  4218. class A(object):
  4219. __getattribute__ = descr
  4220. class B(object):
  4221. __getattr__ = descr
  4222. class C(object):
  4223. __getattribute__ = descr
  4224. __getattr__ = descr
  4225. self.assertRaises(AttributeError, getattr, A(), "attr")
  4226. self.assertEqual(descr.counter, 1)
  4227. self.assertRaises(AttributeError, getattr, B(), "attr")
  4228. self.assertEqual(descr.counter, 2)
  4229. self.assertRaises(AttributeError, getattr, C(), "attr")
  4230. self.assertEqual(descr.counter, 4)
  4231. class EvilGetattribute(object):
  4232. # This used to segfault
  4233. def __getattr__(self, name):
  4234. raise AttributeError(name)
  4235. def __getattribute__(self, name):
  4236. del EvilGetattribute.__getattr__
  4237. for i in range(5):
  4238. gc.collect()
  4239. raise AttributeError(name)
  4240. self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
  4241. def test_type___getattribute__(self):
  4242. self.assertRaises(TypeError, type.__getattribute__, list, type)
  4243. def test_abstractmethods(self):
  4244. # type pretends not to have __abstractmethods__.
  4245. self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
  4246. class meta(type):
  4247. pass
  4248. self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
  4249. class X(object):
  4250. pass
  4251. with self.assertRaises(AttributeError):
  4252. del X.__abstractmethods__
  4253. def test_proxy_call(self):
  4254. class FakeStr:
  4255. __class__ = str
  4256. fake_str = FakeStr()
  4257. # isinstance() reads __class__
  4258. self.assertIsInstance(fake_str, str)
  4259. # call a method descriptor
  4260. with self.assertRaises(TypeError):
  4261. str.split(fake_str)
  4262. # call a slot wrapper descriptor
  4263. with self.assertRaises(TypeError):
  4264. str.__add__(fake_str, "abc")
  4265. def test_specialized_method_calls_check_types(self):
  4266. # https://github.com/python/cpython/issues/92063
  4267. class Thing:
  4268. pass
  4269. thing = Thing()
  4270. for i in range(20):
  4271. with self.assertRaises(TypeError):
  4272. # PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS
  4273. list.sort(thing)
  4274. for i in range(20):
  4275. with self.assertRaises(TypeError):
  4276. # PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS
  4277. str.split(thing)
  4278. for i in range(20):
  4279. with self.assertRaises(TypeError):
  4280. # PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS
  4281. str.upper(thing)
  4282. for i in range(20):
  4283. with self.assertRaises(TypeError):
  4284. # PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST
  4285. str.strip(thing)
  4286. from collections import deque
  4287. for i in range(20):
  4288. with self.assertRaises(TypeError):
  4289. # PRECALL_NO_KW_METHOD_DESCRIPTOR_O
  4290. deque.append(thing, thing)
  4291. def test_repr_as_str(self):
  4292. # Issue #11603: crash or infinite loop when rebinding __str__ as
  4293. # __repr__.
  4294. class Foo:
  4295. pass
  4296. Foo.__repr__ = Foo.__str__
  4297. foo = Foo()
  4298. self.assertRaises(RecursionError, str, foo)
  4299. self.assertRaises(RecursionError, repr, foo)
  4300. def test_mixing_slot_wrappers(self):
  4301. class X(dict):
  4302. __setattr__ = dict.__setitem__
  4303. __neg__ = dict.copy
  4304. x = X()
  4305. x.y = 42
  4306. self.assertEqual(x["y"], 42)
  4307. self.assertEqual(x, -x)
  4308. def test_wrong_class_slot_wrapper(self):
  4309. # Check bpo-37619: a wrapper descriptor taken from the wrong class
  4310. # should raise an exception instead of silently being ignored
  4311. class A(int):
  4312. __eq__ = str.__eq__
  4313. __add__ = str.__add__
  4314. a = A()
  4315. with self.assertRaises(TypeError):
  4316. a == a
  4317. with self.assertRaises(TypeError):
  4318. a + a
  4319. def test_slot_shadows_class_variable(self):
  4320. with self.assertRaises(ValueError) as cm:
  4321. class X:
  4322. __slots__ = ["foo"]
  4323. foo = None
  4324. m = str(cm.exception)
  4325. self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
  4326. def test_set_doc(self):
  4327. class X:
  4328. "elephant"
  4329. X.__doc__ = "banana"
  4330. self.assertEqual(X.__doc__, "banana")
  4331. with self.assertRaises(TypeError) as cm:
  4332. type(list).__dict__["__doc__"].__set__(list, "blah")
  4333. self.assertIn("cannot set '__doc__' attribute of immutable type 'list'", str(cm.exception))
  4334. with self.assertRaises(TypeError) as cm:
  4335. type(X).__dict__["__doc__"].__delete__(X)
  4336. self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception))
  4337. self.assertEqual(X.__doc__, "banana")
  4338. def test_qualname(self):
  4339. descriptors = [str.lower, complex.real, float.real, int.__add__]
  4340. types = ['method', 'member', 'getset', 'wrapper']
  4341. # make sure we have an example of each type of descriptor
  4342. for d, n in zip(descriptors, types):
  4343. self.assertEqual(type(d).__name__, n + '_descriptor')
  4344. for d in descriptors:
  4345. qualname = d.__objclass__.__qualname__ + '.' + d.__name__
  4346. self.assertEqual(d.__qualname__, qualname)
  4347. self.assertEqual(str.lower.__qualname__, 'str.lower')
  4348. self.assertEqual(complex.real.__qualname__, 'complex.real')
  4349. self.assertEqual(float.real.__qualname__, 'float.real')
  4350. self.assertEqual(int.__add__.__qualname__, 'int.__add__')
  4351. class X:
  4352. pass
  4353. with self.assertRaises(TypeError):
  4354. del X.__qualname__
  4355. self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
  4356. str, 'Oink')
  4357. global Y
  4358. class Y:
  4359. class Inside:
  4360. pass
  4361. self.assertEqual(Y.__qualname__, 'Y')
  4362. self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
  4363. def test_qualname_dict(self):
  4364. ns = {'__qualname__': 'some.name'}
  4365. tp = type('Foo', (), ns)
  4366. self.assertEqual(tp.__qualname__, 'some.name')
  4367. self.assertNotIn('__qualname__', tp.__dict__)
  4368. self.assertEqual(ns, {'__qualname__': 'some.name'})
  4369. ns = {'__qualname__': 1}
  4370. self.assertRaises(TypeError, type, 'Foo', (), ns)
  4371. def test_cycle_through_dict(self):
  4372. # See bug #1469629
  4373. class X(dict):
  4374. def __init__(self):
  4375. dict.__init__(self)
  4376. self.__dict__ = self
  4377. x = X()
  4378. x.attr = 42
  4379. wr = weakref.ref(x)
  4380. del x
  4381. support.gc_collect()
  4382. self.assertIsNone(wr())
  4383. for o in gc.get_objects():
  4384. self.assertIsNot(type(o), X)
  4385. def test_object_new_and_init_with_parameters(self):
  4386. # See issue #1683368
  4387. class OverrideNeither:
  4388. pass
  4389. self.assertRaises(TypeError, OverrideNeither, 1)
  4390. self.assertRaises(TypeError, OverrideNeither, kw=1)
  4391. class OverrideNew:
  4392. def __new__(cls, foo, kw=0, *args, **kwds):
  4393. return object.__new__(cls, *args, **kwds)
  4394. class OverrideInit:
  4395. def __init__(self, foo, kw=0, *args, **kwargs):
  4396. return object.__init__(self, *args, **kwargs)
  4397. class OverrideBoth(OverrideNew, OverrideInit):
  4398. pass
  4399. for case in OverrideNew, OverrideInit, OverrideBoth:
  4400. case(1)
  4401. case(1, kw=2)
  4402. self.assertRaises(TypeError, case, 1, 2, 3)
  4403. self.assertRaises(TypeError, case, 1, 2, foo=3)
  4404. def test_subclassing_does_not_duplicate_dict_descriptors(self):
  4405. class Base:
  4406. pass
  4407. class Sub(Base):
  4408. pass
  4409. self.assertIn("__dict__", Base.__dict__)
  4410. self.assertNotIn("__dict__", Sub.__dict__)
  4411. def test_bound_method_repr(self):
  4412. class Foo:
  4413. def method(self):
  4414. pass
  4415. self.assertRegex(repr(Foo().method),
  4416. r"<bound method .*Foo\.method of <.*Foo object at .*>>")
  4417. class Base:
  4418. def method(self):
  4419. pass
  4420. class Derived1(Base):
  4421. pass
  4422. class Derived2(Base):
  4423. def method(self):
  4424. pass
  4425. base = Base()
  4426. derived1 = Derived1()
  4427. derived2 = Derived2()
  4428. super_d2 = super(Derived2, derived2)
  4429. self.assertRegex(repr(base.method),
  4430. r"<bound method .*Base\.method of <.*Base object at .*>>")
  4431. self.assertRegex(repr(derived1.method),
  4432. r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
  4433. self.assertRegex(repr(derived2.method),
  4434. r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
  4435. self.assertRegex(repr(super_d2.method),
  4436. r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
  4437. class Foo:
  4438. @classmethod
  4439. def method(cls):
  4440. pass
  4441. foo = Foo()
  4442. self.assertRegex(repr(foo.method), # access via instance
  4443. r"<bound method .*Foo\.method of <class '.*Foo'>>")
  4444. self.assertRegex(repr(Foo.method), # access via the class
  4445. r"<bound method .*Foo\.method of <class '.*Foo'>>")
  4446. class MyCallable:
  4447. def __call__(self, arg):
  4448. pass
  4449. func = MyCallable() # func has no __name__ or __qualname__ attributes
  4450. instance = object()
  4451. method = types.MethodType(func, instance)
  4452. self.assertRegex(repr(method),
  4453. r"<bound method \? of <object object at .*>>")
  4454. func.__name__ = "name"
  4455. self.assertRegex(repr(method),
  4456. r"<bound method name of <object object at .*>>")
  4457. func.__qualname__ = "qualname"
  4458. self.assertRegex(repr(method),
  4459. r"<bound method qualname of <object object at .*>>")
  4460. @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
  4461. def test_bpo25750(self):
  4462. # bpo-25750: calling a descriptor (implemented as built-in
  4463. # function with METH_FASTCALL) should not crash CPython if the
  4464. # descriptor deletes itself from the class.
  4465. class Descr:
  4466. __get__ = _testcapi.bad_get
  4467. class X:
  4468. descr = Descr()
  4469. def __new__(cls):
  4470. cls.descr = None
  4471. # Create this large list to corrupt some unused memory
  4472. cls.lst = [2**i for i in range(10000)]
  4473. X.descr
  4474. def test_remove_subclass(self):
  4475. # bpo-46417: when the last subclass of a type is deleted,
  4476. # remove_subclass() clears the internal dictionary of subclasses:
  4477. # set PyTypeObject.tp_subclasses to NULL. remove_subclass() is called
  4478. # when a type is deallocated.
  4479. class Parent:
  4480. pass
  4481. self.assertEqual(Parent.__subclasses__(), [])
  4482. class Child(Parent):
  4483. pass
  4484. self.assertEqual(Parent.__subclasses__(), [Child])
  4485. del Child
  4486. gc.collect()
  4487. self.assertEqual(Parent.__subclasses__(), [])
  4488. class DictProxyTests(unittest.TestCase):
  4489. def setUp(self):
  4490. class C(object):
  4491. def meth(self):
  4492. pass
  4493. self.C = C
  4494. @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
  4495. 'trace function introduces __local__')
  4496. def test_iter_keys(self):
  4497. # Testing dict-proxy keys...
  4498. it = self.C.__dict__.keys()
  4499. self.assertNotIsInstance(it, list)
  4500. keys = list(it)
  4501. keys.sort()
  4502. self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
  4503. '__weakref__', 'meth'])
  4504. @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
  4505. 'trace function introduces __local__')
  4506. def test_iter_values(self):
  4507. # Testing dict-proxy values...
  4508. it = self.C.__dict__.values()
  4509. self.assertNotIsInstance(it, list)
  4510. values = list(it)
  4511. self.assertEqual(len(values), 5)
  4512. @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
  4513. 'trace function introduces __local__')
  4514. def test_iter_items(self):
  4515. # Testing dict-proxy iteritems...
  4516. it = self.C.__dict__.items()
  4517. self.assertNotIsInstance(it, list)
  4518. keys = [item[0] for item in it]
  4519. keys.sort()
  4520. self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
  4521. '__weakref__', 'meth'])
  4522. def test_dict_type_with_metaclass(self):
  4523. # Testing type of __dict__ when metaclass set...
  4524. class B(object):
  4525. pass
  4526. class M(type):
  4527. pass
  4528. class C(metaclass=M):
  4529. # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
  4530. pass
  4531. self.assertEqual(type(C.__dict__), type(B.__dict__))
  4532. def test_repr(self):
  4533. # Testing mappingproxy.__repr__.
  4534. # We can't blindly compare with the repr of another dict as ordering
  4535. # of keys and values is arbitrary and may differ.
  4536. r = repr(self.C.__dict__)
  4537. self.assertTrue(r.startswith('mappingproxy('), r)
  4538. self.assertTrue(r.endswith(')'), r)
  4539. for k, v in self.C.__dict__.items():
  4540. self.assertIn('{!r}: {!r}'.format(k, v), r)
  4541. class AAAPTypesLongInitTest(unittest.TestCase):
  4542. # This is in its own TestCase so that it can be run before any other tests.
  4543. # (Hence the 'AAA' in the test class name: to make it the first
  4544. # item in a list sorted by name, like
  4545. # unittest.TestLoader.getTestCaseNames() does.)
  4546. def test_pytype_long_ready(self):
  4547. # Testing SF bug 551412 ...
  4548. # This dumps core when SF bug 551412 isn't fixed --
  4549. # but only when test_descr.py is run separately.
  4550. # (That can't be helped -- as soon as PyType_Ready()
  4551. # is called for PyLong_Type, the bug is gone.)
  4552. class UserLong(object):
  4553. def __pow__(self, *args):
  4554. pass
  4555. try:
  4556. pow(0, UserLong(), 0)
  4557. except:
  4558. pass
  4559. # Another segfault only when run early
  4560. # (before PyType_Ready(tuple) is called)
  4561. type.mro(tuple)
  4562. class MiscTests(unittest.TestCase):
  4563. def test_type_lookup_mro_reference(self):
  4564. # Issue #14199: _PyType_Lookup() has to keep a strong reference to
  4565. # the type MRO because it may be modified during the lookup, if
  4566. # __bases__ is set during the lookup for example.
  4567. class MyKey(object):
  4568. def __hash__(self):
  4569. return hash('mykey')
  4570. def __eq__(self, other):
  4571. X.__bases__ = (Base2,)
  4572. class Base(object):
  4573. mykey = 'from Base'
  4574. mykey2 = 'from Base'
  4575. class Base2(object):
  4576. mykey = 'from Base2'
  4577. mykey2 = 'from Base2'
  4578. X = type('X', (Base,), {MyKey(): 5})
  4579. # mykey is read from Base
  4580. self.assertEqual(X.mykey, 'from Base')
  4581. # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
  4582. self.assertEqual(X.mykey2, 'from Base2')
  4583. class PicklingTests(unittest.TestCase):
  4584. def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
  4585. listitems=None, dictitems=None):
  4586. if proto >= 2:
  4587. reduce_value = obj.__reduce_ex__(proto)
  4588. if kwargs:
  4589. self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
  4590. self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
  4591. else:
  4592. self.assertEqual(reduce_value[0], copyreg.__newobj__)
  4593. self.assertEqual(reduce_value[1], (type(obj),) + args)
  4594. self.assertEqual(reduce_value[2], state)
  4595. if listitems is not None:
  4596. self.assertListEqual(list(reduce_value[3]), listitems)
  4597. else:
  4598. self.assertIsNone(reduce_value[3])
  4599. if dictitems is not None:
  4600. self.assertDictEqual(dict(reduce_value[4]), dictitems)
  4601. else:
  4602. self.assertIsNone(reduce_value[4])
  4603. else:
  4604. base_type = type(obj).__base__
  4605. reduce_value = (copyreg._reconstructor,
  4606. (type(obj),
  4607. base_type,
  4608. None if base_type is object else base_type(obj)))
  4609. if state is not None:
  4610. reduce_value += (state,)
  4611. self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
  4612. self.assertEqual(obj.__reduce__(), reduce_value)
  4613. def test_reduce(self):
  4614. protocols = range(pickle.HIGHEST_PROTOCOL + 1)
  4615. args = (-101, "spam")
  4616. kwargs = {'bacon': -201, 'fish': -301}
  4617. state = {'cheese': -401}
  4618. class C1:
  4619. def __getnewargs__(self):
  4620. return args
  4621. obj = C1()
  4622. for proto in protocols:
  4623. self._check_reduce(proto, obj, args)
  4624. for name, value in state.items():
  4625. setattr(obj, name, value)
  4626. for proto in protocols:
  4627. self._check_reduce(proto, obj, args, state=state)
  4628. class C2:
  4629. def __getnewargs__(self):
  4630. return "bad args"
  4631. obj = C2()
  4632. for proto in protocols:
  4633. if proto >= 2:
  4634. with self.assertRaises(TypeError):
  4635. obj.__reduce_ex__(proto)
  4636. class C3:
  4637. def __getnewargs_ex__(self):
  4638. return (args, kwargs)
  4639. obj = C3()
  4640. for proto in protocols:
  4641. if proto >= 2:
  4642. self._check_reduce(proto, obj, args, kwargs)
  4643. class C4:
  4644. def __getnewargs_ex__(self):
  4645. return (args, "bad dict")
  4646. class C5:
  4647. def __getnewargs_ex__(self):
  4648. return ("bad tuple", kwargs)
  4649. class C6:
  4650. def __getnewargs_ex__(self):
  4651. return ()
  4652. class C7:
  4653. def __getnewargs_ex__(self):
  4654. return "bad args"
  4655. for proto in protocols:
  4656. for cls in C4, C5, C6, C7:
  4657. obj = cls()
  4658. if proto >= 2:
  4659. with self.assertRaises((TypeError, ValueError)):
  4660. obj.__reduce_ex__(proto)
  4661. class C9:
  4662. def __getnewargs_ex__(self):
  4663. return (args, {})
  4664. obj = C9()
  4665. for proto in protocols:
  4666. self._check_reduce(proto, obj, args)
  4667. class C10:
  4668. def __getnewargs_ex__(self):
  4669. raise IndexError
  4670. obj = C10()
  4671. for proto in protocols:
  4672. if proto >= 2:
  4673. with self.assertRaises(IndexError):
  4674. obj.__reduce_ex__(proto)
  4675. class C11:
  4676. def __getstate__(self):
  4677. return state
  4678. obj = C11()
  4679. for proto in protocols:
  4680. self._check_reduce(proto, obj, state=state)
  4681. class C12:
  4682. def __getstate__(self):
  4683. return "not dict"
  4684. obj = C12()
  4685. for proto in protocols:
  4686. self._check_reduce(proto, obj, state="not dict")
  4687. class C13:
  4688. def __getstate__(self):
  4689. raise IndexError
  4690. obj = C13()
  4691. for proto in protocols:
  4692. with self.assertRaises(IndexError):
  4693. obj.__reduce_ex__(proto)
  4694. if proto < 2:
  4695. with self.assertRaises(IndexError):
  4696. obj.__reduce__()
  4697. class C14:
  4698. __slots__ = tuple(state)
  4699. def __init__(self):
  4700. for name, value in state.items():
  4701. setattr(self, name, value)
  4702. obj = C14()
  4703. for proto in protocols:
  4704. if proto >= 2:
  4705. self._check_reduce(proto, obj, state=(None, state))
  4706. else:
  4707. with self.assertRaises(TypeError):
  4708. obj.__reduce_ex__(proto)
  4709. with self.assertRaises(TypeError):
  4710. obj.__reduce__()
  4711. class C15(dict):
  4712. pass
  4713. obj = C15({"quebec": -601})
  4714. for proto in protocols:
  4715. self._check_reduce(proto, obj, dictitems=dict(obj))
  4716. class C16(list):
  4717. pass
  4718. obj = C16(["yukon"])
  4719. for proto in protocols:
  4720. self._check_reduce(proto, obj, listitems=list(obj))
  4721. def test_special_method_lookup(self):
  4722. protocols = range(pickle.HIGHEST_PROTOCOL + 1)
  4723. class Picky:
  4724. def __getstate__(self):
  4725. return {}
  4726. def __getattr__(self, attr):
  4727. if attr in ("__getnewargs__", "__getnewargs_ex__"):
  4728. raise AssertionError(attr)
  4729. return None
  4730. for protocol in protocols:
  4731. state = {} if protocol >= 2 else None
  4732. self._check_reduce(protocol, Picky(), state=state)
  4733. def _assert_is_copy(self, obj, objcopy, msg=None):
  4734. """Utility method to verify if two objects are copies of each others.
  4735. """
  4736. if msg is None:
  4737. msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
  4738. if type(obj).__repr__ is object.__repr__:
  4739. # We have this limitation for now because we use the object's repr
  4740. # to help us verify that the two objects are copies. This allows
  4741. # us to delegate the non-generic verification logic to the objects
  4742. # themselves.
  4743. raise ValueError("object passed to _assert_is_copy must " +
  4744. "override the __repr__ method.")
  4745. self.assertIsNot(obj, objcopy, msg=msg)
  4746. self.assertIs(type(obj), type(objcopy), msg=msg)
  4747. if hasattr(obj, '__dict__'):
  4748. self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
  4749. self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
  4750. if hasattr(obj, '__slots__'):
  4751. self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
  4752. for slot in obj.__slots__:
  4753. self.assertEqual(
  4754. hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
  4755. self.assertEqual(getattr(obj, slot, None),
  4756. getattr(objcopy, slot, None), msg=msg)
  4757. self.assertEqual(repr(obj), repr(objcopy), msg=msg)
  4758. @staticmethod
  4759. def _generate_pickle_copiers():
  4760. """Utility method to generate the many possible pickle configurations.
  4761. """
  4762. class PickleCopier:
  4763. "This class copies object using pickle."
  4764. def __init__(self, proto, dumps, loads):
  4765. self.proto = proto
  4766. self.dumps = dumps
  4767. self.loads = loads
  4768. def copy(self, obj):
  4769. return self.loads(self.dumps(obj, self.proto))
  4770. def __repr__(self):
  4771. # We try to be as descriptive as possible here since this is
  4772. # the string which we will allow us to tell the pickle
  4773. # configuration we are using during debugging.
  4774. return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
  4775. .format(self.proto,
  4776. self.dumps.__module__, self.dumps.__qualname__,
  4777. self.loads.__module__, self.loads.__qualname__))
  4778. return (PickleCopier(*args) for args in
  4779. itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
  4780. {pickle.dumps, pickle._dumps},
  4781. {pickle.loads, pickle._loads}))
  4782. def test_pickle_slots(self):
  4783. # Tests pickling of classes with __slots__.
  4784. # Pickling of classes with __slots__ but without __getstate__ should
  4785. # fail (if using protocol 0 or 1)
  4786. global C
  4787. class C:
  4788. __slots__ = ['a']
  4789. with self.assertRaises(TypeError):
  4790. pickle.dumps(C(), 0)
  4791. global D
  4792. class D(C):
  4793. pass
  4794. with self.assertRaises(TypeError):
  4795. pickle.dumps(D(), 0)
  4796. class C:
  4797. "A class with __getstate__ and __setstate__ implemented."
  4798. __slots__ = ['a']
  4799. def __getstate__(self):
  4800. state = getattr(self, '__dict__', {}).copy()
  4801. for cls in type(self).__mro__:
  4802. for slot in cls.__dict__.get('__slots__', ()):
  4803. try:
  4804. state[slot] = getattr(self, slot)
  4805. except AttributeError:
  4806. pass
  4807. return state
  4808. def __setstate__(self, state):
  4809. for k, v in state.items():
  4810. setattr(self, k, v)
  4811. def __repr__(self):
  4812. return "%s()<%r>" % (type(self).__name__, self.__getstate__())
  4813. class D(C):
  4814. "A subclass of a class with slots."
  4815. pass
  4816. global E
  4817. class E(C):
  4818. "A subclass with an extra slot."
  4819. __slots__ = ['b']
  4820. # Now it should work
  4821. for pickle_copier in self._generate_pickle_copiers():
  4822. with self.subTest(pickle_copier=pickle_copier):
  4823. x = C()
  4824. y = pickle_copier.copy(x)
  4825. self._assert_is_copy(x, y)
  4826. x.a = 42
  4827. y = pickle_copier.copy(x)
  4828. self._assert_is_copy(x, y)
  4829. x = D()
  4830. x.a = 42
  4831. x.b = 100
  4832. y = pickle_copier.copy(x)
  4833. self._assert_is_copy(x, y)
  4834. x = E()
  4835. x.a = 42
  4836. x.b = "foo"
  4837. y = pickle_copier.copy(x)
  4838. self._assert_is_copy(x, y)
  4839. def test_reduce_copying(self):
  4840. # Tests pickling and copying new-style classes and objects.
  4841. global C1
  4842. class C1:
  4843. "The state of this class is copyable via its instance dict."
  4844. ARGS = (1, 2)
  4845. NEED_DICT_COPYING = True
  4846. def __init__(self, a, b):
  4847. super().__init__()
  4848. self.a = a
  4849. self.b = b
  4850. def __repr__(self):
  4851. return "C1(%r, %r)" % (self.a, self.b)
  4852. global C2
  4853. class C2(list):
  4854. "A list subclass copyable via __getnewargs__."
  4855. ARGS = (1, 2)
  4856. NEED_DICT_COPYING = False
  4857. def __new__(cls, a, b):
  4858. self = super().__new__(cls)
  4859. self.a = a
  4860. self.b = b
  4861. return self
  4862. def __init__(self, *args):
  4863. super().__init__()
  4864. # This helps testing that __init__ is not called during the
  4865. # unpickling process, which would cause extra appends.
  4866. self.append("cheese")
  4867. @classmethod
  4868. def __getnewargs__(cls):
  4869. return cls.ARGS
  4870. def __repr__(self):
  4871. return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
  4872. global C3
  4873. class C3(list):
  4874. "A list subclass copyable via __getstate__."
  4875. ARGS = (1, 2)
  4876. NEED_DICT_COPYING = False
  4877. def __init__(self, a, b):
  4878. self.a = a
  4879. self.b = b
  4880. # This helps testing that __init__ is not called during the
  4881. # unpickling process, which would cause extra appends.
  4882. self.append("cheese")
  4883. @classmethod
  4884. def __getstate__(cls):
  4885. return cls.ARGS
  4886. def __setstate__(self, state):
  4887. a, b = state
  4888. self.a = a
  4889. self.b = b
  4890. def __repr__(self):
  4891. return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
  4892. global C4
  4893. class C4(int):
  4894. "An int subclass copyable via __getnewargs__."
  4895. ARGS = ("hello", "world", 1)
  4896. NEED_DICT_COPYING = False
  4897. def __new__(cls, a, b, value):
  4898. self = super().__new__(cls, value)
  4899. self.a = a
  4900. self.b = b
  4901. return self
  4902. @classmethod
  4903. def __getnewargs__(cls):
  4904. return cls.ARGS
  4905. def __repr__(self):
  4906. return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
  4907. global C5
  4908. class C5(int):
  4909. "An int subclass copyable via __getnewargs_ex__."
  4910. ARGS = (1, 2)
  4911. KWARGS = {'value': 3}
  4912. NEED_DICT_COPYING = False
  4913. def __new__(cls, a, b, *, value=0):
  4914. self = super().__new__(cls, value)
  4915. self.a = a
  4916. self.b = b
  4917. return self
  4918. @classmethod
  4919. def __getnewargs_ex__(cls):
  4920. return (cls.ARGS, cls.KWARGS)
  4921. def __repr__(self):
  4922. return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
  4923. test_classes = (C1, C2, C3, C4, C5)
  4924. # Testing copying through pickle
  4925. pickle_copiers = self._generate_pickle_copiers()
  4926. for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
  4927. with self.subTest(cls=cls, pickle_copier=pickle_copier):
  4928. kwargs = getattr(cls, 'KWARGS', {})
  4929. obj = cls(*cls.ARGS, **kwargs)
  4930. proto = pickle_copier.proto
  4931. objcopy = pickle_copier.copy(obj)
  4932. self._assert_is_copy(obj, objcopy)
  4933. # For test classes that supports this, make sure we didn't go
  4934. # around the reduce protocol by simply copying the attribute
  4935. # dictionary. We clear attributes using the previous copy to
  4936. # not mutate the original argument.
  4937. if proto >= 2 and not cls.NEED_DICT_COPYING:
  4938. objcopy.__dict__.clear()
  4939. objcopy2 = pickle_copier.copy(objcopy)
  4940. self._assert_is_copy(obj, objcopy2)
  4941. # Testing copying through copy.deepcopy()
  4942. for cls in test_classes:
  4943. with self.subTest(cls=cls):
  4944. kwargs = getattr(cls, 'KWARGS', {})
  4945. obj = cls(*cls.ARGS, **kwargs)
  4946. objcopy = deepcopy(obj)
  4947. self._assert_is_copy(obj, objcopy)
  4948. # For test classes that supports this, make sure we didn't go
  4949. # around the reduce protocol by simply copying the attribute
  4950. # dictionary. We clear attributes using the previous copy to
  4951. # not mutate the original argument.
  4952. if not cls.NEED_DICT_COPYING:
  4953. objcopy.__dict__.clear()
  4954. objcopy2 = deepcopy(objcopy)
  4955. self._assert_is_copy(obj, objcopy2)
  4956. def test_issue24097(self):
  4957. # Slot name is freed inside __getattr__ and is later used.
  4958. class S(str): # Not interned
  4959. pass
  4960. class A:
  4961. __slotnames__ = [S('spam')]
  4962. def __getattr__(self, attr):
  4963. if attr == 'spam':
  4964. A.__slotnames__[:] = [S('spam')]
  4965. return 42
  4966. else:
  4967. raise AttributeError
  4968. import copyreg
  4969. expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
  4970. self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
  4971. def test_object_reduce(self):
  4972. # Issue #29914
  4973. # __reduce__() takes no arguments
  4974. object().__reduce__()
  4975. with self.assertRaises(TypeError):
  4976. object().__reduce__(0)
  4977. # __reduce_ex__() takes one integer argument
  4978. object().__reduce_ex__(0)
  4979. with self.assertRaises(TypeError):
  4980. object().__reduce_ex__()
  4981. with self.assertRaises(TypeError):
  4982. object().__reduce_ex__(None)
  4983. class SharedKeyTests(unittest.TestCase):
  4984. @support.cpython_only
  4985. def test_subclasses(self):
  4986. # Verify that subclasses can share keys (per PEP 412)
  4987. class A:
  4988. pass
  4989. class B(A):
  4990. pass
  4991. #Shrink keys by repeatedly creating instances
  4992. [(A(), B()) for _ in range(30)]
  4993. a, b = A(), B()
  4994. self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
  4995. self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
  4996. # Initial hash table can contain only one or two elements.
  4997. # Set 6 attributes to cause internal resizing.
  4998. a.x, a.y, a.z, a.w, a.v, a.u = range(6)
  4999. self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
  5000. a2 = A()
  5001. self.assertGreater(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
  5002. self.assertLess(sys.getsizeof(vars(a2)), sys.getsizeof({"a":1}))
  5003. self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
  5004. class DebugHelperMeta(type):
  5005. """
  5006. Sets default __doc__ and simplifies repr() output.
  5007. """
  5008. def __new__(mcls, name, bases, attrs):
  5009. if attrs.get('__doc__') is None:
  5010. attrs['__doc__'] = name # helps when debugging with gdb
  5011. return type.__new__(mcls, name, bases, attrs)
  5012. def __repr__(cls):
  5013. return repr(cls.__name__)
  5014. class MroTest(unittest.TestCase):
  5015. """
  5016. Regressions for some bugs revealed through
  5017. mcsl.mro() customization (typeobject.c: mro_internal()) and
  5018. cls.__bases__ assignment (typeobject.c: type_set_bases()).
  5019. """
  5020. def setUp(self):
  5021. self.step = 0
  5022. self.ready = False
  5023. def step_until(self, limit):
  5024. ret = (self.step < limit)
  5025. if ret:
  5026. self.step += 1
  5027. return ret
  5028. def test_incomplete_set_bases_on_self(self):
  5029. """
  5030. type_set_bases must be aware that type->tp_mro can be NULL.
  5031. """
  5032. class M(DebugHelperMeta):
  5033. def mro(cls):
  5034. if self.step_until(1):
  5035. assert cls.__mro__ is None
  5036. cls.__bases__ += ()
  5037. return type.mro(cls)
  5038. class A(metaclass=M):
  5039. pass
  5040. def test_reent_set_bases_on_base(self):
  5041. """
  5042. Deep reentrancy must not over-decref old_mro.
  5043. """
  5044. class M(DebugHelperMeta):
  5045. def mro(cls):
  5046. if cls.__mro__ is not None and cls.__name__ == 'B':
  5047. # 4-5 steps are usually enough to make it crash somewhere
  5048. if self.step_until(10):
  5049. A.__bases__ += ()
  5050. return type.mro(cls)
  5051. class A(metaclass=M):
  5052. pass
  5053. class B(A):
  5054. pass
  5055. B.__bases__ += ()
  5056. def test_reent_set_bases_on_direct_base(self):
  5057. """
  5058. Similar to test_reent_set_bases_on_base, but may crash differently.
  5059. """
  5060. class M(DebugHelperMeta):
  5061. def mro(cls):
  5062. base = cls.__bases__[0]
  5063. if base is not object:
  5064. if self.step_until(5):
  5065. base.__bases__ += ()
  5066. return type.mro(cls)
  5067. class A(metaclass=M):
  5068. pass
  5069. class B(A):
  5070. pass
  5071. class C(B):
  5072. pass
  5073. def test_reent_set_bases_tp_base_cycle(self):
  5074. """
  5075. type_set_bases must check for an inheritance cycle not only through
  5076. MRO of the type, which may be not yet updated in case of reentrance,
  5077. but also through tp_base chain, which is assigned before diving into
  5078. inner calls to mro().
  5079. Otherwise, the following snippet can loop forever:
  5080. do {
  5081. // ...
  5082. type = type->tp_base;
  5083. } while (type != NULL);
  5084. Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
  5085. would not be happy in that case, causing a stack overflow.
  5086. """
  5087. class M(DebugHelperMeta):
  5088. def mro(cls):
  5089. if self.ready:
  5090. if cls.__name__ == 'B1':
  5091. B2.__bases__ = (B1,)
  5092. if cls.__name__ == 'B2':
  5093. B1.__bases__ = (B2,)
  5094. return type.mro(cls)
  5095. class A(metaclass=M):
  5096. pass
  5097. class B1(A):
  5098. pass
  5099. class B2(A):
  5100. pass
  5101. self.ready = True
  5102. with self.assertRaises(TypeError):
  5103. B1.__bases__ += ()
  5104. def test_tp_subclasses_cycle_in_update_slots(self):
  5105. """
  5106. type_set_bases must check for reentrancy upon finishing its job
  5107. by updating tp_subclasses of old/new bases of the type.
  5108. Otherwise, an implicit inheritance cycle through tp_subclasses
  5109. can break functions that recurse on elements of that field
  5110. (like recurse_down_subclasses and mro_hierarchy) eventually
  5111. leading to a stack overflow.
  5112. """
  5113. class M(DebugHelperMeta):
  5114. def mro(cls):
  5115. if self.ready and cls.__name__ == 'C':
  5116. self.ready = False
  5117. C.__bases__ = (B2,)
  5118. return type.mro(cls)
  5119. class A(metaclass=M):
  5120. pass
  5121. class B1(A):
  5122. pass
  5123. class B2(A):
  5124. pass
  5125. class C(A):
  5126. pass
  5127. self.ready = True
  5128. C.__bases__ = (B1,)
  5129. B1.__bases__ = (C,)
  5130. self.assertEqual(C.__bases__, (B2,))
  5131. self.assertEqual(B2.__subclasses__(), [C])
  5132. self.assertEqual(B1.__subclasses__(), [])
  5133. self.assertEqual(B1.__bases__, (C,))
  5134. self.assertEqual(C.__subclasses__(), [B1])
  5135. def test_tp_subclasses_cycle_error_return_path(self):
  5136. """
  5137. The same as test_tp_subclasses_cycle_in_update_slots, but tests
  5138. a code path executed on error (goto bail).
  5139. """
  5140. class E(Exception):
  5141. pass
  5142. class M(DebugHelperMeta):
  5143. def mro(cls):
  5144. if self.ready and cls.__name__ == 'C':
  5145. if C.__bases__ == (B2,):
  5146. self.ready = False
  5147. else:
  5148. C.__bases__ = (B2,)
  5149. raise E
  5150. return type.mro(cls)
  5151. class A(metaclass=M):
  5152. pass
  5153. class B1(A):
  5154. pass
  5155. class B2(A):
  5156. pass
  5157. class C(A):
  5158. pass
  5159. self.ready = True
  5160. with self.assertRaises(E):
  5161. C.__bases__ = (B1,)
  5162. B1.__bases__ = (C,)
  5163. self.assertEqual(C.__bases__, (B2,))
  5164. self.assertEqual(C.__mro__, tuple(type.mro(C)))
  5165. def test_incomplete_extend(self):
  5166. """
  5167. Extending an uninitialized type with type->tp_mro == NULL must
  5168. throw a reasonable TypeError exception, instead of failing
  5169. with PyErr_BadInternalCall.
  5170. """
  5171. class M(DebugHelperMeta):
  5172. def mro(cls):
  5173. if cls.__mro__ is None and cls.__name__ != 'X':
  5174. with self.assertRaises(TypeError):
  5175. class X(cls):
  5176. pass
  5177. return type.mro(cls)
  5178. class A(metaclass=M):
  5179. pass
  5180. def test_incomplete_super(self):
  5181. """
  5182. Attribute lookup on a super object must be aware that
  5183. its target type can be uninitialized (type->tp_mro == NULL).
  5184. """
  5185. class M(DebugHelperMeta):
  5186. def mro(cls):
  5187. if cls.__mro__ is None:
  5188. with self.assertRaises(AttributeError):
  5189. super(cls, cls).xxx
  5190. return type.mro(cls)
  5191. class A(metaclass=M):
  5192. pass
  5193. def test_disappearing_custom_mro(self):
  5194. """
  5195. gh-92112: A custom mro() returning a result conflicting with
  5196. __bases__ and deleting itself caused a double free.
  5197. """
  5198. class B:
  5199. pass
  5200. class M(DebugHelperMeta):
  5201. def mro(cls):
  5202. del M.mro
  5203. return (B,)
  5204. with self.assertRaises(TypeError):
  5205. class A(metaclass=M):
  5206. pass
  5207. if __name__ == "__main__":
  5208. unittest.main()