test_fixers.py 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649
  1. """ Test suite for the fixer modules """
  2. # Python imports
  3. import os
  4. from itertools import chain
  5. from operator import itemgetter
  6. # Local imports
  7. from lib2to3 import pygram, fixer_util
  8. from lib2to3.tests import support
  9. class FixerTestCase(support.TestCase):
  10. # Other test cases can subclass this class and replace "fixer_pkg" with
  11. # their own.
  12. def setUp(self, fix_list=None, fixer_pkg="lib2to3", options=None):
  13. if fix_list is None:
  14. fix_list = [self.fixer]
  15. self.refactor = support.get_refactorer(fixer_pkg, fix_list, options)
  16. self.fixer_log = []
  17. self.filename = "<string>"
  18. for fixer in chain(self.refactor.pre_order,
  19. self.refactor.post_order):
  20. fixer.log = self.fixer_log
  21. def _check(self, before, after):
  22. before = support.reformat(before)
  23. after = support.reformat(after)
  24. tree = self.refactor.refactor_string(before, self.filename)
  25. self.assertEqual(after, str(tree))
  26. return tree
  27. def check(self, before, after, ignore_warnings=False):
  28. tree = self._check(before, after)
  29. self.assertTrue(tree.was_changed)
  30. if not ignore_warnings:
  31. self.assertEqual(self.fixer_log, [])
  32. def warns(self, before, after, message, unchanged=False):
  33. tree = self._check(before, after)
  34. self.assertIn(message, "".join(self.fixer_log))
  35. if not unchanged:
  36. self.assertTrue(tree.was_changed)
  37. def warns_unchanged(self, before, message):
  38. self.warns(before, before, message, unchanged=True)
  39. def unchanged(self, before, ignore_warnings=False):
  40. self._check(before, before)
  41. if not ignore_warnings:
  42. self.assertEqual(self.fixer_log, [])
  43. def assert_runs_after(self, *names):
  44. fixes = [self.fixer]
  45. fixes.extend(names)
  46. r = support.get_refactorer("lib2to3", fixes)
  47. (pre, post) = r.get_fixers()
  48. n = "fix_" + self.fixer
  49. if post and post[-1].__class__.__module__.endswith(n):
  50. # We're the last fixer to run
  51. return
  52. if pre and pre[-1].__class__.__module__.endswith(n) and not post:
  53. # We're the last in pre and post is empty
  54. return
  55. self.fail("Fixer run order (%s) is incorrect; %s should be last."\
  56. %(", ".join([x.__class__.__module__ for x in (pre+post)]), n))
  57. class Test_ne(FixerTestCase):
  58. fixer = "ne"
  59. def test_basic(self):
  60. b = """if x <> y:
  61. pass"""
  62. a = """if x != y:
  63. pass"""
  64. self.check(b, a)
  65. def test_no_spaces(self):
  66. b = """if x<>y:
  67. pass"""
  68. a = """if x!=y:
  69. pass"""
  70. self.check(b, a)
  71. def test_chained(self):
  72. b = """if x<>y<>z:
  73. pass"""
  74. a = """if x!=y!=z:
  75. pass"""
  76. self.check(b, a)
  77. class Test_has_key(FixerTestCase):
  78. fixer = "has_key"
  79. def test_1(self):
  80. b = """x = d.has_key("x") or d.has_key("y")"""
  81. a = """x = "x" in d or "y" in d"""
  82. self.check(b, a)
  83. def test_2(self):
  84. b = """x = a.b.c.d.has_key("x") ** 3"""
  85. a = """x = ("x" in a.b.c.d) ** 3"""
  86. self.check(b, a)
  87. def test_3(self):
  88. b = """x = a.b.has_key(1 + 2).__repr__()"""
  89. a = """x = (1 + 2 in a.b).__repr__()"""
  90. self.check(b, a)
  91. def test_4(self):
  92. b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""
  93. a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""
  94. self.check(b, a)
  95. def test_5(self):
  96. b = """x = a.has_key(f or g)"""
  97. a = """x = (f or g) in a"""
  98. self.check(b, a)
  99. def test_6(self):
  100. b = """x = a + b.has_key(c)"""
  101. a = """x = a + (c in b)"""
  102. self.check(b, a)
  103. def test_7(self):
  104. b = """x = a.has_key(lambda: 12)"""
  105. a = """x = (lambda: 12) in a"""
  106. self.check(b, a)
  107. def test_8(self):
  108. b = """x = a.has_key(a for a in b)"""
  109. a = """x = (a for a in b) in a"""
  110. self.check(b, a)
  111. def test_9(self):
  112. b = """if not a.has_key(b): pass"""
  113. a = """if b not in a: pass"""
  114. self.check(b, a)
  115. def test_10(self):
  116. b = """if not a.has_key(b).__repr__(): pass"""
  117. a = """if not (b in a).__repr__(): pass"""
  118. self.check(b, a)
  119. def test_11(self):
  120. b = """if not a.has_key(b) ** 2: pass"""
  121. a = """if not (b in a) ** 2: pass"""
  122. self.check(b, a)
  123. class Test_apply(FixerTestCase):
  124. fixer = "apply"
  125. def test_1(self):
  126. b = """x = apply(f, g + h)"""
  127. a = """x = f(*g + h)"""
  128. self.check(b, a)
  129. def test_2(self):
  130. b = """y = apply(f, g, h)"""
  131. a = """y = f(*g, **h)"""
  132. self.check(b, a)
  133. def test_3(self):
  134. b = """z = apply(fs[0], g or h, h or g)"""
  135. a = """z = fs[0](*g or h, **h or g)"""
  136. self.check(b, a)
  137. def test_4(self):
  138. b = """apply(f, (x, y) + t)"""
  139. a = """f(*(x, y) + t)"""
  140. self.check(b, a)
  141. def test_5(self):
  142. b = """apply(f, args,)"""
  143. a = """f(*args)"""
  144. self.check(b, a)
  145. def test_6(self):
  146. b = """apply(f, args, kwds,)"""
  147. a = """f(*args, **kwds)"""
  148. self.check(b, a)
  149. # Test that complex functions are parenthesized
  150. def test_complex_1(self):
  151. b = """x = apply(f+g, args)"""
  152. a = """x = (f+g)(*args)"""
  153. self.check(b, a)
  154. def test_complex_2(self):
  155. b = """x = apply(f*g, args)"""
  156. a = """x = (f*g)(*args)"""
  157. self.check(b, a)
  158. def test_complex_3(self):
  159. b = """x = apply(f**g, args)"""
  160. a = """x = (f**g)(*args)"""
  161. self.check(b, a)
  162. # But dotted names etc. not
  163. def test_dotted_name(self):
  164. b = """x = apply(f.g, args)"""
  165. a = """x = f.g(*args)"""
  166. self.check(b, a)
  167. def test_subscript(self):
  168. b = """x = apply(f[x], args)"""
  169. a = """x = f[x](*args)"""
  170. self.check(b, a)
  171. def test_call(self):
  172. b = """x = apply(f(), args)"""
  173. a = """x = f()(*args)"""
  174. self.check(b, a)
  175. # Extreme case
  176. def test_extreme(self):
  177. b = """x = apply(a.b.c.d.e.f, args, kwds)"""
  178. a = """x = a.b.c.d.e.f(*args, **kwds)"""
  179. self.check(b, a)
  180. # XXX Comments in weird places still get lost
  181. def test_weird_comments(self):
  182. b = """apply( # foo
  183. f, # bar
  184. args)"""
  185. a = """f(*args)"""
  186. self.check(b, a)
  187. # These should *not* be touched
  188. def test_unchanged_1(self):
  189. s = """apply()"""
  190. self.unchanged(s)
  191. def test_unchanged_2(self):
  192. s = """apply(f)"""
  193. self.unchanged(s)
  194. def test_unchanged_3(self):
  195. s = """apply(f,)"""
  196. self.unchanged(s)
  197. def test_unchanged_4(self):
  198. s = """apply(f, args, kwds, extras)"""
  199. self.unchanged(s)
  200. def test_unchanged_5(self):
  201. s = """apply(f, *args, **kwds)"""
  202. self.unchanged(s)
  203. def test_unchanged_6(self):
  204. s = """apply(f, *args)"""
  205. self.unchanged(s)
  206. def test_unchanged_6b(self):
  207. s = """apply(f, **kwds)"""
  208. self.unchanged(s)
  209. def test_unchanged_7(self):
  210. s = """apply(func=f, args=args, kwds=kwds)"""
  211. self.unchanged(s)
  212. def test_unchanged_8(self):
  213. s = """apply(f, args=args, kwds=kwds)"""
  214. self.unchanged(s)
  215. def test_unchanged_9(self):
  216. s = """apply(f, args, kwds=kwds)"""
  217. self.unchanged(s)
  218. def test_space_1(self):
  219. a = """apply( f, args, kwds)"""
  220. b = """f(*args, **kwds)"""
  221. self.check(a, b)
  222. def test_space_2(self):
  223. a = """apply( f ,args,kwds )"""
  224. b = """f(*args, **kwds)"""
  225. self.check(a, b)
  226. class Test_reload(FixerTestCase):
  227. fixer = "reload"
  228. def test(self):
  229. b = """reload(a)"""
  230. a = """import importlib\nimportlib.reload(a)"""
  231. self.check(b, a)
  232. def test_comment(self):
  233. b = """reload( a ) # comment"""
  234. a = """import importlib\nimportlib.reload( a ) # comment"""
  235. self.check(b, a)
  236. # PEP 8 comments
  237. b = """reload( a ) # comment"""
  238. a = """import importlib\nimportlib.reload( a ) # comment"""
  239. self.check(b, a)
  240. def test_space(self):
  241. b = """reload( a )"""
  242. a = """import importlib\nimportlib.reload( a )"""
  243. self.check(b, a)
  244. b = """reload( a)"""
  245. a = """import importlib\nimportlib.reload( a)"""
  246. self.check(b, a)
  247. b = """reload(a )"""
  248. a = """import importlib\nimportlib.reload(a )"""
  249. self.check(b, a)
  250. def test_unchanged(self):
  251. s = """reload(a=1)"""
  252. self.unchanged(s)
  253. s = """reload(f, g)"""
  254. self.unchanged(s)
  255. s = """reload(f, *h)"""
  256. self.unchanged(s)
  257. s = """reload(f, *h, **i)"""
  258. self.unchanged(s)
  259. s = """reload(f, **i)"""
  260. self.unchanged(s)
  261. s = """reload(*h, **i)"""
  262. self.unchanged(s)
  263. s = """reload(*h)"""
  264. self.unchanged(s)
  265. s = """reload(**i)"""
  266. self.unchanged(s)
  267. s = """reload()"""
  268. self.unchanged(s)
  269. class Test_intern(FixerTestCase):
  270. fixer = "intern"
  271. def test_prefix_preservation(self):
  272. b = """x = intern( a )"""
  273. a = """import sys\nx = sys.intern( a )"""
  274. self.check(b, a)
  275. b = """y = intern("b" # test
  276. )"""
  277. a = """import sys\ny = sys.intern("b" # test
  278. )"""
  279. self.check(b, a)
  280. b = """z = intern(a+b+c.d, )"""
  281. a = """import sys\nz = sys.intern(a+b+c.d, )"""
  282. self.check(b, a)
  283. def test(self):
  284. b = """x = intern(a)"""
  285. a = """import sys\nx = sys.intern(a)"""
  286. self.check(b, a)
  287. b = """z = intern(a+b+c.d,)"""
  288. a = """import sys\nz = sys.intern(a+b+c.d,)"""
  289. self.check(b, a)
  290. b = """intern("y%s" % 5).replace("y", "")"""
  291. a = """import sys\nsys.intern("y%s" % 5).replace("y", "")"""
  292. self.check(b, a)
  293. # These should not be refactored
  294. def test_unchanged(self):
  295. s = """intern(a=1)"""
  296. self.unchanged(s)
  297. s = """intern(f, g)"""
  298. self.unchanged(s)
  299. s = """intern(*h)"""
  300. self.unchanged(s)
  301. s = """intern(**i)"""
  302. self.unchanged(s)
  303. s = """intern()"""
  304. self.unchanged(s)
  305. class Test_reduce(FixerTestCase):
  306. fixer = "reduce"
  307. def test_simple_call(self):
  308. b = "reduce(a, b, c)"
  309. a = "from functools import reduce\nreduce(a, b, c)"
  310. self.check(b, a)
  311. def test_bug_7253(self):
  312. # fix_tuple_params was being bad and orphaning nodes in the tree.
  313. b = "def x(arg): reduce(sum, [])"
  314. a = "from functools import reduce\ndef x(arg): reduce(sum, [])"
  315. self.check(b, a)
  316. def test_call_with_lambda(self):
  317. b = "reduce(lambda x, y: x + y, seq)"
  318. a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
  319. self.check(b, a)
  320. def test_unchanged(self):
  321. s = "reduce(a)"
  322. self.unchanged(s)
  323. s = "reduce(a, b=42)"
  324. self.unchanged(s)
  325. s = "reduce(a, b, c, d)"
  326. self.unchanged(s)
  327. s = "reduce(**c)"
  328. self.unchanged(s)
  329. s = "reduce()"
  330. self.unchanged(s)
  331. class Test_print(FixerTestCase):
  332. fixer = "print"
  333. def test_prefix_preservation(self):
  334. b = """print 1, 1+1, 1+1+1"""
  335. a = """print(1, 1+1, 1+1+1)"""
  336. self.check(b, a)
  337. def test_idempotency(self):
  338. s = """print()"""
  339. self.unchanged(s)
  340. s = """print('')"""
  341. self.unchanged(s)
  342. def test_idempotency_print_as_function(self):
  343. self.refactor.driver.grammar = pygram.python_grammar_no_print_statement
  344. s = """print(1, 1+1, 1+1+1)"""
  345. self.unchanged(s)
  346. s = """print()"""
  347. self.unchanged(s)
  348. s = """print('')"""
  349. self.unchanged(s)
  350. def test_1(self):
  351. b = """print 1, 1+1, 1+1+1"""
  352. a = """print(1, 1+1, 1+1+1)"""
  353. self.check(b, a)
  354. def test_2(self):
  355. b = """print 1, 2"""
  356. a = """print(1, 2)"""
  357. self.check(b, a)
  358. def test_3(self):
  359. b = """print"""
  360. a = """print()"""
  361. self.check(b, a)
  362. def test_4(self):
  363. # from bug 3000
  364. b = """print whatever; print"""
  365. a = """print(whatever); print()"""
  366. self.check(b, a)
  367. def test_5(self):
  368. b = """print; print whatever;"""
  369. a = """print(); print(whatever);"""
  370. self.check(b, a)
  371. def test_tuple(self):
  372. b = """print (a, b, c)"""
  373. a = """print((a, b, c))"""
  374. self.check(b, a)
  375. # trailing commas
  376. def test_trailing_comma_1(self):
  377. b = """print 1, 2, 3,"""
  378. a = """print(1, 2, 3, end=' ')"""
  379. self.check(b, a)
  380. def test_trailing_comma_2(self):
  381. b = """print 1, 2,"""
  382. a = """print(1, 2, end=' ')"""
  383. self.check(b, a)
  384. def test_trailing_comma_3(self):
  385. b = """print 1,"""
  386. a = """print(1, end=' ')"""
  387. self.check(b, a)
  388. # >> stuff
  389. def test_vargs_without_trailing_comma(self):
  390. b = """print >>sys.stderr, 1, 2, 3"""
  391. a = """print(1, 2, 3, file=sys.stderr)"""
  392. self.check(b, a)
  393. def test_with_trailing_comma(self):
  394. b = """print >>sys.stderr, 1, 2,"""
  395. a = """print(1, 2, end=' ', file=sys.stderr)"""
  396. self.check(b, a)
  397. def test_no_trailing_comma(self):
  398. b = """print >>sys.stderr, 1+1"""
  399. a = """print(1+1, file=sys.stderr)"""
  400. self.check(b, a)
  401. def test_spaces_before_file(self):
  402. b = """print >> sys.stderr"""
  403. a = """print(file=sys.stderr)"""
  404. self.check(b, a)
  405. def test_with_future_print_function(self):
  406. s = "from __future__ import print_function\n" \
  407. "print('Hai!', end=' ')"
  408. self.unchanged(s)
  409. b = "print 'Hello, world!'"
  410. a = "print('Hello, world!')"
  411. self.check(b, a)
  412. class Test_exec(FixerTestCase):
  413. fixer = "exec"
  414. def test_prefix_preservation(self):
  415. b = """ exec code in ns1, ns2"""
  416. a = """ exec(code, ns1, ns2)"""
  417. self.check(b, a)
  418. def test_basic(self):
  419. b = """exec code"""
  420. a = """exec(code)"""
  421. self.check(b, a)
  422. def test_with_globals(self):
  423. b = """exec code in ns"""
  424. a = """exec(code, ns)"""
  425. self.check(b, a)
  426. def test_with_globals_locals(self):
  427. b = """exec code in ns1, ns2"""
  428. a = """exec(code, ns1, ns2)"""
  429. self.check(b, a)
  430. def test_complex_1(self):
  431. b = """exec (a.b()) in ns"""
  432. a = """exec((a.b()), ns)"""
  433. self.check(b, a)
  434. def test_complex_2(self):
  435. b = """exec a.b() + c in ns"""
  436. a = """exec(a.b() + c, ns)"""
  437. self.check(b, a)
  438. # These should not be touched
  439. def test_unchanged_1(self):
  440. s = """exec(code)"""
  441. self.unchanged(s)
  442. def test_unchanged_2(self):
  443. s = """exec (code)"""
  444. self.unchanged(s)
  445. def test_unchanged_3(self):
  446. s = """exec(code, ns)"""
  447. self.unchanged(s)
  448. def test_unchanged_4(self):
  449. s = """exec(code, ns1, ns2)"""
  450. self.unchanged(s)
  451. class Test_repr(FixerTestCase):
  452. fixer = "repr"
  453. def test_prefix_preservation(self):
  454. b = """x = `1 + 2`"""
  455. a = """x = repr(1 + 2)"""
  456. self.check(b, a)
  457. def test_simple_1(self):
  458. b = """x = `1 + 2`"""
  459. a = """x = repr(1 + 2)"""
  460. self.check(b, a)
  461. def test_simple_2(self):
  462. b = """y = `x`"""
  463. a = """y = repr(x)"""
  464. self.check(b, a)
  465. def test_complex(self):
  466. b = """z = `y`.__repr__()"""
  467. a = """z = repr(y).__repr__()"""
  468. self.check(b, a)
  469. def test_tuple(self):
  470. b = """x = `1, 2, 3`"""
  471. a = """x = repr((1, 2, 3))"""
  472. self.check(b, a)
  473. def test_nested(self):
  474. b = """x = `1 + `2``"""
  475. a = """x = repr(1 + repr(2))"""
  476. self.check(b, a)
  477. def test_nested_tuples(self):
  478. b = """x = `1, 2 + `3, 4``"""
  479. a = """x = repr((1, 2 + repr((3, 4))))"""
  480. self.check(b, a)
  481. class Test_except(FixerTestCase):
  482. fixer = "except"
  483. def test_prefix_preservation(self):
  484. b = """
  485. try:
  486. pass
  487. except (RuntimeError, ImportError), e:
  488. pass"""
  489. a = """
  490. try:
  491. pass
  492. except (RuntimeError, ImportError) as e:
  493. pass"""
  494. self.check(b, a)
  495. def test_simple(self):
  496. b = """
  497. try:
  498. pass
  499. except Foo, e:
  500. pass"""
  501. a = """
  502. try:
  503. pass
  504. except Foo as e:
  505. pass"""
  506. self.check(b, a)
  507. def test_simple_no_space_before_target(self):
  508. b = """
  509. try:
  510. pass
  511. except Foo,e:
  512. pass"""
  513. a = """
  514. try:
  515. pass
  516. except Foo as e:
  517. pass"""
  518. self.check(b, a)
  519. def test_tuple_unpack(self):
  520. b = """
  521. def foo():
  522. try:
  523. pass
  524. except Exception, (f, e):
  525. pass
  526. except ImportError, e:
  527. pass"""
  528. a = """
  529. def foo():
  530. try:
  531. pass
  532. except Exception as xxx_todo_changeme:
  533. (f, e) = xxx_todo_changeme.args
  534. pass
  535. except ImportError as e:
  536. pass"""
  537. self.check(b, a)
  538. def test_multi_class(self):
  539. b = """
  540. try:
  541. pass
  542. except (RuntimeError, ImportError), e:
  543. pass"""
  544. a = """
  545. try:
  546. pass
  547. except (RuntimeError, ImportError) as e:
  548. pass"""
  549. self.check(b, a)
  550. def test_list_unpack(self):
  551. b = """
  552. try:
  553. pass
  554. except Exception, [a, b]:
  555. pass"""
  556. a = """
  557. try:
  558. pass
  559. except Exception as xxx_todo_changeme:
  560. [a, b] = xxx_todo_changeme.args
  561. pass"""
  562. self.check(b, a)
  563. def test_weird_target_1(self):
  564. b = """
  565. try:
  566. pass
  567. except Exception, d[5]:
  568. pass"""
  569. a = """
  570. try:
  571. pass
  572. except Exception as xxx_todo_changeme:
  573. d[5] = xxx_todo_changeme
  574. pass"""
  575. self.check(b, a)
  576. def test_weird_target_2(self):
  577. b = """
  578. try:
  579. pass
  580. except Exception, a.foo:
  581. pass"""
  582. a = """
  583. try:
  584. pass
  585. except Exception as xxx_todo_changeme:
  586. a.foo = xxx_todo_changeme
  587. pass"""
  588. self.check(b, a)
  589. def test_weird_target_3(self):
  590. b = """
  591. try:
  592. pass
  593. except Exception, a().foo:
  594. pass"""
  595. a = """
  596. try:
  597. pass
  598. except Exception as xxx_todo_changeme:
  599. a().foo = xxx_todo_changeme
  600. pass"""
  601. self.check(b, a)
  602. def test_bare_except(self):
  603. b = """
  604. try:
  605. pass
  606. except Exception, a:
  607. pass
  608. except:
  609. pass"""
  610. a = """
  611. try:
  612. pass
  613. except Exception as a:
  614. pass
  615. except:
  616. pass"""
  617. self.check(b, a)
  618. def test_bare_except_and_else_finally(self):
  619. b = """
  620. try:
  621. pass
  622. except Exception, a:
  623. pass
  624. except:
  625. pass
  626. else:
  627. pass
  628. finally:
  629. pass"""
  630. a = """
  631. try:
  632. pass
  633. except Exception as a:
  634. pass
  635. except:
  636. pass
  637. else:
  638. pass
  639. finally:
  640. pass"""
  641. self.check(b, a)
  642. def test_multi_fixed_excepts_before_bare_except(self):
  643. b = """
  644. try:
  645. pass
  646. except TypeError, b:
  647. pass
  648. except Exception, a:
  649. pass
  650. except:
  651. pass"""
  652. a = """
  653. try:
  654. pass
  655. except TypeError as b:
  656. pass
  657. except Exception as a:
  658. pass
  659. except:
  660. pass"""
  661. self.check(b, a)
  662. def test_one_line_suites(self):
  663. b = """
  664. try: raise TypeError
  665. except TypeError, e:
  666. pass
  667. """
  668. a = """
  669. try: raise TypeError
  670. except TypeError as e:
  671. pass
  672. """
  673. self.check(b, a)
  674. b = """
  675. try:
  676. raise TypeError
  677. except TypeError, e: pass
  678. """
  679. a = """
  680. try:
  681. raise TypeError
  682. except TypeError as e: pass
  683. """
  684. self.check(b, a)
  685. b = """
  686. try: raise TypeError
  687. except TypeError, e: pass
  688. """
  689. a = """
  690. try: raise TypeError
  691. except TypeError as e: pass
  692. """
  693. self.check(b, a)
  694. b = """
  695. try: raise TypeError
  696. except TypeError, e: pass
  697. else: function()
  698. finally: done()
  699. """
  700. a = """
  701. try: raise TypeError
  702. except TypeError as e: pass
  703. else: function()
  704. finally: done()
  705. """
  706. self.check(b, a)
  707. # These should not be touched:
  708. def test_unchanged_1(self):
  709. s = """
  710. try:
  711. pass
  712. except:
  713. pass"""
  714. self.unchanged(s)
  715. def test_unchanged_2(self):
  716. s = """
  717. try:
  718. pass
  719. except Exception:
  720. pass"""
  721. self.unchanged(s)
  722. def test_unchanged_3(self):
  723. s = """
  724. try:
  725. pass
  726. except (Exception, SystemExit):
  727. pass"""
  728. self.unchanged(s)
  729. class Test_raise(FixerTestCase):
  730. fixer = "raise"
  731. def test_basic(self):
  732. b = """raise Exception, 5"""
  733. a = """raise Exception(5)"""
  734. self.check(b, a)
  735. def test_prefix_preservation(self):
  736. b = """raise Exception,5"""
  737. a = """raise Exception(5)"""
  738. self.check(b, a)
  739. b = """raise Exception, 5"""
  740. a = """raise Exception(5)"""
  741. self.check(b, a)
  742. def test_with_comments(self):
  743. b = """raise Exception, 5 # foo"""
  744. a = """raise Exception(5) # foo"""
  745. self.check(b, a)
  746. b = """raise E, (5, 6) % (a, b) # foo"""
  747. a = """raise E((5, 6) % (a, b)) # foo"""
  748. self.check(b, a)
  749. b = """def foo():
  750. raise Exception, 5, 6 # foo"""
  751. a = """def foo():
  752. raise Exception(5).with_traceback(6) # foo"""
  753. self.check(b, a)
  754. def test_None_value(self):
  755. b = """raise Exception(5), None, tb"""
  756. a = """raise Exception(5).with_traceback(tb)"""
  757. self.check(b, a)
  758. def test_tuple_value(self):
  759. b = """raise Exception, (5, 6, 7)"""
  760. a = """raise Exception(5, 6, 7)"""
  761. self.check(b, a)
  762. def test_tuple_detection(self):
  763. b = """raise E, (5, 6) % (a, b)"""
  764. a = """raise E((5, 6) % (a, b))"""
  765. self.check(b, a)
  766. def test_tuple_exc_1(self):
  767. b = """raise (((E1, E2), E3), E4), V"""
  768. a = """raise E1(V)"""
  769. self.check(b, a)
  770. def test_tuple_exc_2(self):
  771. b = """raise (E1, (E2, E3), E4), V"""
  772. a = """raise E1(V)"""
  773. self.check(b, a)
  774. # These should produce a warning
  775. def test_string_exc(self):
  776. s = """raise 'foo'"""
  777. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  778. def test_string_exc_val(self):
  779. s = """raise "foo", 5"""
  780. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  781. def test_string_exc_val_tb(self):
  782. s = """raise "foo", 5, 6"""
  783. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  784. # These should result in traceback-assignment
  785. def test_tb_1(self):
  786. b = """def foo():
  787. raise Exception, 5, 6"""
  788. a = """def foo():
  789. raise Exception(5).with_traceback(6)"""
  790. self.check(b, a)
  791. def test_tb_2(self):
  792. b = """def foo():
  793. a = 5
  794. raise Exception, 5, 6
  795. b = 6"""
  796. a = """def foo():
  797. a = 5
  798. raise Exception(5).with_traceback(6)
  799. b = 6"""
  800. self.check(b, a)
  801. def test_tb_3(self):
  802. b = """def foo():
  803. raise Exception,5,6"""
  804. a = """def foo():
  805. raise Exception(5).with_traceback(6)"""
  806. self.check(b, a)
  807. def test_tb_4(self):
  808. b = """def foo():
  809. a = 5
  810. raise Exception,5,6
  811. b = 6"""
  812. a = """def foo():
  813. a = 5
  814. raise Exception(5).with_traceback(6)
  815. b = 6"""
  816. self.check(b, a)
  817. def test_tb_5(self):
  818. b = """def foo():
  819. raise Exception, (5, 6, 7), 6"""
  820. a = """def foo():
  821. raise Exception(5, 6, 7).with_traceback(6)"""
  822. self.check(b, a)
  823. def test_tb_6(self):
  824. b = """def foo():
  825. a = 5
  826. raise Exception, (5, 6, 7), 6
  827. b = 6"""
  828. a = """def foo():
  829. a = 5
  830. raise Exception(5, 6, 7).with_traceback(6)
  831. b = 6"""
  832. self.check(b, a)
  833. class Test_throw(FixerTestCase):
  834. fixer = "throw"
  835. def test_1(self):
  836. b = """g.throw(Exception, 5)"""
  837. a = """g.throw(Exception(5))"""
  838. self.check(b, a)
  839. def test_2(self):
  840. b = """g.throw(Exception,5)"""
  841. a = """g.throw(Exception(5))"""
  842. self.check(b, a)
  843. def test_3(self):
  844. b = """g.throw(Exception, (5, 6, 7))"""
  845. a = """g.throw(Exception(5, 6, 7))"""
  846. self.check(b, a)
  847. def test_4(self):
  848. b = """5 + g.throw(Exception, 5)"""
  849. a = """5 + g.throw(Exception(5))"""
  850. self.check(b, a)
  851. # These should produce warnings
  852. def test_warn_1(self):
  853. s = """g.throw("foo")"""
  854. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  855. def test_warn_2(self):
  856. s = """g.throw("foo", 5)"""
  857. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  858. def test_warn_3(self):
  859. s = """g.throw("foo", 5, 6)"""
  860. self.warns_unchanged(s, "Python 3 does not support string exceptions")
  861. # These should not be touched
  862. def test_untouched_1(self):
  863. s = """g.throw(Exception)"""
  864. self.unchanged(s)
  865. def test_untouched_2(self):
  866. s = """g.throw(Exception(5, 6))"""
  867. self.unchanged(s)
  868. def test_untouched_3(self):
  869. s = """5 + g.throw(Exception(5, 6))"""
  870. self.unchanged(s)
  871. # These should result in traceback-assignment
  872. def test_tb_1(self):
  873. b = """def foo():
  874. g.throw(Exception, 5, 6)"""
  875. a = """def foo():
  876. g.throw(Exception(5).with_traceback(6))"""
  877. self.check(b, a)
  878. def test_tb_2(self):
  879. b = """def foo():
  880. a = 5
  881. g.throw(Exception, 5, 6)
  882. b = 6"""
  883. a = """def foo():
  884. a = 5
  885. g.throw(Exception(5).with_traceback(6))
  886. b = 6"""
  887. self.check(b, a)
  888. def test_tb_3(self):
  889. b = """def foo():
  890. g.throw(Exception,5,6)"""
  891. a = """def foo():
  892. g.throw(Exception(5).with_traceback(6))"""
  893. self.check(b, a)
  894. def test_tb_4(self):
  895. b = """def foo():
  896. a = 5
  897. g.throw(Exception,5,6)
  898. b = 6"""
  899. a = """def foo():
  900. a = 5
  901. g.throw(Exception(5).with_traceback(6))
  902. b = 6"""
  903. self.check(b, a)
  904. def test_tb_5(self):
  905. b = """def foo():
  906. g.throw(Exception, (5, 6, 7), 6)"""
  907. a = """def foo():
  908. g.throw(Exception(5, 6, 7).with_traceback(6))"""
  909. self.check(b, a)
  910. def test_tb_6(self):
  911. b = """def foo():
  912. a = 5
  913. g.throw(Exception, (5, 6, 7), 6)
  914. b = 6"""
  915. a = """def foo():
  916. a = 5
  917. g.throw(Exception(5, 6, 7).with_traceback(6))
  918. b = 6"""
  919. self.check(b, a)
  920. def test_tb_7(self):
  921. b = """def foo():
  922. a + g.throw(Exception, 5, 6)"""
  923. a = """def foo():
  924. a + g.throw(Exception(5).with_traceback(6))"""
  925. self.check(b, a)
  926. def test_tb_8(self):
  927. b = """def foo():
  928. a = 5
  929. a + g.throw(Exception, 5, 6)
  930. b = 6"""
  931. a = """def foo():
  932. a = 5
  933. a + g.throw(Exception(5).with_traceback(6))
  934. b = 6"""
  935. self.check(b, a)
  936. class Test_long(FixerTestCase):
  937. fixer = "long"
  938. def test_1(self):
  939. b = """x = long(x)"""
  940. a = """x = int(x)"""
  941. self.check(b, a)
  942. def test_2(self):
  943. b = """y = isinstance(x, long)"""
  944. a = """y = isinstance(x, int)"""
  945. self.check(b, a)
  946. def test_3(self):
  947. b = """z = type(x) in (int, long)"""
  948. a = """z = type(x) in (int, int)"""
  949. self.check(b, a)
  950. def test_unchanged(self):
  951. s = """long = True"""
  952. self.unchanged(s)
  953. s = """s.long = True"""
  954. self.unchanged(s)
  955. s = """def long(): pass"""
  956. self.unchanged(s)
  957. s = """class long(): pass"""
  958. self.unchanged(s)
  959. s = """def f(long): pass"""
  960. self.unchanged(s)
  961. s = """def f(g, long): pass"""
  962. self.unchanged(s)
  963. s = """def f(x, long=True): pass"""
  964. self.unchanged(s)
  965. def test_prefix_preservation(self):
  966. b = """x = long( x )"""
  967. a = """x = int( x )"""
  968. self.check(b, a)
  969. class Test_execfile(FixerTestCase):
  970. fixer = "execfile"
  971. def test_conversion(self):
  972. b = """execfile("fn")"""
  973. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'))"""
  974. self.check(b, a)
  975. b = """execfile("fn", glob)"""
  976. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), glob)"""
  977. self.check(b, a)
  978. b = """execfile("fn", glob, loc)"""
  979. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), glob, loc)"""
  980. self.check(b, a)
  981. b = """execfile("fn", globals=glob)"""
  982. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), globals=glob)"""
  983. self.check(b, a)
  984. b = """execfile("fn", locals=loc)"""
  985. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), locals=loc)"""
  986. self.check(b, a)
  987. b = """execfile("fn", globals=glob, locals=loc)"""
  988. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), globals=glob, locals=loc)"""
  989. self.check(b, a)
  990. def test_spacing(self):
  991. b = """execfile( "fn" )"""
  992. a = """exec(compile(open( "fn", "rb" ).read(), "fn", 'exec'))"""
  993. self.check(b, a)
  994. b = """execfile("fn", globals = glob)"""
  995. a = """exec(compile(open("fn", "rb").read(), "fn", 'exec'), globals = glob)"""
  996. self.check(b, a)
  997. class Test_isinstance(FixerTestCase):
  998. fixer = "isinstance"
  999. def test_remove_multiple_items(self):
  1000. b = """isinstance(x, (int, int, int))"""
  1001. a = """isinstance(x, int)"""
  1002. self.check(b, a)
  1003. b = """isinstance(x, (int, float, int, int, float))"""
  1004. a = """isinstance(x, (int, float))"""
  1005. self.check(b, a)
  1006. b = """isinstance(x, (int, float, int, int, float, str))"""
  1007. a = """isinstance(x, (int, float, str))"""
  1008. self.check(b, a)
  1009. b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""
  1010. a = """isinstance(foo() + bar(), (x(), y(), x(), int))"""
  1011. self.check(b, a)
  1012. def test_prefix_preservation(self):
  1013. b = """if isinstance( foo(), ( bar, bar, baz )) : pass"""
  1014. a = """if isinstance( foo(), ( bar, baz )) : pass"""
  1015. self.check(b, a)
  1016. def test_unchanged(self):
  1017. self.unchanged("isinstance(x, (str, int))")
  1018. class Test_dict(FixerTestCase):
  1019. fixer = "dict"
  1020. def test_prefix_preservation(self):
  1021. b = "if d. keys ( ) : pass"
  1022. a = "if list(d. keys ( )) : pass"
  1023. self.check(b, a)
  1024. b = "if d. items ( ) : pass"
  1025. a = "if list(d. items ( )) : pass"
  1026. self.check(b, a)
  1027. b = "if d. iterkeys ( ) : pass"
  1028. a = "if iter(d. keys ( )) : pass"
  1029. self.check(b, a)
  1030. b = "[i for i in d. iterkeys( ) ]"
  1031. a = "[i for i in d. keys( ) ]"
  1032. self.check(b, a)
  1033. b = "if d. viewkeys ( ) : pass"
  1034. a = "if d. keys ( ) : pass"
  1035. self.check(b, a)
  1036. b = "[i for i in d. viewkeys( ) ]"
  1037. a = "[i for i in d. keys( ) ]"
  1038. self.check(b, a)
  1039. def test_trailing_comment(self):
  1040. b = "d.keys() # foo"
  1041. a = "list(d.keys()) # foo"
  1042. self.check(b, a)
  1043. b = "d.items() # foo"
  1044. a = "list(d.items()) # foo"
  1045. self.check(b, a)
  1046. b = "d.iterkeys() # foo"
  1047. a = "iter(d.keys()) # foo"
  1048. self.check(b, a)
  1049. b = """[i for i in d.iterkeys() # foo
  1050. ]"""
  1051. a = """[i for i in d.keys() # foo
  1052. ]"""
  1053. self.check(b, a)
  1054. b = """[i for i in d.iterkeys() # foo
  1055. ]"""
  1056. a = """[i for i in d.keys() # foo
  1057. ]"""
  1058. self.check(b, a)
  1059. b = "d.viewitems() # foo"
  1060. a = "d.items() # foo"
  1061. self.check(b, a)
  1062. def test_unchanged(self):
  1063. for wrapper in fixer_util.consuming_calls:
  1064. s = "s = %s(d.keys())" % wrapper
  1065. self.unchanged(s)
  1066. s = "s = %s(d.values())" % wrapper
  1067. self.unchanged(s)
  1068. s = "s = %s(d.items())" % wrapper
  1069. self.unchanged(s)
  1070. def test_01(self):
  1071. b = "d.keys()"
  1072. a = "list(d.keys())"
  1073. self.check(b, a)
  1074. b = "a[0].foo().keys()"
  1075. a = "list(a[0].foo().keys())"
  1076. self.check(b, a)
  1077. def test_02(self):
  1078. b = "d.items()"
  1079. a = "list(d.items())"
  1080. self.check(b, a)
  1081. def test_03(self):
  1082. b = "d.values()"
  1083. a = "list(d.values())"
  1084. self.check(b, a)
  1085. def test_04(self):
  1086. b = "d.iterkeys()"
  1087. a = "iter(d.keys())"
  1088. self.check(b, a)
  1089. def test_05(self):
  1090. b = "d.iteritems()"
  1091. a = "iter(d.items())"
  1092. self.check(b, a)
  1093. def test_06(self):
  1094. b = "d.itervalues()"
  1095. a = "iter(d.values())"
  1096. self.check(b, a)
  1097. def test_07(self):
  1098. s = "list(d.keys())"
  1099. self.unchanged(s)
  1100. def test_08(self):
  1101. s = "sorted(d.keys())"
  1102. self.unchanged(s)
  1103. def test_09(self):
  1104. b = "iter(d.keys())"
  1105. a = "iter(list(d.keys()))"
  1106. self.check(b, a)
  1107. def test_10(self):
  1108. b = "foo(d.keys())"
  1109. a = "foo(list(d.keys()))"
  1110. self.check(b, a)
  1111. def test_11(self):
  1112. b = "for i in d.keys(): print i"
  1113. a = "for i in list(d.keys()): print i"
  1114. self.check(b, a)
  1115. def test_12(self):
  1116. b = "for i in d.iterkeys(): print i"
  1117. a = "for i in d.keys(): print i"
  1118. self.check(b, a)
  1119. def test_13(self):
  1120. b = "[i for i in d.keys()]"
  1121. a = "[i for i in list(d.keys())]"
  1122. self.check(b, a)
  1123. def test_14(self):
  1124. b = "[i for i in d.iterkeys()]"
  1125. a = "[i for i in d.keys()]"
  1126. self.check(b, a)
  1127. def test_15(self):
  1128. b = "(i for i in d.keys())"
  1129. a = "(i for i in list(d.keys()))"
  1130. self.check(b, a)
  1131. def test_16(self):
  1132. b = "(i for i in d.iterkeys())"
  1133. a = "(i for i in d.keys())"
  1134. self.check(b, a)
  1135. def test_17(self):
  1136. b = "iter(d.iterkeys())"
  1137. a = "iter(d.keys())"
  1138. self.check(b, a)
  1139. def test_18(self):
  1140. b = "list(d.iterkeys())"
  1141. a = "list(d.keys())"
  1142. self.check(b, a)
  1143. def test_19(self):
  1144. b = "sorted(d.iterkeys())"
  1145. a = "sorted(d.keys())"
  1146. self.check(b, a)
  1147. def test_20(self):
  1148. b = "foo(d.iterkeys())"
  1149. a = "foo(iter(d.keys()))"
  1150. self.check(b, a)
  1151. def test_21(self):
  1152. b = "print h.iterkeys().next()"
  1153. a = "print iter(h.keys()).next()"
  1154. self.check(b, a)
  1155. def test_22(self):
  1156. b = "print h.keys()[0]"
  1157. a = "print list(h.keys())[0]"
  1158. self.check(b, a)
  1159. def test_23(self):
  1160. b = "print list(h.iterkeys().next())"
  1161. a = "print list(iter(h.keys()).next())"
  1162. self.check(b, a)
  1163. def test_24(self):
  1164. b = "for x in h.keys()[0]: print x"
  1165. a = "for x in list(h.keys())[0]: print x"
  1166. self.check(b, a)
  1167. def test_25(self):
  1168. b = "d.viewkeys()"
  1169. a = "d.keys()"
  1170. self.check(b, a)
  1171. def test_26(self):
  1172. b = "d.viewitems()"
  1173. a = "d.items()"
  1174. self.check(b, a)
  1175. def test_27(self):
  1176. b = "d.viewvalues()"
  1177. a = "d.values()"
  1178. self.check(b, a)
  1179. def test_28(self):
  1180. b = "[i for i in d.viewkeys()]"
  1181. a = "[i for i in d.keys()]"
  1182. self.check(b, a)
  1183. def test_29(self):
  1184. b = "(i for i in d.viewkeys())"
  1185. a = "(i for i in d.keys())"
  1186. self.check(b, a)
  1187. def test_30(self):
  1188. b = "iter(d.viewkeys())"
  1189. a = "iter(d.keys())"
  1190. self.check(b, a)
  1191. def test_31(self):
  1192. b = "list(d.viewkeys())"
  1193. a = "list(d.keys())"
  1194. self.check(b, a)
  1195. def test_32(self):
  1196. b = "sorted(d.viewkeys())"
  1197. a = "sorted(d.keys())"
  1198. self.check(b, a)
  1199. class Test_xrange(FixerTestCase):
  1200. fixer = "xrange"
  1201. def test_prefix_preservation(self):
  1202. b = """x = xrange( 10 )"""
  1203. a = """x = range( 10 )"""
  1204. self.check(b, a)
  1205. b = """x = xrange( 1 , 10 )"""
  1206. a = """x = range( 1 , 10 )"""
  1207. self.check(b, a)
  1208. b = """x = xrange( 0 , 10 , 2 )"""
  1209. a = """x = range( 0 , 10 , 2 )"""
  1210. self.check(b, a)
  1211. def test_single_arg(self):
  1212. b = """x = xrange(10)"""
  1213. a = """x = range(10)"""
  1214. self.check(b, a)
  1215. def test_two_args(self):
  1216. b = """x = xrange(1, 10)"""
  1217. a = """x = range(1, 10)"""
  1218. self.check(b, a)
  1219. def test_three_args(self):
  1220. b = """x = xrange(0, 10, 2)"""
  1221. a = """x = range(0, 10, 2)"""
  1222. self.check(b, a)
  1223. def test_wrap_in_list(self):
  1224. b = """x = range(10, 3, 9)"""
  1225. a = """x = list(range(10, 3, 9))"""
  1226. self.check(b, a)
  1227. b = """x = foo(range(10, 3, 9))"""
  1228. a = """x = foo(list(range(10, 3, 9)))"""
  1229. self.check(b, a)
  1230. b = """x = range(10, 3, 9) + [4]"""
  1231. a = """x = list(range(10, 3, 9)) + [4]"""
  1232. self.check(b, a)
  1233. b = """x = range(10)[::-1]"""
  1234. a = """x = list(range(10))[::-1]"""
  1235. self.check(b, a)
  1236. b = """x = range(10) [3]"""
  1237. a = """x = list(range(10)) [3]"""
  1238. self.check(b, a)
  1239. def test_xrange_in_for(self):
  1240. b = """for i in xrange(10):\n j=i"""
  1241. a = """for i in range(10):\n j=i"""
  1242. self.check(b, a)
  1243. b = """[i for i in xrange(10)]"""
  1244. a = """[i for i in range(10)]"""
  1245. self.check(b, a)
  1246. def test_range_in_for(self):
  1247. self.unchanged("for i in range(10): pass")
  1248. self.unchanged("[i for i in range(10)]")
  1249. def test_in_contains_test(self):
  1250. self.unchanged("x in range(10, 3, 9)")
  1251. def test_in_consuming_context(self):
  1252. for call in fixer_util.consuming_calls:
  1253. self.unchanged("a = %s(range(10))" % call)
  1254. class Test_xrange_with_reduce(FixerTestCase):
  1255. def setUp(self):
  1256. super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"])
  1257. def test_double_transform(self):
  1258. b = """reduce(x, xrange(5))"""
  1259. a = """from functools import reduce
  1260. reduce(x, range(5))"""
  1261. self.check(b, a)
  1262. class Test_raw_input(FixerTestCase):
  1263. fixer = "raw_input"
  1264. def test_prefix_preservation(self):
  1265. b = """x = raw_input( )"""
  1266. a = """x = input( )"""
  1267. self.check(b, a)
  1268. b = """x = raw_input( '' )"""
  1269. a = """x = input( '' )"""
  1270. self.check(b, a)
  1271. def test_1(self):
  1272. b = """x = raw_input()"""
  1273. a = """x = input()"""
  1274. self.check(b, a)
  1275. def test_2(self):
  1276. b = """x = raw_input('')"""
  1277. a = """x = input('')"""
  1278. self.check(b, a)
  1279. def test_3(self):
  1280. b = """x = raw_input('prompt')"""
  1281. a = """x = input('prompt')"""
  1282. self.check(b, a)
  1283. def test_4(self):
  1284. b = """x = raw_input(foo(a) + 6)"""
  1285. a = """x = input(foo(a) + 6)"""
  1286. self.check(b, a)
  1287. def test_5(self):
  1288. b = """x = raw_input(invite).split()"""
  1289. a = """x = input(invite).split()"""
  1290. self.check(b, a)
  1291. def test_6(self):
  1292. b = """x = raw_input(invite) . split ()"""
  1293. a = """x = input(invite) . split ()"""
  1294. self.check(b, a)
  1295. def test_8(self):
  1296. b = "x = int(raw_input())"
  1297. a = "x = int(input())"
  1298. self.check(b, a)
  1299. class Test_funcattrs(FixerTestCase):
  1300. fixer = "funcattrs"
  1301. attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"]
  1302. def test(self):
  1303. for attr in self.attrs:
  1304. b = "a.func_%s" % attr
  1305. a = "a.__%s__" % attr
  1306. self.check(b, a)
  1307. b = "self.foo.func_%s.foo_bar" % attr
  1308. a = "self.foo.__%s__.foo_bar" % attr
  1309. self.check(b, a)
  1310. def test_unchanged(self):
  1311. for attr in self.attrs:
  1312. s = "foo(func_%s + 5)" % attr
  1313. self.unchanged(s)
  1314. s = "f(foo.__%s__)" % attr
  1315. self.unchanged(s)
  1316. s = "f(foo.__%s__.foo)" % attr
  1317. self.unchanged(s)
  1318. class Test_xreadlines(FixerTestCase):
  1319. fixer = "xreadlines"
  1320. def test_call(self):
  1321. b = "for x in f.xreadlines(): pass"
  1322. a = "for x in f: pass"
  1323. self.check(b, a)
  1324. b = "for x in foo().xreadlines(): pass"
  1325. a = "for x in foo(): pass"
  1326. self.check(b, a)
  1327. b = "for x in (5 + foo()).xreadlines(): pass"
  1328. a = "for x in (5 + foo()): pass"
  1329. self.check(b, a)
  1330. def test_attr_ref(self):
  1331. b = "foo(f.xreadlines + 5)"
  1332. a = "foo(f.__iter__ + 5)"
  1333. self.check(b, a)
  1334. b = "foo(f().xreadlines + 5)"
  1335. a = "foo(f().__iter__ + 5)"
  1336. self.check(b, a)
  1337. b = "foo((5 + f()).xreadlines + 5)"
  1338. a = "foo((5 + f()).__iter__ + 5)"
  1339. self.check(b, a)
  1340. def test_unchanged(self):
  1341. s = "for x in f.xreadlines(5): pass"
  1342. self.unchanged(s)
  1343. s = "for x in f.xreadlines(k=5): pass"
  1344. self.unchanged(s)
  1345. s = "for x in f.xreadlines(*k, **v): pass"
  1346. self.unchanged(s)
  1347. s = "foo(xreadlines)"
  1348. self.unchanged(s)
  1349. class ImportsFixerTests:
  1350. def test_import_module(self):
  1351. for old, new in self.modules.items():
  1352. b = "import %s" % old
  1353. a = "import %s" % new
  1354. self.check(b, a)
  1355. b = "import foo, %s, bar" % old
  1356. a = "import foo, %s, bar" % new
  1357. self.check(b, a)
  1358. def test_import_from(self):
  1359. for old, new in self.modules.items():
  1360. b = "from %s import foo" % old
  1361. a = "from %s import foo" % new
  1362. self.check(b, a)
  1363. b = "from %s import foo, bar" % old
  1364. a = "from %s import foo, bar" % new
  1365. self.check(b, a)
  1366. b = "from %s import (yes, no)" % old
  1367. a = "from %s import (yes, no)" % new
  1368. self.check(b, a)
  1369. def test_import_module_as(self):
  1370. for old, new in self.modules.items():
  1371. b = "import %s as foo_bar" % old
  1372. a = "import %s as foo_bar" % new
  1373. self.check(b, a)
  1374. b = "import %s as foo_bar" % old
  1375. a = "import %s as foo_bar" % new
  1376. self.check(b, a)
  1377. def test_import_from_as(self):
  1378. for old, new in self.modules.items():
  1379. b = "from %s import foo as bar" % old
  1380. a = "from %s import foo as bar" % new
  1381. self.check(b, a)
  1382. def test_star(self):
  1383. for old, new in self.modules.items():
  1384. b = "from %s import *" % old
  1385. a = "from %s import *" % new
  1386. self.check(b, a)
  1387. def test_import_module_usage(self):
  1388. for old, new in self.modules.items():
  1389. b = """
  1390. import %s
  1391. foo(%s.bar)
  1392. """ % (old, old)
  1393. a = """
  1394. import %s
  1395. foo(%s.bar)
  1396. """ % (new, new)
  1397. self.check(b, a)
  1398. b = """
  1399. from %s import x
  1400. %s = 23
  1401. """ % (old, old)
  1402. a = """
  1403. from %s import x
  1404. %s = 23
  1405. """ % (new, old)
  1406. self.check(b, a)
  1407. s = """
  1408. def f():
  1409. %s.method()
  1410. """ % (old,)
  1411. self.unchanged(s)
  1412. # test nested usage
  1413. b = """
  1414. import %s
  1415. %s.bar(%s.foo)
  1416. """ % (old, old, old)
  1417. a = """
  1418. import %s
  1419. %s.bar(%s.foo)
  1420. """ % (new, new, new)
  1421. self.check(b, a)
  1422. b = """
  1423. import %s
  1424. x.%s
  1425. """ % (old, old)
  1426. a = """
  1427. import %s
  1428. x.%s
  1429. """ % (new, old)
  1430. self.check(b, a)
  1431. class Test_imports(FixerTestCase, ImportsFixerTests):
  1432. fixer = "imports"
  1433. from ..fixes.fix_imports import MAPPING as modules
  1434. def test_multiple_imports(self):
  1435. b = """import urlparse, cStringIO"""
  1436. a = """import urllib.parse, io"""
  1437. self.check(b, a)
  1438. def test_multiple_imports_as(self):
  1439. b = """
  1440. import copy_reg as bar, HTMLParser as foo, urlparse
  1441. s = urlparse.spam(bar.foo())
  1442. """
  1443. a = """
  1444. import copyreg as bar, html.parser as foo, urllib.parse
  1445. s = urllib.parse.spam(bar.foo())
  1446. """
  1447. self.check(b, a)
  1448. class Test_imports2(FixerTestCase, ImportsFixerTests):
  1449. fixer = "imports2"
  1450. from ..fixes.fix_imports2 import MAPPING as modules
  1451. class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests):
  1452. def setUp(self):
  1453. super(Test_imports_fixer_order, self).setUp(['imports', 'imports2'])
  1454. from ..fixes.fix_imports2 import MAPPING as mapping2
  1455. self.modules = mapping2.copy()
  1456. from ..fixes.fix_imports import MAPPING as mapping1
  1457. for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
  1458. self.modules[key] = mapping1[key]
  1459. def test_after_local_imports_refactoring(self):
  1460. for fix in ("imports", "imports2"):
  1461. self.fixer = fix
  1462. self.assert_runs_after("import")
  1463. class Test_urllib(FixerTestCase):
  1464. fixer = "urllib"
  1465. from ..fixes.fix_urllib import MAPPING as modules
  1466. def test_import_module(self):
  1467. for old, changes in self.modules.items():
  1468. b = "import %s" % old
  1469. a = "import %s" % ", ".join(map(itemgetter(0), changes))
  1470. self.check(b, a)
  1471. def test_import_from(self):
  1472. for old, changes in self.modules.items():
  1473. all_members = []
  1474. for new, members in changes:
  1475. for member in members:
  1476. all_members.append(member)
  1477. b = "from %s import %s" % (old, member)
  1478. a = "from %s import %s" % (new, member)
  1479. self.check(b, a)
  1480. s = "from foo import %s" % member
  1481. self.unchanged(s)
  1482. b = "from %s import %s" % (old, ", ".join(members))
  1483. a = "from %s import %s" % (new, ", ".join(members))
  1484. self.check(b, a)
  1485. s = "from foo import %s" % ", ".join(members)
  1486. self.unchanged(s)
  1487. # test the breaking of a module into multiple replacements
  1488. b = "from %s import %s" % (old, ", ".join(all_members))
  1489. a = "\n".join(["from %s import %s" % (new, ", ".join(members))
  1490. for (new, members) in changes])
  1491. self.check(b, a)
  1492. def test_import_module_as(self):
  1493. for old in self.modules:
  1494. s = "import %s as foo" % old
  1495. self.warns_unchanged(s, "This module is now multiple modules")
  1496. def test_import_from_as(self):
  1497. for old, changes in self.modules.items():
  1498. for new, members in changes:
  1499. for member in members:
  1500. b = "from %s import %s as foo_bar" % (old, member)
  1501. a = "from %s import %s as foo_bar" % (new, member)
  1502. self.check(b, a)
  1503. b = "from %s import %s as blah, %s" % (old, member, member)
  1504. a = "from %s import %s as blah, %s" % (new, member, member)
  1505. self.check(b, a)
  1506. def test_star(self):
  1507. for old in self.modules:
  1508. s = "from %s import *" % old
  1509. self.warns_unchanged(s, "Cannot handle star imports")
  1510. def test_indented(self):
  1511. b = """
  1512. def foo():
  1513. from urllib import urlencode, urlopen
  1514. """
  1515. a = """
  1516. def foo():
  1517. from urllib.parse import urlencode
  1518. from urllib.request import urlopen
  1519. """
  1520. self.check(b, a)
  1521. b = """
  1522. def foo():
  1523. other()
  1524. from urllib import urlencode, urlopen
  1525. """
  1526. a = """
  1527. def foo():
  1528. other()
  1529. from urllib.parse import urlencode
  1530. from urllib.request import urlopen
  1531. """
  1532. self.check(b, a)
  1533. def test_single_import(self):
  1534. b = "from urllib import getproxies"
  1535. a = "from urllib.request import getproxies"
  1536. self.check(b, a)
  1537. def test_import_module_usage(self):
  1538. for old, changes in self.modules.items():
  1539. for new, members in changes:
  1540. for member in members:
  1541. new_import = ", ".join([n for (n, mems)
  1542. in self.modules[old]])
  1543. b = """
  1544. import %s
  1545. foo(%s.%s)
  1546. """ % (old, old, member)
  1547. a = """
  1548. import %s
  1549. foo(%s.%s)
  1550. """ % (new_import, new, member)
  1551. self.check(b, a)
  1552. b = """
  1553. import %s
  1554. %s.%s(%s.%s)
  1555. """ % (old, old, member, old, member)
  1556. a = """
  1557. import %s
  1558. %s.%s(%s.%s)
  1559. """ % (new_import, new, member, new, member)
  1560. self.check(b, a)
  1561. class Test_input(FixerTestCase):
  1562. fixer = "input"
  1563. def test_prefix_preservation(self):
  1564. b = """x = input( )"""
  1565. a = """x = eval(input( ))"""
  1566. self.check(b, a)
  1567. b = """x = input( '' )"""
  1568. a = """x = eval(input( '' ))"""
  1569. self.check(b, a)
  1570. def test_trailing_comment(self):
  1571. b = """x = input() # foo"""
  1572. a = """x = eval(input()) # foo"""
  1573. self.check(b, a)
  1574. def test_idempotency(self):
  1575. s = """x = eval(input())"""
  1576. self.unchanged(s)
  1577. s = """x = eval(input(''))"""
  1578. self.unchanged(s)
  1579. s = """x = eval(input(foo(5) + 9))"""
  1580. self.unchanged(s)
  1581. def test_1(self):
  1582. b = """x = input()"""
  1583. a = """x = eval(input())"""
  1584. self.check(b, a)
  1585. def test_2(self):
  1586. b = """x = input('')"""
  1587. a = """x = eval(input(''))"""
  1588. self.check(b, a)
  1589. def test_3(self):
  1590. b = """x = input('prompt')"""
  1591. a = """x = eval(input('prompt'))"""
  1592. self.check(b, a)
  1593. def test_4(self):
  1594. b = """x = input(foo(5) + 9)"""
  1595. a = """x = eval(input(foo(5) + 9))"""
  1596. self.check(b, a)
  1597. class Test_tuple_params(FixerTestCase):
  1598. fixer = "tuple_params"
  1599. def test_unchanged_1(self):
  1600. s = """def foo(): pass"""
  1601. self.unchanged(s)
  1602. def test_unchanged_2(self):
  1603. s = """def foo(a, b, c): pass"""
  1604. self.unchanged(s)
  1605. def test_unchanged_3(self):
  1606. s = """def foo(a=3, b=4, c=5): pass"""
  1607. self.unchanged(s)
  1608. def test_1(self):
  1609. b = """
  1610. def foo(((a, b), c)):
  1611. x = 5"""
  1612. a = """
  1613. def foo(xxx_todo_changeme):
  1614. ((a, b), c) = xxx_todo_changeme
  1615. x = 5"""
  1616. self.check(b, a)
  1617. def test_2(self):
  1618. b = """
  1619. def foo(((a, b), c), d):
  1620. x = 5"""
  1621. a = """
  1622. def foo(xxx_todo_changeme, d):
  1623. ((a, b), c) = xxx_todo_changeme
  1624. x = 5"""
  1625. self.check(b, a)
  1626. def test_3(self):
  1627. b = """
  1628. def foo(((a, b), c), d) -> e:
  1629. x = 5"""
  1630. a = """
  1631. def foo(xxx_todo_changeme, d) -> e:
  1632. ((a, b), c) = xxx_todo_changeme
  1633. x = 5"""
  1634. self.check(b, a)
  1635. def test_semicolon(self):
  1636. b = """
  1637. def foo(((a, b), c)): x = 5; y = 7"""
  1638. a = """
  1639. def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""
  1640. self.check(b, a)
  1641. def test_keywords(self):
  1642. b = """
  1643. def foo(((a, b), c), d, e=5) -> z:
  1644. x = 5"""
  1645. a = """
  1646. def foo(xxx_todo_changeme, d, e=5) -> z:
  1647. ((a, b), c) = xxx_todo_changeme
  1648. x = 5"""
  1649. self.check(b, a)
  1650. def test_varargs(self):
  1651. b = """
  1652. def foo(((a, b), c), d, *vargs, **kwargs) -> z:
  1653. x = 5"""
  1654. a = """
  1655. def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:
  1656. ((a, b), c) = xxx_todo_changeme
  1657. x = 5"""
  1658. self.check(b, a)
  1659. def test_multi_1(self):
  1660. b = """
  1661. def foo(((a, b), c), (d, e, f)) -> z:
  1662. x = 5"""
  1663. a = """
  1664. def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
  1665. ((a, b), c) = xxx_todo_changeme
  1666. (d, e, f) = xxx_todo_changeme1
  1667. x = 5"""
  1668. self.check(b, a)
  1669. def test_multi_2(self):
  1670. b = """
  1671. def foo(x, ((a, b), c), d, (e, f, g), y) -> z:
  1672. x = 5"""
  1673. a = """
  1674. def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:
  1675. ((a, b), c) = xxx_todo_changeme
  1676. (e, f, g) = xxx_todo_changeme1
  1677. x = 5"""
  1678. self.check(b, a)
  1679. def test_docstring(self):
  1680. b = """
  1681. def foo(((a, b), c), (d, e, f)) -> z:
  1682. "foo foo foo foo"
  1683. x = 5"""
  1684. a = """
  1685. def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
  1686. "foo foo foo foo"
  1687. ((a, b), c) = xxx_todo_changeme
  1688. (d, e, f) = xxx_todo_changeme1
  1689. x = 5"""
  1690. self.check(b, a)
  1691. def test_lambda_no_change(self):
  1692. s = """lambda x: x + 5"""
  1693. self.unchanged(s)
  1694. def test_lambda_parens_single_arg(self):
  1695. b = """lambda (x): x + 5"""
  1696. a = """lambda x: x + 5"""
  1697. self.check(b, a)
  1698. b = """lambda(x): x + 5"""
  1699. a = """lambda x: x + 5"""
  1700. self.check(b, a)
  1701. b = """lambda ((((x)))): x + 5"""
  1702. a = """lambda x: x + 5"""
  1703. self.check(b, a)
  1704. b = """lambda((((x)))): x + 5"""
  1705. a = """lambda x: x + 5"""
  1706. self.check(b, a)
  1707. def test_lambda_simple(self):
  1708. b = """lambda (x, y): x + f(y)"""
  1709. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1710. self.check(b, a)
  1711. b = """lambda(x, y): x + f(y)"""
  1712. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1713. self.check(b, a)
  1714. b = """lambda (((x, y))): x + f(y)"""
  1715. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1716. self.check(b, a)
  1717. b = """lambda(((x, y))): x + f(y)"""
  1718. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1719. self.check(b, a)
  1720. def test_lambda_one_tuple(self):
  1721. b = """lambda (x,): x + f(x)"""
  1722. a = """lambda x1: x1[0] + f(x1[0])"""
  1723. self.check(b, a)
  1724. b = """lambda (((x,))): x + f(x)"""
  1725. a = """lambda x1: x1[0] + f(x1[0])"""
  1726. self.check(b, a)
  1727. def test_lambda_simple_multi_use(self):
  1728. b = """lambda (x, y): x + x + f(x) + x"""
  1729. a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""
  1730. self.check(b, a)
  1731. def test_lambda_simple_reverse(self):
  1732. b = """lambda (x, y): y + x"""
  1733. a = """lambda x_y: x_y[1] + x_y[0]"""
  1734. self.check(b, a)
  1735. def test_lambda_nested(self):
  1736. b = """lambda (x, (y, z)): x + y + z"""
  1737. a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
  1738. self.check(b, a)
  1739. b = """lambda (((x, (y, z)))): x + y + z"""
  1740. a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
  1741. self.check(b, a)
  1742. def test_lambda_nested_multi_use(self):
  1743. b = """lambda (x, (y, z)): x + y + f(y)"""
  1744. a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""
  1745. self.check(b, a)
  1746. class Test_methodattrs(FixerTestCase):
  1747. fixer = "methodattrs"
  1748. attrs = ["func", "self", "class"]
  1749. def test(self):
  1750. for attr in self.attrs:
  1751. b = "a.im_%s" % attr
  1752. if attr == "class":
  1753. a = "a.__self__.__class__"
  1754. else:
  1755. a = "a.__%s__" % attr
  1756. self.check(b, a)
  1757. b = "self.foo.im_%s.foo_bar" % attr
  1758. if attr == "class":
  1759. a = "self.foo.__self__.__class__.foo_bar"
  1760. else:
  1761. a = "self.foo.__%s__.foo_bar" % attr
  1762. self.check(b, a)
  1763. def test_unchanged(self):
  1764. for attr in self.attrs:
  1765. s = "foo(im_%s + 5)" % attr
  1766. self.unchanged(s)
  1767. s = "f(foo.__%s__)" % attr
  1768. self.unchanged(s)
  1769. s = "f(foo.__%s__.foo)" % attr
  1770. self.unchanged(s)
  1771. class Test_next(FixerTestCase):
  1772. fixer = "next"
  1773. def test_1(self):
  1774. b = """it.next()"""
  1775. a = """next(it)"""
  1776. self.check(b, a)
  1777. def test_2(self):
  1778. b = """a.b.c.d.next()"""
  1779. a = """next(a.b.c.d)"""
  1780. self.check(b, a)
  1781. def test_3(self):
  1782. b = """(a + b).next()"""
  1783. a = """next((a + b))"""
  1784. self.check(b, a)
  1785. def test_4(self):
  1786. b = """a().next()"""
  1787. a = """next(a())"""
  1788. self.check(b, a)
  1789. def test_5(self):
  1790. b = """a().next() + b"""
  1791. a = """next(a()) + b"""
  1792. self.check(b, a)
  1793. def test_6(self):
  1794. b = """c( a().next() + b)"""
  1795. a = """c( next(a()) + b)"""
  1796. self.check(b, a)
  1797. def test_prefix_preservation_1(self):
  1798. b = """
  1799. for a in b:
  1800. foo(a)
  1801. a.next()
  1802. """
  1803. a = """
  1804. for a in b:
  1805. foo(a)
  1806. next(a)
  1807. """
  1808. self.check(b, a)
  1809. def test_prefix_preservation_2(self):
  1810. b = """
  1811. for a in b:
  1812. foo(a) # abc
  1813. # def
  1814. a.next()
  1815. """
  1816. a = """
  1817. for a in b:
  1818. foo(a) # abc
  1819. # def
  1820. next(a)
  1821. """
  1822. self.check(b, a)
  1823. def test_prefix_preservation_3(self):
  1824. b = """
  1825. next = 5
  1826. for a in b:
  1827. foo(a)
  1828. a.next()
  1829. """
  1830. a = """
  1831. next = 5
  1832. for a in b:
  1833. foo(a)
  1834. a.__next__()
  1835. """
  1836. self.check(b, a, ignore_warnings=True)
  1837. def test_prefix_preservation_4(self):
  1838. b = """
  1839. next = 5
  1840. for a in b:
  1841. foo(a) # abc
  1842. # def
  1843. a.next()
  1844. """
  1845. a = """
  1846. next = 5
  1847. for a in b:
  1848. foo(a) # abc
  1849. # def
  1850. a.__next__()
  1851. """
  1852. self.check(b, a, ignore_warnings=True)
  1853. def test_prefix_preservation_5(self):
  1854. b = """
  1855. next = 5
  1856. for a in b:
  1857. foo(foo(a), # abc
  1858. a.next())
  1859. """
  1860. a = """
  1861. next = 5
  1862. for a in b:
  1863. foo(foo(a), # abc
  1864. a.__next__())
  1865. """
  1866. self.check(b, a, ignore_warnings=True)
  1867. def test_prefix_preservation_6(self):
  1868. b = """
  1869. for a in b:
  1870. foo(foo(a), # abc
  1871. a.next())
  1872. """
  1873. a = """
  1874. for a in b:
  1875. foo(foo(a), # abc
  1876. next(a))
  1877. """
  1878. self.check(b, a)
  1879. def test_method_1(self):
  1880. b = """
  1881. class A:
  1882. def next(self):
  1883. pass
  1884. """
  1885. a = """
  1886. class A:
  1887. def __next__(self):
  1888. pass
  1889. """
  1890. self.check(b, a)
  1891. def test_method_2(self):
  1892. b = """
  1893. class A(object):
  1894. def next(self):
  1895. pass
  1896. """
  1897. a = """
  1898. class A(object):
  1899. def __next__(self):
  1900. pass
  1901. """
  1902. self.check(b, a)
  1903. def test_method_3(self):
  1904. b = """
  1905. class A:
  1906. def next(x):
  1907. pass
  1908. """
  1909. a = """
  1910. class A:
  1911. def __next__(x):
  1912. pass
  1913. """
  1914. self.check(b, a)
  1915. def test_method_4(self):
  1916. b = """
  1917. class A:
  1918. def __init__(self, foo):
  1919. self.foo = foo
  1920. def next(self):
  1921. pass
  1922. def __iter__(self):
  1923. return self
  1924. """
  1925. a = """
  1926. class A:
  1927. def __init__(self, foo):
  1928. self.foo = foo
  1929. def __next__(self):
  1930. pass
  1931. def __iter__(self):
  1932. return self
  1933. """
  1934. self.check(b, a)
  1935. def test_method_unchanged(self):
  1936. s = """
  1937. class A:
  1938. def next(self, a, b):
  1939. pass
  1940. """
  1941. self.unchanged(s)
  1942. def test_shadowing_assign_simple(self):
  1943. s = """
  1944. next = foo
  1945. class A:
  1946. def next(self, a, b):
  1947. pass
  1948. """
  1949. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1950. def test_shadowing_assign_tuple_1(self):
  1951. s = """
  1952. (next, a) = foo
  1953. class A:
  1954. def next(self, a, b):
  1955. pass
  1956. """
  1957. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1958. def test_shadowing_assign_tuple_2(self):
  1959. s = """
  1960. (a, (b, (next, c)), a) = foo
  1961. class A:
  1962. def next(self, a, b):
  1963. pass
  1964. """
  1965. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1966. def test_shadowing_assign_list_1(self):
  1967. s = """
  1968. [next, a] = foo
  1969. class A:
  1970. def next(self, a, b):
  1971. pass
  1972. """
  1973. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1974. def test_shadowing_assign_list_2(self):
  1975. s = """
  1976. [a, [b, [next, c]], a] = foo
  1977. class A:
  1978. def next(self, a, b):
  1979. pass
  1980. """
  1981. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1982. def test_builtin_assign(self):
  1983. s = """
  1984. def foo():
  1985. __builtin__.next = foo
  1986. class A:
  1987. def next(self, a, b):
  1988. pass
  1989. """
  1990. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1991. def test_builtin_assign_in_tuple(self):
  1992. s = """
  1993. def foo():
  1994. (a, __builtin__.next) = foo
  1995. class A:
  1996. def next(self, a, b):
  1997. pass
  1998. """
  1999. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2000. def test_builtin_assign_in_list(self):
  2001. s = """
  2002. def foo():
  2003. [a, __builtin__.next] = foo
  2004. class A:
  2005. def next(self, a, b):
  2006. pass
  2007. """
  2008. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2009. def test_assign_to_next(self):
  2010. s = """
  2011. def foo():
  2012. A.next = foo
  2013. class A:
  2014. def next(self, a, b):
  2015. pass
  2016. """
  2017. self.unchanged(s)
  2018. def test_assign_to_next_in_tuple(self):
  2019. s = """
  2020. def foo():
  2021. (a, A.next) = foo
  2022. class A:
  2023. def next(self, a, b):
  2024. pass
  2025. """
  2026. self.unchanged(s)
  2027. def test_assign_to_next_in_list(self):
  2028. s = """
  2029. def foo():
  2030. [a, A.next] = foo
  2031. class A:
  2032. def next(self, a, b):
  2033. pass
  2034. """
  2035. self.unchanged(s)
  2036. def test_shadowing_import_1(self):
  2037. s = """
  2038. import foo.bar as next
  2039. class A:
  2040. def next(self, a, b):
  2041. pass
  2042. """
  2043. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2044. def test_shadowing_import_2(self):
  2045. s = """
  2046. import bar, bar.foo as next
  2047. class A:
  2048. def next(self, a, b):
  2049. pass
  2050. """
  2051. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2052. def test_shadowing_import_3(self):
  2053. s = """
  2054. import bar, bar.foo as next, baz
  2055. class A:
  2056. def next(self, a, b):
  2057. pass
  2058. """
  2059. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2060. def test_shadowing_import_from_1(self):
  2061. s = """
  2062. from x import next
  2063. class A:
  2064. def next(self, a, b):
  2065. pass
  2066. """
  2067. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2068. def test_shadowing_import_from_2(self):
  2069. s = """
  2070. from x.a import next
  2071. class A:
  2072. def next(self, a, b):
  2073. pass
  2074. """
  2075. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2076. def test_shadowing_import_from_3(self):
  2077. s = """
  2078. from x import a, next, b
  2079. class A:
  2080. def next(self, a, b):
  2081. pass
  2082. """
  2083. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2084. def test_shadowing_import_from_4(self):
  2085. s = """
  2086. from x.a import a, next, b
  2087. class A:
  2088. def next(self, a, b):
  2089. pass
  2090. """
  2091. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2092. def test_shadowing_funcdef_1(self):
  2093. s = """
  2094. def next(a):
  2095. pass
  2096. class A:
  2097. def next(self, a, b):
  2098. pass
  2099. """
  2100. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2101. def test_shadowing_funcdef_2(self):
  2102. b = """
  2103. def next(a):
  2104. pass
  2105. class A:
  2106. def next(self):
  2107. pass
  2108. it.next()
  2109. """
  2110. a = """
  2111. def next(a):
  2112. pass
  2113. class A:
  2114. def __next__(self):
  2115. pass
  2116. it.__next__()
  2117. """
  2118. self.warns(b, a, "Calls to builtin next() possibly shadowed")
  2119. def test_shadowing_global_1(self):
  2120. s = """
  2121. def f():
  2122. global next
  2123. next = 5
  2124. """
  2125. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2126. def test_shadowing_global_2(self):
  2127. s = """
  2128. def f():
  2129. global a, next, b
  2130. next = 5
  2131. """
  2132. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2133. def test_shadowing_for_simple(self):
  2134. s = """
  2135. for next in it():
  2136. pass
  2137. b = 5
  2138. c = 6
  2139. """
  2140. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2141. def test_shadowing_for_tuple_1(self):
  2142. s = """
  2143. for next, b in it():
  2144. pass
  2145. b = 5
  2146. c = 6
  2147. """
  2148. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2149. def test_shadowing_for_tuple_2(self):
  2150. s = """
  2151. for a, (next, c), b in it():
  2152. pass
  2153. b = 5
  2154. c = 6
  2155. """
  2156. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2157. def test_noncall_access_1(self):
  2158. b = """gnext = g.next"""
  2159. a = """gnext = g.__next__"""
  2160. self.check(b, a)
  2161. def test_noncall_access_2(self):
  2162. b = """f(g.next + 5)"""
  2163. a = """f(g.__next__ + 5)"""
  2164. self.check(b, a)
  2165. def test_noncall_access_3(self):
  2166. b = """f(g().next + 5)"""
  2167. a = """f(g().__next__ + 5)"""
  2168. self.check(b, a)
  2169. class Test_nonzero(FixerTestCase):
  2170. fixer = "nonzero"
  2171. def test_1(self):
  2172. b = """
  2173. class A:
  2174. def __nonzero__(self):
  2175. pass
  2176. """
  2177. a = """
  2178. class A:
  2179. def __bool__(self):
  2180. pass
  2181. """
  2182. self.check(b, a)
  2183. def test_2(self):
  2184. b = """
  2185. class A(object):
  2186. def __nonzero__(self):
  2187. pass
  2188. """
  2189. a = """
  2190. class A(object):
  2191. def __bool__(self):
  2192. pass
  2193. """
  2194. self.check(b, a)
  2195. def test_unchanged_1(self):
  2196. s = """
  2197. class A(object):
  2198. def __bool__(self):
  2199. pass
  2200. """
  2201. self.unchanged(s)
  2202. def test_unchanged_2(self):
  2203. s = """
  2204. class A(object):
  2205. def __nonzero__(self, a):
  2206. pass
  2207. """
  2208. self.unchanged(s)
  2209. def test_unchanged_func(self):
  2210. s = """
  2211. def __nonzero__(self):
  2212. pass
  2213. """
  2214. self.unchanged(s)
  2215. class Test_numliterals(FixerTestCase):
  2216. fixer = "numliterals"
  2217. def test_octal_1(self):
  2218. b = """0755"""
  2219. a = """0o755"""
  2220. self.check(b, a)
  2221. def test_long_int_1(self):
  2222. b = """a = 12L"""
  2223. a = """a = 12"""
  2224. self.check(b, a)
  2225. def test_long_int_2(self):
  2226. b = """a = 12l"""
  2227. a = """a = 12"""
  2228. self.check(b, a)
  2229. def test_long_hex(self):
  2230. b = """b = 0x12l"""
  2231. a = """b = 0x12"""
  2232. self.check(b, a)
  2233. def test_comments_and_spacing(self):
  2234. b = """b = 0x12L"""
  2235. a = """b = 0x12"""
  2236. self.check(b, a)
  2237. b = """b = 0755 # spam"""
  2238. a = """b = 0o755 # spam"""
  2239. self.check(b, a)
  2240. def test_unchanged_int(self):
  2241. s = """5"""
  2242. self.unchanged(s)
  2243. def test_unchanged_float(self):
  2244. s = """5.0"""
  2245. self.unchanged(s)
  2246. def test_unchanged_octal(self):
  2247. s = """0o755"""
  2248. self.unchanged(s)
  2249. def test_unchanged_hex(self):
  2250. s = """0xABC"""
  2251. self.unchanged(s)
  2252. def test_unchanged_exp(self):
  2253. s = """5.0e10"""
  2254. self.unchanged(s)
  2255. def test_unchanged_complex_int(self):
  2256. s = """5 + 4j"""
  2257. self.unchanged(s)
  2258. def test_unchanged_complex_float(self):
  2259. s = """5.4 + 4.9j"""
  2260. self.unchanged(s)
  2261. def test_unchanged_complex_bare(self):
  2262. s = """4j"""
  2263. self.unchanged(s)
  2264. s = """4.4j"""
  2265. self.unchanged(s)
  2266. class Test_renames(FixerTestCase):
  2267. fixer = "renames"
  2268. modules = {"sys": ("maxint", "maxsize"),
  2269. }
  2270. def test_import_from(self):
  2271. for mod, (old, new) in list(self.modules.items()):
  2272. b = "from %s import %s" % (mod, old)
  2273. a = "from %s import %s" % (mod, new)
  2274. self.check(b, a)
  2275. s = "from foo import %s" % old
  2276. self.unchanged(s)
  2277. def test_import_from_as(self):
  2278. for mod, (old, new) in list(self.modules.items()):
  2279. b = "from %s import %s as foo_bar" % (mod, old)
  2280. a = "from %s import %s as foo_bar" % (mod, new)
  2281. self.check(b, a)
  2282. def test_import_module_usage(self):
  2283. for mod, (old, new) in list(self.modules.items()):
  2284. b = """
  2285. import %s
  2286. foo(%s, %s.%s)
  2287. """ % (mod, mod, mod, old)
  2288. a = """
  2289. import %s
  2290. foo(%s, %s.%s)
  2291. """ % (mod, mod, mod, new)
  2292. self.check(b, a)
  2293. def XXX_test_from_import_usage(self):
  2294. # not implemented yet
  2295. for mod, (old, new) in list(self.modules.items()):
  2296. b = """
  2297. from %s import %s
  2298. foo(%s, %s)
  2299. """ % (mod, old, mod, old)
  2300. a = """
  2301. from %s import %s
  2302. foo(%s, %s)
  2303. """ % (mod, new, mod, new)
  2304. self.check(b, a)
  2305. class Test_unicode(FixerTestCase):
  2306. fixer = "unicode"
  2307. def test_whitespace(self):
  2308. b = """unicode( x)"""
  2309. a = """str( x)"""
  2310. self.check(b, a)
  2311. b = """ unicode(x )"""
  2312. a = """ str(x )"""
  2313. self.check(b, a)
  2314. b = """ u'h'"""
  2315. a = """ 'h'"""
  2316. self.check(b, a)
  2317. def test_unicode_call(self):
  2318. b = """unicode(x, y, z)"""
  2319. a = """str(x, y, z)"""
  2320. self.check(b, a)
  2321. def test_unichr(self):
  2322. b = """unichr(u'h')"""
  2323. a = """chr('h')"""
  2324. self.check(b, a)
  2325. def test_unicode_literal_1(self):
  2326. b = '''u"x"'''
  2327. a = '''"x"'''
  2328. self.check(b, a)
  2329. def test_unicode_literal_2(self):
  2330. b = """ur'x'"""
  2331. a = """r'x'"""
  2332. self.check(b, a)
  2333. def test_unicode_literal_3(self):
  2334. b = """UR'''x''' """
  2335. a = """R'''x''' """
  2336. self.check(b, a)
  2337. def test_native_literal_escape_u(self):
  2338. b = r"""'\\\u20ac\U0001d121\\u20ac'"""
  2339. a = r"""'\\\\u20ac\\U0001d121\\u20ac'"""
  2340. self.check(b, a)
  2341. b = r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2342. a = r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2343. self.check(b, a)
  2344. def test_bytes_literal_escape_u(self):
  2345. b = r"""b'\\\u20ac\U0001d121\\u20ac'"""
  2346. a = r"""b'\\\u20ac\U0001d121\\u20ac'"""
  2347. self.check(b, a)
  2348. b = r"""br'\\\u20ac\U0001d121\\u20ac'"""
  2349. a = r"""br'\\\u20ac\U0001d121\\u20ac'"""
  2350. self.check(b, a)
  2351. def test_unicode_literal_escape_u(self):
  2352. b = r"""u'\\\u20ac\U0001d121\\u20ac'"""
  2353. a = r"""'\\\u20ac\U0001d121\\u20ac'"""
  2354. self.check(b, a)
  2355. b = r"""ur'\\\u20ac\U0001d121\\u20ac'"""
  2356. a = r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2357. self.check(b, a)
  2358. def test_native_unicode_literal_escape_u(self):
  2359. f = 'from __future__ import unicode_literals\n'
  2360. b = f + r"""'\\\u20ac\U0001d121\\u20ac'"""
  2361. a = f + r"""'\\\u20ac\U0001d121\\u20ac'"""
  2362. self.check(b, a)
  2363. b = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2364. a = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2365. self.check(b, a)
  2366. class Test_filter(FixerTestCase):
  2367. fixer = "filter"
  2368. def test_prefix_preservation(self):
  2369. b = """x = filter( foo, 'abc' )"""
  2370. a = """x = list(filter( foo, 'abc' ))"""
  2371. self.check(b, a)
  2372. b = """x = filter( None , 'abc' )"""
  2373. a = """x = [_f for _f in 'abc' if _f]"""
  2374. self.check(b, a)
  2375. def test_filter_basic(self):
  2376. b = """x = filter(None, 'abc')"""
  2377. a = """x = [_f for _f in 'abc' if _f]"""
  2378. self.check(b, a)
  2379. b = """x = len(filter(f, 'abc'))"""
  2380. a = """x = len(list(filter(f, 'abc')))"""
  2381. self.check(b, a)
  2382. b = """x = filter(lambda x: x%2 == 0, range(10))"""
  2383. a = """x = [x for x in range(10) if x%2 == 0]"""
  2384. self.check(b, a)
  2385. # Note the parens around x
  2386. b = """x = filter(lambda (x): x%2 == 0, range(10))"""
  2387. a = """x = [x for x in range(10) if x%2 == 0]"""
  2388. self.check(b, a)
  2389. # bpo-38871
  2390. b = """filter(lambda x: True if x > 2 else False, [1, 2, 3])"""
  2391. a = """[x for x in [1, 2, 3] if (True if x > 2 else False)]"""
  2392. self.check(b, a)
  2393. def test_filter_trailers(self):
  2394. b = """x = filter(None, 'abc')[0]"""
  2395. a = """x = [_f for _f in 'abc' if _f][0]"""
  2396. self.check(b, a)
  2397. b = """x = len(filter(f, 'abc')[0])"""
  2398. a = """x = len(list(filter(f, 'abc'))[0])"""
  2399. self.check(b, a)
  2400. b = """x = filter(lambda x: x%2 == 0, range(10))[0]"""
  2401. a = """x = [x for x in range(10) if x%2 == 0][0]"""
  2402. self.check(b, a)
  2403. # Note the parens around x
  2404. b = """x = filter(lambda (x): x%2 == 0, range(10))[0]"""
  2405. a = """x = [x for x in range(10) if x%2 == 0][0]"""
  2406. self.check(b, a)
  2407. def test_filter_nochange(self):
  2408. a = """b.join(filter(f, 'abc'))"""
  2409. self.unchanged(a)
  2410. a = """(a + foo(5)).join(filter(f, 'abc'))"""
  2411. self.unchanged(a)
  2412. a = """iter(filter(f, 'abc'))"""
  2413. self.unchanged(a)
  2414. a = """list(filter(f, 'abc'))"""
  2415. self.unchanged(a)
  2416. a = """list(filter(f, 'abc'))[0]"""
  2417. self.unchanged(a)
  2418. a = """set(filter(f, 'abc'))"""
  2419. self.unchanged(a)
  2420. a = """set(filter(f, 'abc')).pop()"""
  2421. self.unchanged(a)
  2422. a = """tuple(filter(f, 'abc'))"""
  2423. self.unchanged(a)
  2424. a = """any(filter(f, 'abc'))"""
  2425. self.unchanged(a)
  2426. a = """all(filter(f, 'abc'))"""
  2427. self.unchanged(a)
  2428. a = """sum(filter(f, 'abc'))"""
  2429. self.unchanged(a)
  2430. a = """sorted(filter(f, 'abc'))"""
  2431. self.unchanged(a)
  2432. a = """sorted(filter(f, 'abc'), key=blah)"""
  2433. self.unchanged(a)
  2434. a = """sorted(filter(f, 'abc'), key=blah)[0]"""
  2435. self.unchanged(a)
  2436. a = """enumerate(filter(f, 'abc'))"""
  2437. self.unchanged(a)
  2438. a = """enumerate(filter(f, 'abc'), start=1)"""
  2439. self.unchanged(a)
  2440. a = """for i in filter(f, 'abc'): pass"""
  2441. self.unchanged(a)
  2442. a = """[x for x in filter(f, 'abc')]"""
  2443. self.unchanged(a)
  2444. a = """(x for x in filter(f, 'abc'))"""
  2445. self.unchanged(a)
  2446. def test_future_builtins(self):
  2447. a = "from future_builtins import spam, filter; filter(f, 'ham')"
  2448. self.unchanged(a)
  2449. b = """from future_builtins import spam; x = filter(f, 'abc')"""
  2450. a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""
  2451. self.check(b, a)
  2452. a = "from future_builtins import *; filter(f, 'ham')"
  2453. self.unchanged(a)
  2454. class Test_map(FixerTestCase):
  2455. fixer = "map"
  2456. def check(self, b, a):
  2457. self.unchanged("from future_builtins import map; " + b, a)
  2458. super(Test_map, self).check(b, a)
  2459. def test_prefix_preservation(self):
  2460. b = """x = map( f, 'abc' )"""
  2461. a = """x = list(map( f, 'abc' ))"""
  2462. self.check(b, a)
  2463. def test_map_trailers(self):
  2464. b = """x = map(f, 'abc')[0]"""
  2465. a = """x = list(map(f, 'abc'))[0]"""
  2466. self.check(b, a)
  2467. b = """x = map(None, l)[0]"""
  2468. a = """x = list(l)[0]"""
  2469. self.check(b, a)
  2470. b = """x = map(lambda x:x, l)[0]"""
  2471. a = """x = [x for x in l][0]"""
  2472. self.check(b, a)
  2473. b = """x = map(f, 'abc')[0][1]"""
  2474. a = """x = list(map(f, 'abc'))[0][1]"""
  2475. self.check(b, a)
  2476. def test_trailing_comment(self):
  2477. b = """x = map(f, 'abc') # foo"""
  2478. a = """x = list(map(f, 'abc')) # foo"""
  2479. self.check(b, a)
  2480. def test_None_with_multiple_arguments(self):
  2481. s = """x = map(None, a, b, c)"""
  2482. self.warns_unchanged(s, "cannot convert map(None, ...) with "
  2483. "multiple arguments")
  2484. def test_map_basic(self):
  2485. b = """x = map(f, 'abc')"""
  2486. a = """x = list(map(f, 'abc'))"""
  2487. self.check(b, a)
  2488. b = """x = len(map(f, 'abc', 'def'))"""
  2489. a = """x = len(list(map(f, 'abc', 'def')))"""
  2490. self.check(b, a)
  2491. b = """x = map(None, 'abc')"""
  2492. a = """x = list('abc')"""
  2493. self.check(b, a)
  2494. b = """x = map(lambda x: x+1, range(4))"""
  2495. a = """x = [x+1 for x in range(4)]"""
  2496. self.check(b, a)
  2497. # Note the parens around x
  2498. b = """x = map(lambda (x): x+1, range(4))"""
  2499. a = """x = [x+1 for x in range(4)]"""
  2500. self.check(b, a)
  2501. b = """
  2502. foo()
  2503. # foo
  2504. map(f, x)
  2505. """
  2506. a = """
  2507. foo()
  2508. # foo
  2509. list(map(f, x))
  2510. """
  2511. self.warns(b, a, "You should use a for loop here")
  2512. def test_map_nochange(self):
  2513. a = """b.join(map(f, 'abc'))"""
  2514. self.unchanged(a)
  2515. a = """(a + foo(5)).join(map(f, 'abc'))"""
  2516. self.unchanged(a)
  2517. a = """iter(map(f, 'abc'))"""
  2518. self.unchanged(a)
  2519. a = """list(map(f, 'abc'))"""
  2520. self.unchanged(a)
  2521. a = """list(map(f, 'abc'))[0]"""
  2522. self.unchanged(a)
  2523. a = """set(map(f, 'abc'))"""
  2524. self.unchanged(a)
  2525. a = """set(map(f, 'abc')).pop()"""
  2526. self.unchanged(a)
  2527. a = """tuple(map(f, 'abc'))"""
  2528. self.unchanged(a)
  2529. a = """any(map(f, 'abc'))"""
  2530. self.unchanged(a)
  2531. a = """all(map(f, 'abc'))"""
  2532. self.unchanged(a)
  2533. a = """sum(map(f, 'abc'))"""
  2534. self.unchanged(a)
  2535. a = """sorted(map(f, 'abc'))"""
  2536. self.unchanged(a)
  2537. a = """sorted(map(f, 'abc'), key=blah)"""
  2538. self.unchanged(a)
  2539. a = """sorted(map(f, 'abc'), key=blah)[0]"""
  2540. self.unchanged(a)
  2541. a = """enumerate(map(f, 'abc'))"""
  2542. self.unchanged(a)
  2543. a = """enumerate(map(f, 'abc'), start=1)"""
  2544. self.unchanged(a)
  2545. a = """for i in map(f, 'abc'): pass"""
  2546. self.unchanged(a)
  2547. a = """[x for x in map(f, 'abc')]"""
  2548. self.unchanged(a)
  2549. a = """(x for x in map(f, 'abc'))"""
  2550. self.unchanged(a)
  2551. def test_future_builtins(self):
  2552. a = "from future_builtins import spam, map, eggs; map(f, 'ham')"
  2553. self.unchanged(a)
  2554. b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""
  2555. a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
  2556. self.check(b, a)
  2557. a = "from future_builtins import *; map(f, 'ham')"
  2558. self.unchanged(a)
  2559. class Test_zip(FixerTestCase):
  2560. fixer = "zip"
  2561. def check(self, b, a):
  2562. self.unchanged("from future_builtins import zip; " + b, a)
  2563. super(Test_zip, self).check(b, a)
  2564. def test_zip_basic(self):
  2565. b = """x = zip()"""
  2566. a = """x = list(zip())"""
  2567. self.check(b, a)
  2568. b = """x = zip(a, b, c)"""
  2569. a = """x = list(zip(a, b, c))"""
  2570. self.check(b, a)
  2571. b = """x = len(zip(a, b))"""
  2572. a = """x = len(list(zip(a, b)))"""
  2573. self.check(b, a)
  2574. def test_zip_trailers(self):
  2575. b = """x = zip(a, b, c)[0]"""
  2576. a = """x = list(zip(a, b, c))[0]"""
  2577. self.check(b, a)
  2578. b = """x = zip(a, b, c)[0][1]"""
  2579. a = """x = list(zip(a, b, c))[0][1]"""
  2580. self.check(b, a)
  2581. def test_zip_nochange(self):
  2582. a = """b.join(zip(a, b))"""
  2583. self.unchanged(a)
  2584. a = """(a + foo(5)).join(zip(a, b))"""
  2585. self.unchanged(a)
  2586. a = """iter(zip(a, b))"""
  2587. self.unchanged(a)
  2588. a = """list(zip(a, b))"""
  2589. self.unchanged(a)
  2590. a = """list(zip(a, b))[0]"""
  2591. self.unchanged(a)
  2592. a = """set(zip(a, b))"""
  2593. self.unchanged(a)
  2594. a = """set(zip(a, b)).pop()"""
  2595. self.unchanged(a)
  2596. a = """tuple(zip(a, b))"""
  2597. self.unchanged(a)
  2598. a = """any(zip(a, b))"""
  2599. self.unchanged(a)
  2600. a = """all(zip(a, b))"""
  2601. self.unchanged(a)
  2602. a = """sum(zip(a, b))"""
  2603. self.unchanged(a)
  2604. a = """sorted(zip(a, b))"""
  2605. self.unchanged(a)
  2606. a = """sorted(zip(a, b), key=blah)"""
  2607. self.unchanged(a)
  2608. a = """sorted(zip(a, b), key=blah)[0]"""
  2609. self.unchanged(a)
  2610. a = """enumerate(zip(a, b))"""
  2611. self.unchanged(a)
  2612. a = """enumerate(zip(a, b), start=1)"""
  2613. self.unchanged(a)
  2614. a = """for i in zip(a, b): pass"""
  2615. self.unchanged(a)
  2616. a = """[x for x in zip(a, b)]"""
  2617. self.unchanged(a)
  2618. a = """(x for x in zip(a, b))"""
  2619. self.unchanged(a)
  2620. def test_future_builtins(self):
  2621. a = "from future_builtins import spam, zip, eggs; zip(a, b)"
  2622. self.unchanged(a)
  2623. b = """from future_builtins import spam, eggs; x = zip(a, b)"""
  2624. a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""
  2625. self.check(b, a)
  2626. a = "from future_builtins import *; zip(a, b)"
  2627. self.unchanged(a)
  2628. class Test_standarderror(FixerTestCase):
  2629. fixer = "standarderror"
  2630. def test(self):
  2631. b = """x = StandardError()"""
  2632. a = """x = Exception()"""
  2633. self.check(b, a)
  2634. b = """x = StandardError(a, b, c)"""
  2635. a = """x = Exception(a, b, c)"""
  2636. self.check(b, a)
  2637. b = """f(2 + StandardError(a, b, c))"""
  2638. a = """f(2 + Exception(a, b, c))"""
  2639. self.check(b, a)
  2640. class Test_types(FixerTestCase):
  2641. fixer = "types"
  2642. def test_basic_types_convert(self):
  2643. b = """types.StringType"""
  2644. a = """bytes"""
  2645. self.check(b, a)
  2646. b = """types.DictType"""
  2647. a = """dict"""
  2648. self.check(b, a)
  2649. b = """types . IntType"""
  2650. a = """int"""
  2651. self.check(b, a)
  2652. b = """types.ListType"""
  2653. a = """list"""
  2654. self.check(b, a)
  2655. b = """types.LongType"""
  2656. a = """int"""
  2657. self.check(b, a)
  2658. b = """types.NoneType"""
  2659. a = """type(None)"""
  2660. self.check(b, a)
  2661. b = "types.StringTypes"
  2662. a = "(str,)"
  2663. self.check(b, a)
  2664. class Test_idioms(FixerTestCase):
  2665. fixer = "idioms"
  2666. def test_while(self):
  2667. b = """while 1: foo()"""
  2668. a = """while True: foo()"""
  2669. self.check(b, a)
  2670. b = """while 1: foo()"""
  2671. a = """while True: foo()"""
  2672. self.check(b, a)
  2673. b = """
  2674. while 1:
  2675. foo()
  2676. """
  2677. a = """
  2678. while True:
  2679. foo()
  2680. """
  2681. self.check(b, a)
  2682. def test_while_unchanged(self):
  2683. s = """while 11: foo()"""
  2684. self.unchanged(s)
  2685. s = """while 0: foo()"""
  2686. self.unchanged(s)
  2687. s = """while foo(): foo()"""
  2688. self.unchanged(s)
  2689. s = """while []: foo()"""
  2690. self.unchanged(s)
  2691. def test_eq_simple(self):
  2692. b = """type(x) == T"""
  2693. a = """isinstance(x, T)"""
  2694. self.check(b, a)
  2695. b = """if type(x) == T: pass"""
  2696. a = """if isinstance(x, T): pass"""
  2697. self.check(b, a)
  2698. def test_eq_reverse(self):
  2699. b = """T == type(x)"""
  2700. a = """isinstance(x, T)"""
  2701. self.check(b, a)
  2702. b = """if T == type(x): pass"""
  2703. a = """if isinstance(x, T): pass"""
  2704. self.check(b, a)
  2705. def test_eq_expression(self):
  2706. b = """type(x+y) == d.get('T')"""
  2707. a = """isinstance(x+y, d.get('T'))"""
  2708. self.check(b, a)
  2709. b = """type( x + y) == d.get('T')"""
  2710. a = """isinstance(x + y, d.get('T'))"""
  2711. self.check(b, a)
  2712. def test_is_simple(self):
  2713. b = """type(x) is T"""
  2714. a = """isinstance(x, T)"""
  2715. self.check(b, a)
  2716. b = """if type(x) is T: pass"""
  2717. a = """if isinstance(x, T): pass"""
  2718. self.check(b, a)
  2719. def test_is_reverse(self):
  2720. b = """T is type(x)"""
  2721. a = """isinstance(x, T)"""
  2722. self.check(b, a)
  2723. b = """if T is type(x): pass"""
  2724. a = """if isinstance(x, T): pass"""
  2725. self.check(b, a)
  2726. def test_is_expression(self):
  2727. b = """type(x+y) is d.get('T')"""
  2728. a = """isinstance(x+y, d.get('T'))"""
  2729. self.check(b, a)
  2730. b = """type( x + y) is d.get('T')"""
  2731. a = """isinstance(x + y, d.get('T'))"""
  2732. self.check(b, a)
  2733. def test_is_not_simple(self):
  2734. b = """type(x) is not T"""
  2735. a = """not isinstance(x, T)"""
  2736. self.check(b, a)
  2737. b = """if type(x) is not T: pass"""
  2738. a = """if not isinstance(x, T): pass"""
  2739. self.check(b, a)
  2740. def test_is_not_reverse(self):
  2741. b = """T is not type(x)"""
  2742. a = """not isinstance(x, T)"""
  2743. self.check(b, a)
  2744. b = """if T is not type(x): pass"""
  2745. a = """if not isinstance(x, T): pass"""
  2746. self.check(b, a)
  2747. def test_is_not_expression(self):
  2748. b = """type(x+y) is not d.get('T')"""
  2749. a = """not isinstance(x+y, d.get('T'))"""
  2750. self.check(b, a)
  2751. b = """type( x + y) is not d.get('T')"""
  2752. a = """not isinstance(x + y, d.get('T'))"""
  2753. self.check(b, a)
  2754. def test_ne_simple(self):
  2755. b = """type(x) != T"""
  2756. a = """not isinstance(x, T)"""
  2757. self.check(b, a)
  2758. b = """if type(x) != T: pass"""
  2759. a = """if not isinstance(x, T): pass"""
  2760. self.check(b, a)
  2761. def test_ne_reverse(self):
  2762. b = """T != type(x)"""
  2763. a = """not isinstance(x, T)"""
  2764. self.check(b, a)
  2765. b = """if T != type(x): pass"""
  2766. a = """if not isinstance(x, T): pass"""
  2767. self.check(b, a)
  2768. def test_ne_expression(self):
  2769. b = """type(x+y) != d.get('T')"""
  2770. a = """not isinstance(x+y, d.get('T'))"""
  2771. self.check(b, a)
  2772. b = """type( x + y) != d.get('T')"""
  2773. a = """not isinstance(x + y, d.get('T'))"""
  2774. self.check(b, a)
  2775. def test_type_unchanged(self):
  2776. a = """type(x).__name__"""
  2777. self.unchanged(a)
  2778. def test_sort_list_call(self):
  2779. b = """
  2780. v = list(t)
  2781. v.sort()
  2782. foo(v)
  2783. """
  2784. a = """
  2785. v = sorted(t)
  2786. foo(v)
  2787. """
  2788. self.check(b, a)
  2789. b = """
  2790. v = list(foo(b) + d)
  2791. v.sort()
  2792. foo(v)
  2793. """
  2794. a = """
  2795. v = sorted(foo(b) + d)
  2796. foo(v)
  2797. """
  2798. self.check(b, a)
  2799. b = """
  2800. while x:
  2801. v = list(t)
  2802. v.sort()
  2803. foo(v)
  2804. """
  2805. a = """
  2806. while x:
  2807. v = sorted(t)
  2808. foo(v)
  2809. """
  2810. self.check(b, a)
  2811. b = """
  2812. v = list(t)
  2813. # foo
  2814. v.sort()
  2815. foo(v)
  2816. """
  2817. a = """
  2818. v = sorted(t)
  2819. # foo
  2820. foo(v)
  2821. """
  2822. self.check(b, a)
  2823. b = r"""
  2824. v = list( t)
  2825. v.sort()
  2826. foo(v)
  2827. """
  2828. a = r"""
  2829. v = sorted( t)
  2830. foo(v)
  2831. """
  2832. self.check(b, a)
  2833. b = r"""
  2834. try:
  2835. m = list(s)
  2836. m.sort()
  2837. except: pass
  2838. """
  2839. a = r"""
  2840. try:
  2841. m = sorted(s)
  2842. except: pass
  2843. """
  2844. self.check(b, a)
  2845. b = r"""
  2846. try:
  2847. m = list(s)
  2848. # foo
  2849. m.sort()
  2850. except: pass
  2851. """
  2852. a = r"""
  2853. try:
  2854. m = sorted(s)
  2855. # foo
  2856. except: pass
  2857. """
  2858. self.check(b, a)
  2859. b = r"""
  2860. m = list(s)
  2861. # more comments
  2862. m.sort()"""
  2863. a = r"""
  2864. m = sorted(s)
  2865. # more comments"""
  2866. self.check(b, a)
  2867. def test_sort_simple_expr(self):
  2868. b = """
  2869. v = t
  2870. v.sort()
  2871. foo(v)
  2872. """
  2873. a = """
  2874. v = sorted(t)
  2875. foo(v)
  2876. """
  2877. self.check(b, a)
  2878. b = """
  2879. v = foo(b)
  2880. v.sort()
  2881. foo(v)
  2882. """
  2883. a = """
  2884. v = sorted(foo(b))
  2885. foo(v)
  2886. """
  2887. self.check(b, a)
  2888. b = """
  2889. v = b.keys()
  2890. v.sort()
  2891. foo(v)
  2892. """
  2893. a = """
  2894. v = sorted(b.keys())
  2895. foo(v)
  2896. """
  2897. self.check(b, a)
  2898. b = """
  2899. v = foo(b) + d
  2900. v.sort()
  2901. foo(v)
  2902. """
  2903. a = """
  2904. v = sorted(foo(b) + d)
  2905. foo(v)
  2906. """
  2907. self.check(b, a)
  2908. b = """
  2909. while x:
  2910. v = t
  2911. v.sort()
  2912. foo(v)
  2913. """
  2914. a = """
  2915. while x:
  2916. v = sorted(t)
  2917. foo(v)
  2918. """
  2919. self.check(b, a)
  2920. b = """
  2921. v = t
  2922. # foo
  2923. v.sort()
  2924. foo(v)
  2925. """
  2926. a = """
  2927. v = sorted(t)
  2928. # foo
  2929. foo(v)
  2930. """
  2931. self.check(b, a)
  2932. b = r"""
  2933. v = t
  2934. v.sort()
  2935. foo(v)
  2936. """
  2937. a = r"""
  2938. v = sorted(t)
  2939. foo(v)
  2940. """
  2941. self.check(b, a)
  2942. def test_sort_unchanged(self):
  2943. s = """
  2944. v = list(t)
  2945. w.sort()
  2946. foo(w)
  2947. """
  2948. self.unchanged(s)
  2949. s = """
  2950. v = list(t)
  2951. v.sort(u)
  2952. foo(v)
  2953. """
  2954. self.unchanged(s)
  2955. class Test_basestring(FixerTestCase):
  2956. fixer = "basestring"
  2957. def test_basestring(self):
  2958. b = """isinstance(x, basestring)"""
  2959. a = """isinstance(x, str)"""
  2960. self.check(b, a)
  2961. class Test_buffer(FixerTestCase):
  2962. fixer = "buffer"
  2963. def test_buffer(self):
  2964. b = """x = buffer(y)"""
  2965. a = """x = memoryview(y)"""
  2966. self.check(b, a)
  2967. def test_slicing(self):
  2968. b = """buffer(y)[4:5]"""
  2969. a = """memoryview(y)[4:5]"""
  2970. self.check(b, a)
  2971. class Test_future(FixerTestCase):
  2972. fixer = "future"
  2973. def test_future(self):
  2974. b = """from __future__ import braces"""
  2975. a = """"""
  2976. self.check(b, a)
  2977. b = """# comment\nfrom __future__ import braces"""
  2978. a = """# comment\n"""
  2979. self.check(b, a)
  2980. b = """from __future__ import braces\n# comment"""
  2981. a = """\n# comment"""
  2982. self.check(b, a)
  2983. def test_run_order(self):
  2984. self.assert_runs_after('print')
  2985. class Test_itertools(FixerTestCase):
  2986. fixer = "itertools"
  2987. def checkall(self, before, after):
  2988. # Because we need to check with and without the itertools prefix
  2989. # and on each of the three functions, these loops make it all
  2990. # much easier
  2991. for i in ('itertools.', ''):
  2992. for f in ('map', 'filter', 'zip'):
  2993. b = before %(i+'i'+f)
  2994. a = after %(f)
  2995. self.check(b, a)
  2996. def test_0(self):
  2997. # A simple example -- test_1 covers exactly the same thing,
  2998. # but it's not quite as clear.
  2999. b = "itertools.izip(a, b)"
  3000. a = "zip(a, b)"
  3001. self.check(b, a)
  3002. def test_1(self):
  3003. b = """%s(f, a)"""
  3004. a = """%s(f, a)"""
  3005. self.checkall(b, a)
  3006. def test_qualified(self):
  3007. b = """itertools.ifilterfalse(a, b)"""
  3008. a = """itertools.filterfalse(a, b)"""
  3009. self.check(b, a)
  3010. b = """itertools.izip_longest(a, b)"""
  3011. a = """itertools.zip_longest(a, b)"""
  3012. self.check(b, a)
  3013. def test_2(self):
  3014. b = """ifilterfalse(a, b)"""
  3015. a = """filterfalse(a, b)"""
  3016. self.check(b, a)
  3017. b = """izip_longest(a, b)"""
  3018. a = """zip_longest(a, b)"""
  3019. self.check(b, a)
  3020. def test_space_1(self):
  3021. b = """ %s(f, a)"""
  3022. a = """ %s(f, a)"""
  3023. self.checkall(b, a)
  3024. def test_space_2(self):
  3025. b = """ itertools.ifilterfalse(a, b)"""
  3026. a = """ itertools.filterfalse(a, b)"""
  3027. self.check(b, a)
  3028. b = """ itertools.izip_longest(a, b)"""
  3029. a = """ itertools.zip_longest(a, b)"""
  3030. self.check(b, a)
  3031. def test_run_order(self):
  3032. self.assert_runs_after('map', 'zip', 'filter')
  3033. class Test_itertools_imports(FixerTestCase):
  3034. fixer = 'itertools_imports'
  3035. def test_reduced(self):
  3036. b = "from itertools import imap, izip, foo"
  3037. a = "from itertools import foo"
  3038. self.check(b, a)
  3039. b = "from itertools import bar, imap, izip, foo"
  3040. a = "from itertools import bar, foo"
  3041. self.check(b, a)
  3042. b = "from itertools import chain, imap, izip"
  3043. a = "from itertools import chain"
  3044. self.check(b, a)
  3045. def test_comments(self):
  3046. b = "#foo\nfrom itertools import imap, izip"
  3047. a = "#foo\n"
  3048. self.check(b, a)
  3049. def test_none(self):
  3050. b = "from itertools import imap, izip"
  3051. a = ""
  3052. self.check(b, a)
  3053. b = "from itertools import izip"
  3054. a = ""
  3055. self.check(b, a)
  3056. def test_import_as(self):
  3057. b = "from itertools import izip, bar as bang, imap"
  3058. a = "from itertools import bar as bang"
  3059. self.check(b, a)
  3060. b = "from itertools import izip as _zip, imap, bar"
  3061. a = "from itertools import bar"
  3062. self.check(b, a)
  3063. b = "from itertools import imap as _map"
  3064. a = ""
  3065. self.check(b, a)
  3066. b = "from itertools import imap as _map, izip as _zip"
  3067. a = ""
  3068. self.check(b, a)
  3069. s = "from itertools import bar as bang"
  3070. self.unchanged(s)
  3071. def test_ifilter_and_zip_longest(self):
  3072. for name in "filterfalse", "zip_longest":
  3073. b = "from itertools import i%s" % (name,)
  3074. a = "from itertools import %s" % (name,)
  3075. self.check(b, a)
  3076. b = "from itertools import imap, i%s, foo" % (name,)
  3077. a = "from itertools import %s, foo" % (name,)
  3078. self.check(b, a)
  3079. b = "from itertools import bar, i%s, foo" % (name,)
  3080. a = "from itertools import bar, %s, foo" % (name,)
  3081. self.check(b, a)
  3082. def test_import_star(self):
  3083. s = "from itertools import *"
  3084. self.unchanged(s)
  3085. def test_unchanged(self):
  3086. s = "from itertools import foo"
  3087. self.unchanged(s)
  3088. class Test_import(FixerTestCase):
  3089. fixer = "import"
  3090. def setUp(self):
  3091. super(Test_import, self).setUp()
  3092. # Need to replace fix_import's exists method
  3093. # so we can check that it's doing the right thing
  3094. self.files_checked = []
  3095. self.present_files = set()
  3096. self.always_exists = True
  3097. def fake_exists(name):
  3098. self.files_checked.append(name)
  3099. return self.always_exists or (name in self.present_files)
  3100. from lib2to3.fixes import fix_import
  3101. fix_import.exists = fake_exists
  3102. def tearDown(self):
  3103. from lib2to3.fixes import fix_import
  3104. fix_import.exists = os.path.exists
  3105. def check_both(self, b, a):
  3106. self.always_exists = True
  3107. super(Test_import, self).check(b, a)
  3108. self.always_exists = False
  3109. super(Test_import, self).unchanged(b)
  3110. def test_files_checked(self):
  3111. def p(path):
  3112. # Takes a unix path and returns a path with correct separators
  3113. return os.path.pathsep.join(path.split("/"))
  3114. self.always_exists = False
  3115. self.present_files = set(['__init__.py'])
  3116. expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')
  3117. names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
  3118. for name in names_to_test:
  3119. self.files_checked = []
  3120. self.filename = name
  3121. self.unchanged("import jam")
  3122. if os.path.dirname(name):
  3123. name = os.path.dirname(name) + '/jam'
  3124. else:
  3125. name = 'jam'
  3126. expected_checks = set(name + ext for ext in expected_extensions)
  3127. expected_checks.add("__init__.py")
  3128. self.assertEqual(set(self.files_checked), expected_checks)
  3129. def test_not_in_package(self):
  3130. s = "import bar"
  3131. self.always_exists = False
  3132. self.present_files = set(["bar.py"])
  3133. self.unchanged(s)
  3134. def test_with_absolute_import_enabled(self):
  3135. s = "from __future__ import absolute_import\nimport bar"
  3136. self.always_exists = False
  3137. self.present_files = set(["__init__.py", "bar.py"])
  3138. self.unchanged(s)
  3139. def test_in_package(self):
  3140. b = "import bar"
  3141. a = "from . import bar"
  3142. self.always_exists = False
  3143. self.present_files = set(["__init__.py", "bar.py"])
  3144. self.check(b, a)
  3145. def test_import_from_package(self):
  3146. b = "import bar"
  3147. a = "from . import bar"
  3148. self.always_exists = False
  3149. self.present_files = set(["__init__.py", "bar" + os.path.sep])
  3150. self.check(b, a)
  3151. def test_already_relative_import(self):
  3152. s = "from . import bar"
  3153. self.unchanged(s)
  3154. def test_comments_and_indent(self):
  3155. b = "import bar # Foo"
  3156. a = "from . import bar # Foo"
  3157. self.check(b, a)
  3158. def test_from(self):
  3159. b = "from foo import bar, baz"
  3160. a = "from .foo import bar, baz"
  3161. self.check_both(b, a)
  3162. b = "from foo import bar"
  3163. a = "from .foo import bar"
  3164. self.check_both(b, a)
  3165. b = "from foo import (bar, baz)"
  3166. a = "from .foo import (bar, baz)"
  3167. self.check_both(b, a)
  3168. def test_dotted_from(self):
  3169. b = "from green.eggs import ham"
  3170. a = "from .green.eggs import ham"
  3171. self.check_both(b, a)
  3172. def test_from_as(self):
  3173. b = "from green.eggs import ham as spam"
  3174. a = "from .green.eggs import ham as spam"
  3175. self.check_both(b, a)
  3176. def test_import(self):
  3177. b = "import foo"
  3178. a = "from . import foo"
  3179. self.check_both(b, a)
  3180. b = "import foo, bar"
  3181. a = "from . import foo, bar"
  3182. self.check_both(b, a)
  3183. b = "import foo, bar, x"
  3184. a = "from . import foo, bar, x"
  3185. self.check_both(b, a)
  3186. b = "import x, y, z"
  3187. a = "from . import x, y, z"
  3188. self.check_both(b, a)
  3189. def test_import_as(self):
  3190. b = "import foo as x"
  3191. a = "from . import foo as x"
  3192. self.check_both(b, a)
  3193. b = "import a as b, b as c, c as d"
  3194. a = "from . import a as b, b as c, c as d"
  3195. self.check_both(b, a)
  3196. def test_local_and_absolute(self):
  3197. self.always_exists = False
  3198. self.present_files = set(["foo.py", "__init__.py"])
  3199. s = "import foo, bar"
  3200. self.warns_unchanged(s, "absolute and local imports together")
  3201. def test_dotted_import(self):
  3202. b = "import foo.bar"
  3203. a = "from . import foo.bar"
  3204. self.check_both(b, a)
  3205. def test_dotted_import_as(self):
  3206. b = "import foo.bar as bang"
  3207. a = "from . import foo.bar as bang"
  3208. self.check_both(b, a)
  3209. def test_prefix(self):
  3210. b = """
  3211. # prefix
  3212. import foo.bar
  3213. """
  3214. a = """
  3215. # prefix
  3216. from . import foo.bar
  3217. """
  3218. self.check_both(b, a)
  3219. class Test_set_literal(FixerTestCase):
  3220. fixer = "set_literal"
  3221. def test_basic(self):
  3222. b = """set([1, 2, 3])"""
  3223. a = """{1, 2, 3}"""
  3224. self.check(b, a)
  3225. b = """set((1, 2, 3))"""
  3226. a = """{1, 2, 3}"""
  3227. self.check(b, a)
  3228. b = """set((1,))"""
  3229. a = """{1}"""
  3230. self.check(b, a)
  3231. b = """set([1])"""
  3232. self.check(b, a)
  3233. b = """set((a, b))"""
  3234. a = """{a, b}"""
  3235. self.check(b, a)
  3236. b = """set([a, b])"""
  3237. self.check(b, a)
  3238. b = """set((a*234, f(args=23)))"""
  3239. a = """{a*234, f(args=23)}"""
  3240. self.check(b, a)
  3241. b = """set([a*23, f(23)])"""
  3242. a = """{a*23, f(23)}"""
  3243. self.check(b, a)
  3244. b = """set([a-234**23])"""
  3245. a = """{a-234**23}"""
  3246. self.check(b, a)
  3247. def test_listcomps(self):
  3248. b = """set([x for x in y])"""
  3249. a = """{x for x in y}"""
  3250. self.check(b, a)
  3251. b = """set([x for x in y if x == m])"""
  3252. a = """{x for x in y if x == m}"""
  3253. self.check(b, a)
  3254. b = """set([x for x in y for a in b])"""
  3255. a = """{x for x in y for a in b}"""
  3256. self.check(b, a)
  3257. b = """set([f(x) - 23 for x in y])"""
  3258. a = """{f(x) - 23 for x in y}"""
  3259. self.check(b, a)
  3260. def test_whitespace(self):
  3261. b = """set( [1, 2])"""
  3262. a = """{1, 2}"""
  3263. self.check(b, a)
  3264. b = """set([1 , 2])"""
  3265. a = """{1 , 2}"""
  3266. self.check(b, a)
  3267. b = """set([ 1 ])"""
  3268. a = """{ 1 }"""
  3269. self.check(b, a)
  3270. b = """set( [1] )"""
  3271. a = """{1}"""
  3272. self.check(b, a)
  3273. b = """set([ 1, 2 ])"""
  3274. a = """{ 1, 2 }"""
  3275. self.check(b, a)
  3276. b = """set([x for x in y ])"""
  3277. a = """{x for x in y }"""
  3278. self.check(b, a)
  3279. b = """set(
  3280. [1, 2]
  3281. )
  3282. """
  3283. a = """{1, 2}\n"""
  3284. self.check(b, a)
  3285. def test_comments(self):
  3286. b = """set((1, 2)) # Hi"""
  3287. a = """{1, 2} # Hi"""
  3288. self.check(b, a)
  3289. # This isn't optimal behavior, but the fixer is optional.
  3290. b = """
  3291. # Foo
  3292. set( # Bar
  3293. (1, 2)
  3294. )
  3295. """
  3296. a = """
  3297. # Foo
  3298. {1, 2}
  3299. """
  3300. self.check(b, a)
  3301. def test_unchanged(self):
  3302. s = """set()"""
  3303. self.unchanged(s)
  3304. s = """set(a)"""
  3305. self.unchanged(s)
  3306. s = """set(a, b, c)"""
  3307. self.unchanged(s)
  3308. # Don't transform generators because they might have to be lazy.
  3309. s = """set(x for x in y)"""
  3310. self.unchanged(s)
  3311. s = """set(x for x in y if z)"""
  3312. self.unchanged(s)
  3313. s = """set(a*823-23**2 + f(23))"""
  3314. self.unchanged(s)
  3315. class Test_sys_exc(FixerTestCase):
  3316. fixer = "sys_exc"
  3317. def test_0(self):
  3318. b = "sys.exc_type"
  3319. a = "sys.exc_info()[0]"
  3320. self.check(b, a)
  3321. def test_1(self):
  3322. b = "sys.exc_value"
  3323. a = "sys.exc_info()[1]"
  3324. self.check(b, a)
  3325. def test_2(self):
  3326. b = "sys.exc_traceback"
  3327. a = "sys.exc_info()[2]"
  3328. self.check(b, a)
  3329. def test_3(self):
  3330. b = "sys.exc_type # Foo"
  3331. a = "sys.exc_info()[0] # Foo"
  3332. self.check(b, a)
  3333. def test_4(self):
  3334. b = "sys. exc_type"
  3335. a = "sys. exc_info()[0]"
  3336. self.check(b, a)
  3337. def test_5(self):
  3338. b = "sys .exc_type"
  3339. a = "sys .exc_info()[0]"
  3340. self.check(b, a)
  3341. class Test_paren(FixerTestCase):
  3342. fixer = "paren"
  3343. def test_0(self):
  3344. b = """[i for i in 1, 2 ]"""
  3345. a = """[i for i in (1, 2) ]"""
  3346. self.check(b, a)
  3347. def test_1(self):
  3348. b = """[i for i in 1, 2, ]"""
  3349. a = """[i for i in (1, 2,) ]"""
  3350. self.check(b, a)
  3351. def test_2(self):
  3352. b = """[i for i in 1, 2 ]"""
  3353. a = """[i for i in (1, 2) ]"""
  3354. self.check(b, a)
  3355. def test_3(self):
  3356. b = """[i for i in 1, 2 if i]"""
  3357. a = """[i for i in (1, 2) if i]"""
  3358. self.check(b, a)
  3359. def test_4(self):
  3360. b = """[i for i in 1, 2 ]"""
  3361. a = """[i for i in (1, 2) ]"""
  3362. self.check(b, a)
  3363. def test_5(self):
  3364. b = """(i for i in 1, 2)"""
  3365. a = """(i for i in (1, 2))"""
  3366. self.check(b, a)
  3367. def test_6(self):
  3368. b = """(i for i in 1 ,2 if i)"""
  3369. a = """(i for i in (1 ,2) if i)"""
  3370. self.check(b, a)
  3371. def test_unchanged_0(self):
  3372. s = """[i for i in (1, 2)]"""
  3373. self.unchanged(s)
  3374. def test_unchanged_1(self):
  3375. s = """[i for i in foo()]"""
  3376. self.unchanged(s)
  3377. def test_unchanged_2(self):
  3378. s = """[i for i in (1, 2) if nothing]"""
  3379. self.unchanged(s)
  3380. def test_unchanged_3(self):
  3381. s = """(i for i in (1, 2))"""
  3382. self.unchanged(s)
  3383. def test_unchanged_4(self):
  3384. s = """[i for i in m]"""
  3385. self.unchanged(s)
  3386. class Test_metaclass(FixerTestCase):
  3387. fixer = 'metaclass'
  3388. def test_unchanged(self):
  3389. self.unchanged("class X(): pass")
  3390. self.unchanged("class X(object): pass")
  3391. self.unchanged("class X(object1, object2): pass")
  3392. self.unchanged("class X(object1, object2, object3): pass")
  3393. self.unchanged("class X(metaclass=Meta): pass")
  3394. self.unchanged("class X(b, arg=23, metclass=Meta): pass")
  3395. self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
  3396. s = """
  3397. class X:
  3398. def __metaclass__(self): pass
  3399. """
  3400. self.unchanged(s)
  3401. s = """
  3402. class X:
  3403. a[23] = 74
  3404. """
  3405. self.unchanged(s)
  3406. def test_comments(self):
  3407. b = """
  3408. class X:
  3409. # hi
  3410. __metaclass__ = AppleMeta
  3411. """
  3412. a = """
  3413. class X(metaclass=AppleMeta):
  3414. # hi
  3415. pass
  3416. """
  3417. self.check(b, a)
  3418. b = """
  3419. class X:
  3420. __metaclass__ = Meta
  3421. # Bedtime!
  3422. """
  3423. a = """
  3424. class X(metaclass=Meta):
  3425. pass
  3426. # Bedtime!
  3427. """
  3428. self.check(b, a)
  3429. def test_meta(self):
  3430. # no-parent class, odd body
  3431. b = """
  3432. class X():
  3433. __metaclass__ = Q
  3434. pass
  3435. """
  3436. a = """
  3437. class X(metaclass=Q):
  3438. pass
  3439. """
  3440. self.check(b, a)
  3441. # one parent class, no body
  3442. b = """class X(object): __metaclass__ = Q"""
  3443. a = """class X(object, metaclass=Q): pass"""
  3444. self.check(b, a)
  3445. # one parent, simple body
  3446. b = """
  3447. class X(object):
  3448. __metaclass__ = Meta
  3449. bar = 7
  3450. """
  3451. a = """
  3452. class X(object, metaclass=Meta):
  3453. bar = 7
  3454. """
  3455. self.check(b, a)
  3456. b = """
  3457. class X:
  3458. __metaclass__ = Meta; x = 4; g = 23
  3459. """
  3460. a = """
  3461. class X(metaclass=Meta):
  3462. x = 4; g = 23
  3463. """
  3464. self.check(b, a)
  3465. # one parent, simple body, __metaclass__ last
  3466. b = """
  3467. class X(object):
  3468. bar = 7
  3469. __metaclass__ = Meta
  3470. """
  3471. a = """
  3472. class X(object, metaclass=Meta):
  3473. bar = 7
  3474. """
  3475. self.check(b, a)
  3476. # redefining __metaclass__
  3477. b = """
  3478. class X():
  3479. __metaclass__ = A
  3480. __metaclass__ = B
  3481. bar = 7
  3482. """
  3483. a = """
  3484. class X(metaclass=B):
  3485. bar = 7
  3486. """
  3487. self.check(b, a)
  3488. # multiple inheritance, simple body
  3489. b = """
  3490. class X(clsA, clsB):
  3491. __metaclass__ = Meta
  3492. bar = 7
  3493. """
  3494. a = """
  3495. class X(clsA, clsB, metaclass=Meta):
  3496. bar = 7
  3497. """
  3498. self.check(b, a)
  3499. # keywords in the class statement
  3500. b = """class m(a, arg=23): __metaclass__ = Meta"""
  3501. a = """class m(a, arg=23, metaclass=Meta): pass"""
  3502. self.check(b, a)
  3503. b = """
  3504. class X(expression(2 + 4)):
  3505. __metaclass__ = Meta
  3506. """
  3507. a = """
  3508. class X(expression(2 + 4), metaclass=Meta):
  3509. pass
  3510. """
  3511. self.check(b, a)
  3512. b = """
  3513. class X(expression(2 + 4), x**4):
  3514. __metaclass__ = Meta
  3515. """
  3516. a = """
  3517. class X(expression(2 + 4), x**4, metaclass=Meta):
  3518. pass
  3519. """
  3520. self.check(b, a)
  3521. b = """
  3522. class X:
  3523. __metaclass__ = Meta
  3524. save.py = 23
  3525. """
  3526. a = """
  3527. class X(metaclass=Meta):
  3528. save.py = 23
  3529. """
  3530. self.check(b, a)
  3531. class Test_getcwdu(FixerTestCase):
  3532. fixer = 'getcwdu'
  3533. def test_basic(self):
  3534. b = """os.getcwdu"""
  3535. a = """os.getcwd"""
  3536. self.check(b, a)
  3537. b = """os.getcwdu()"""
  3538. a = """os.getcwd()"""
  3539. self.check(b, a)
  3540. b = """meth = os.getcwdu"""
  3541. a = """meth = os.getcwd"""
  3542. self.check(b, a)
  3543. b = """os.getcwdu(args)"""
  3544. a = """os.getcwd(args)"""
  3545. self.check(b, a)
  3546. def test_comment(self):
  3547. b = """os.getcwdu() # Foo"""
  3548. a = """os.getcwd() # Foo"""
  3549. self.check(b, a)
  3550. def test_unchanged(self):
  3551. s = """os.getcwd()"""
  3552. self.unchanged(s)
  3553. s = """getcwdu()"""
  3554. self.unchanged(s)
  3555. s = """os.getcwdb()"""
  3556. self.unchanged(s)
  3557. def test_indentation(self):
  3558. b = """
  3559. if 1:
  3560. os.getcwdu()
  3561. """
  3562. a = """
  3563. if 1:
  3564. os.getcwd()
  3565. """
  3566. self.check(b, a)
  3567. def test_multilation(self):
  3568. b = """os .getcwdu()"""
  3569. a = """os .getcwd()"""
  3570. self.check(b, a)
  3571. b = """os. getcwdu"""
  3572. a = """os. getcwd"""
  3573. self.check(b, a)
  3574. b = """os.getcwdu ( )"""
  3575. a = """os.getcwd ( )"""
  3576. self.check(b, a)
  3577. class Test_operator(FixerTestCase):
  3578. fixer = "operator"
  3579. def test_operator_isCallable(self):
  3580. b = "operator.isCallable(x)"
  3581. a = "callable(x)"
  3582. self.check(b, a)
  3583. def test_operator_sequenceIncludes(self):
  3584. b = "operator.sequenceIncludes(x, y)"
  3585. a = "operator.contains(x, y)"
  3586. self.check(b, a)
  3587. b = "operator .sequenceIncludes(x, y)"
  3588. a = "operator .contains(x, y)"
  3589. self.check(b, a)
  3590. b = "operator. sequenceIncludes(x, y)"
  3591. a = "operator. contains(x, y)"
  3592. self.check(b, a)
  3593. def test_operator_isSequenceType(self):
  3594. b = "operator.isSequenceType(x)"
  3595. a = "import collections.abc\nisinstance(x, collections.abc.Sequence)"
  3596. self.check(b, a)
  3597. def test_operator_isMappingType(self):
  3598. b = "operator.isMappingType(x)"
  3599. a = "import collections.abc\nisinstance(x, collections.abc.Mapping)"
  3600. self.check(b, a)
  3601. def test_operator_isNumberType(self):
  3602. b = "operator.isNumberType(x)"
  3603. a = "import numbers\nisinstance(x, numbers.Number)"
  3604. self.check(b, a)
  3605. def test_operator_repeat(self):
  3606. b = "operator.repeat(x, n)"
  3607. a = "operator.mul(x, n)"
  3608. self.check(b, a)
  3609. b = "operator .repeat(x, n)"
  3610. a = "operator .mul(x, n)"
  3611. self.check(b, a)
  3612. b = "operator. repeat(x, n)"
  3613. a = "operator. mul(x, n)"
  3614. self.check(b, a)
  3615. def test_operator_irepeat(self):
  3616. b = "operator.irepeat(x, n)"
  3617. a = "operator.imul(x, n)"
  3618. self.check(b, a)
  3619. b = "operator .irepeat(x, n)"
  3620. a = "operator .imul(x, n)"
  3621. self.check(b, a)
  3622. b = "operator. irepeat(x, n)"
  3623. a = "operator. imul(x, n)"
  3624. self.check(b, a)
  3625. def test_bare_isCallable(self):
  3626. s = "isCallable(x)"
  3627. t = "You should use 'callable(x)' here."
  3628. self.warns_unchanged(s, t)
  3629. def test_bare_sequenceIncludes(self):
  3630. s = "sequenceIncludes(x, y)"
  3631. t = "You should use 'operator.contains(x, y)' here."
  3632. self.warns_unchanged(s, t)
  3633. def test_bare_operator_isSequenceType(self):
  3634. s = "isSequenceType(z)"
  3635. t = "You should use 'isinstance(z, collections.abc.Sequence)' here."
  3636. self.warns_unchanged(s, t)
  3637. def test_bare_operator_isMappingType(self):
  3638. s = "isMappingType(x)"
  3639. t = "You should use 'isinstance(x, collections.abc.Mapping)' here."
  3640. self.warns_unchanged(s, t)
  3641. def test_bare_operator_isNumberType(self):
  3642. s = "isNumberType(y)"
  3643. t = "You should use 'isinstance(y, numbers.Number)' here."
  3644. self.warns_unchanged(s, t)
  3645. def test_bare_operator_repeat(self):
  3646. s = "repeat(x, n)"
  3647. t = "You should use 'operator.mul(x, n)' here."
  3648. self.warns_unchanged(s, t)
  3649. def test_bare_operator_irepeat(self):
  3650. s = "irepeat(y, 187)"
  3651. t = "You should use 'operator.imul(y, 187)' here."
  3652. self.warns_unchanged(s, t)
  3653. class Test_exitfunc(FixerTestCase):
  3654. fixer = "exitfunc"
  3655. def test_simple(self):
  3656. b = """
  3657. import sys
  3658. sys.exitfunc = my_atexit
  3659. """
  3660. a = """
  3661. import sys
  3662. import atexit
  3663. atexit.register(my_atexit)
  3664. """
  3665. self.check(b, a)
  3666. def test_names_import(self):
  3667. b = """
  3668. import sys, crumbs
  3669. sys.exitfunc = my_func
  3670. """
  3671. a = """
  3672. import sys, crumbs, atexit
  3673. atexit.register(my_func)
  3674. """
  3675. self.check(b, a)
  3676. def test_complex_expression(self):
  3677. b = """
  3678. import sys
  3679. sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
  3680. """
  3681. a = """
  3682. import sys
  3683. import atexit
  3684. atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
  3685. """
  3686. self.check(b, a)
  3687. def test_comments(self):
  3688. b = """
  3689. import sys # Foo
  3690. sys.exitfunc = f # Blah
  3691. """
  3692. a = """
  3693. import sys
  3694. import atexit # Foo
  3695. atexit.register(f) # Blah
  3696. """
  3697. self.check(b, a)
  3698. b = """
  3699. import apples, sys, crumbs, larry # Pleasant comments
  3700. sys.exitfunc = func
  3701. """
  3702. a = """
  3703. import apples, sys, crumbs, larry, atexit # Pleasant comments
  3704. atexit.register(func)
  3705. """
  3706. self.check(b, a)
  3707. def test_in_a_function(self):
  3708. b = """
  3709. import sys
  3710. def f():
  3711. sys.exitfunc = func
  3712. """
  3713. a = """
  3714. import sys
  3715. import atexit
  3716. def f():
  3717. atexit.register(func)
  3718. """
  3719. self.check(b, a)
  3720. def test_no_sys_import(self):
  3721. b = """sys.exitfunc = f"""
  3722. a = """atexit.register(f)"""
  3723. msg = ("Can't find sys import; Please add an atexit import at the "
  3724. "top of your file.")
  3725. self.warns(b, a, msg)
  3726. def test_unchanged(self):
  3727. s = """f(sys.exitfunc)"""
  3728. self.unchanged(s)
  3729. class Test_asserts(FixerTestCase):
  3730. fixer = "asserts"
  3731. def test_deprecated_names(self):
  3732. tests = [
  3733. ('self.assert_(True)', 'self.assertTrue(True)'),
  3734. ('self.assertEquals(2, 2)', 'self.assertEqual(2, 2)'),
  3735. ('self.assertNotEquals(2, 3)', 'self.assertNotEqual(2, 3)'),
  3736. ('self.assertAlmostEquals(2, 3)', 'self.assertAlmostEqual(2, 3)'),
  3737. ('self.assertNotAlmostEquals(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),
  3738. ('self.failUnlessEqual(2, 2)', 'self.assertEqual(2, 2)'),
  3739. ('self.failIfEqual(2, 3)', 'self.assertNotEqual(2, 3)'),
  3740. ('self.failUnlessAlmostEqual(2, 3)', 'self.assertAlmostEqual(2, 3)'),
  3741. ('self.failIfAlmostEqual(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),
  3742. ('self.failUnless(True)', 'self.assertTrue(True)'),
  3743. ('self.failUnlessRaises(foo)', 'self.assertRaises(foo)'),
  3744. ('self.failIf(False)', 'self.assertFalse(False)'),
  3745. ]
  3746. for b, a in tests:
  3747. self.check(b, a)
  3748. def test_variants(self):
  3749. b = 'eq = self.assertEquals'
  3750. a = 'eq = self.assertEqual'
  3751. self.check(b, a)
  3752. b = 'self.assertEquals(2, 3, msg="fail")'
  3753. a = 'self.assertEqual(2, 3, msg="fail")'
  3754. self.check(b, a)
  3755. b = 'self.assertEquals(2, 3, msg="fail") # foo'
  3756. a = 'self.assertEqual(2, 3, msg="fail") # foo'
  3757. self.check(b, a)
  3758. b = 'self.assertEquals (2, 3)'
  3759. a = 'self.assertEqual (2, 3)'
  3760. self.check(b, a)
  3761. b = ' self.assertEquals (2, 3)'
  3762. a = ' self.assertEqual (2, 3)'
  3763. self.check(b, a)
  3764. b = 'with self.failUnlessRaises(Explosion): explode()'
  3765. a = 'with self.assertRaises(Explosion): explode()'
  3766. self.check(b, a)
  3767. b = 'with self.failUnlessRaises(Explosion) as cm: explode()'
  3768. a = 'with self.assertRaises(Explosion) as cm: explode()'
  3769. self.check(b, a)
  3770. def test_unchanged(self):
  3771. self.unchanged('self.assertEqualsOnSaturday')
  3772. self.unchanged('self.assertEqualsOnSaturday(3, 5)')