test_fixers.py 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645
  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_import_module_usage(self):
  1534. for old, changes in self.modules.items():
  1535. for new, members in changes:
  1536. for member in members:
  1537. new_import = ", ".join([n for (n, mems)
  1538. in self.modules[old]])
  1539. b = """
  1540. import %s
  1541. foo(%s.%s)
  1542. """ % (old, old, member)
  1543. a = """
  1544. import %s
  1545. foo(%s.%s)
  1546. """ % (new_import, new, member)
  1547. self.check(b, a)
  1548. b = """
  1549. import %s
  1550. %s.%s(%s.%s)
  1551. """ % (old, old, member, old, member)
  1552. a = """
  1553. import %s
  1554. %s.%s(%s.%s)
  1555. """ % (new_import, new, member, new, member)
  1556. self.check(b, a)
  1557. class Test_input(FixerTestCase):
  1558. fixer = "input"
  1559. def test_prefix_preservation(self):
  1560. b = """x = input( )"""
  1561. a = """x = eval(input( ))"""
  1562. self.check(b, a)
  1563. b = """x = input( '' )"""
  1564. a = """x = eval(input( '' ))"""
  1565. self.check(b, a)
  1566. def test_trailing_comment(self):
  1567. b = """x = input() # foo"""
  1568. a = """x = eval(input()) # foo"""
  1569. self.check(b, a)
  1570. def test_idempotency(self):
  1571. s = """x = eval(input())"""
  1572. self.unchanged(s)
  1573. s = """x = eval(input(''))"""
  1574. self.unchanged(s)
  1575. s = """x = eval(input(foo(5) + 9))"""
  1576. self.unchanged(s)
  1577. def test_1(self):
  1578. b = """x = input()"""
  1579. a = """x = eval(input())"""
  1580. self.check(b, a)
  1581. def test_2(self):
  1582. b = """x = input('')"""
  1583. a = """x = eval(input(''))"""
  1584. self.check(b, a)
  1585. def test_3(self):
  1586. b = """x = input('prompt')"""
  1587. a = """x = eval(input('prompt'))"""
  1588. self.check(b, a)
  1589. def test_4(self):
  1590. b = """x = input(foo(5) + 9)"""
  1591. a = """x = eval(input(foo(5) + 9))"""
  1592. self.check(b, a)
  1593. class Test_tuple_params(FixerTestCase):
  1594. fixer = "tuple_params"
  1595. def test_unchanged_1(self):
  1596. s = """def foo(): pass"""
  1597. self.unchanged(s)
  1598. def test_unchanged_2(self):
  1599. s = """def foo(a, b, c): pass"""
  1600. self.unchanged(s)
  1601. def test_unchanged_3(self):
  1602. s = """def foo(a=3, b=4, c=5): pass"""
  1603. self.unchanged(s)
  1604. def test_1(self):
  1605. b = """
  1606. def foo(((a, b), c)):
  1607. x = 5"""
  1608. a = """
  1609. def foo(xxx_todo_changeme):
  1610. ((a, b), c) = xxx_todo_changeme
  1611. x = 5"""
  1612. self.check(b, a)
  1613. def test_2(self):
  1614. b = """
  1615. def foo(((a, b), c), d):
  1616. x = 5"""
  1617. a = """
  1618. def foo(xxx_todo_changeme, d):
  1619. ((a, b), c) = xxx_todo_changeme
  1620. x = 5"""
  1621. self.check(b, a)
  1622. def test_3(self):
  1623. b = """
  1624. def foo(((a, b), c), d) -> e:
  1625. x = 5"""
  1626. a = """
  1627. def foo(xxx_todo_changeme, d) -> e:
  1628. ((a, b), c) = xxx_todo_changeme
  1629. x = 5"""
  1630. self.check(b, a)
  1631. def test_semicolon(self):
  1632. b = """
  1633. def foo(((a, b), c)): x = 5; y = 7"""
  1634. a = """
  1635. def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""
  1636. self.check(b, a)
  1637. def test_keywords(self):
  1638. b = """
  1639. def foo(((a, b), c), d, e=5) -> z:
  1640. x = 5"""
  1641. a = """
  1642. def foo(xxx_todo_changeme, d, e=5) -> z:
  1643. ((a, b), c) = xxx_todo_changeme
  1644. x = 5"""
  1645. self.check(b, a)
  1646. def test_varargs(self):
  1647. b = """
  1648. def foo(((a, b), c), d, *vargs, **kwargs) -> z:
  1649. x = 5"""
  1650. a = """
  1651. def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:
  1652. ((a, b), c) = xxx_todo_changeme
  1653. x = 5"""
  1654. self.check(b, a)
  1655. def test_multi_1(self):
  1656. b = """
  1657. def foo(((a, b), c), (d, e, f)) -> z:
  1658. x = 5"""
  1659. a = """
  1660. def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
  1661. ((a, b), c) = xxx_todo_changeme
  1662. (d, e, f) = xxx_todo_changeme1
  1663. x = 5"""
  1664. self.check(b, a)
  1665. def test_multi_2(self):
  1666. b = """
  1667. def foo(x, ((a, b), c), d, (e, f, g), y) -> z:
  1668. x = 5"""
  1669. a = """
  1670. def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:
  1671. ((a, b), c) = xxx_todo_changeme
  1672. (e, f, g) = xxx_todo_changeme1
  1673. x = 5"""
  1674. self.check(b, a)
  1675. def test_docstring(self):
  1676. b = """
  1677. def foo(((a, b), c), (d, e, f)) -> z:
  1678. "foo foo foo foo"
  1679. x = 5"""
  1680. a = """
  1681. def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
  1682. "foo foo foo foo"
  1683. ((a, b), c) = xxx_todo_changeme
  1684. (d, e, f) = xxx_todo_changeme1
  1685. x = 5"""
  1686. self.check(b, a)
  1687. def test_lambda_no_change(self):
  1688. s = """lambda x: x + 5"""
  1689. self.unchanged(s)
  1690. def test_lambda_parens_single_arg(self):
  1691. b = """lambda (x): x + 5"""
  1692. a = """lambda x: x + 5"""
  1693. self.check(b, a)
  1694. b = """lambda(x): x + 5"""
  1695. a = """lambda x: x + 5"""
  1696. self.check(b, a)
  1697. b = """lambda ((((x)))): x + 5"""
  1698. a = """lambda x: x + 5"""
  1699. self.check(b, a)
  1700. b = """lambda((((x)))): x + 5"""
  1701. a = """lambda x: x + 5"""
  1702. self.check(b, a)
  1703. def test_lambda_simple(self):
  1704. b = """lambda (x, y): x + f(y)"""
  1705. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1706. self.check(b, a)
  1707. b = """lambda(x, y): x + f(y)"""
  1708. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1709. self.check(b, a)
  1710. b = """lambda (((x, y))): x + f(y)"""
  1711. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1712. self.check(b, a)
  1713. b = """lambda(((x, y))): x + f(y)"""
  1714. a = """lambda x_y: x_y[0] + f(x_y[1])"""
  1715. self.check(b, a)
  1716. def test_lambda_one_tuple(self):
  1717. b = """lambda (x,): x + f(x)"""
  1718. a = """lambda x1: x1[0] + f(x1[0])"""
  1719. self.check(b, a)
  1720. b = """lambda (((x,))): x + f(x)"""
  1721. a = """lambda x1: x1[0] + f(x1[0])"""
  1722. self.check(b, a)
  1723. def test_lambda_simple_multi_use(self):
  1724. b = """lambda (x, y): x + x + f(x) + x"""
  1725. a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""
  1726. self.check(b, a)
  1727. def test_lambda_simple_reverse(self):
  1728. b = """lambda (x, y): y + x"""
  1729. a = """lambda x_y: x_y[1] + x_y[0]"""
  1730. self.check(b, a)
  1731. def test_lambda_nested(self):
  1732. b = """lambda (x, (y, z)): x + y + z"""
  1733. a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
  1734. self.check(b, a)
  1735. b = """lambda (((x, (y, z)))): x + y + z"""
  1736. a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
  1737. self.check(b, a)
  1738. def test_lambda_nested_multi_use(self):
  1739. b = """lambda (x, (y, z)): x + y + f(y)"""
  1740. a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""
  1741. self.check(b, a)
  1742. class Test_methodattrs(FixerTestCase):
  1743. fixer = "methodattrs"
  1744. attrs = ["func", "self", "class"]
  1745. def test(self):
  1746. for attr in self.attrs:
  1747. b = "a.im_%s" % attr
  1748. if attr == "class":
  1749. a = "a.__self__.__class__"
  1750. else:
  1751. a = "a.__%s__" % attr
  1752. self.check(b, a)
  1753. b = "self.foo.im_%s.foo_bar" % attr
  1754. if attr == "class":
  1755. a = "self.foo.__self__.__class__.foo_bar"
  1756. else:
  1757. a = "self.foo.__%s__.foo_bar" % attr
  1758. self.check(b, a)
  1759. def test_unchanged(self):
  1760. for attr in self.attrs:
  1761. s = "foo(im_%s + 5)" % attr
  1762. self.unchanged(s)
  1763. s = "f(foo.__%s__)" % attr
  1764. self.unchanged(s)
  1765. s = "f(foo.__%s__.foo)" % attr
  1766. self.unchanged(s)
  1767. class Test_next(FixerTestCase):
  1768. fixer = "next"
  1769. def test_1(self):
  1770. b = """it.next()"""
  1771. a = """next(it)"""
  1772. self.check(b, a)
  1773. def test_2(self):
  1774. b = """a.b.c.d.next()"""
  1775. a = """next(a.b.c.d)"""
  1776. self.check(b, a)
  1777. def test_3(self):
  1778. b = """(a + b).next()"""
  1779. a = """next((a + b))"""
  1780. self.check(b, a)
  1781. def test_4(self):
  1782. b = """a().next()"""
  1783. a = """next(a())"""
  1784. self.check(b, a)
  1785. def test_5(self):
  1786. b = """a().next() + b"""
  1787. a = """next(a()) + b"""
  1788. self.check(b, a)
  1789. def test_6(self):
  1790. b = """c( a().next() + b)"""
  1791. a = """c( next(a()) + b)"""
  1792. self.check(b, a)
  1793. def test_prefix_preservation_1(self):
  1794. b = """
  1795. for a in b:
  1796. foo(a)
  1797. a.next()
  1798. """
  1799. a = """
  1800. for a in b:
  1801. foo(a)
  1802. next(a)
  1803. """
  1804. self.check(b, a)
  1805. def test_prefix_preservation_2(self):
  1806. b = """
  1807. for a in b:
  1808. foo(a) # abc
  1809. # def
  1810. a.next()
  1811. """
  1812. a = """
  1813. for a in b:
  1814. foo(a) # abc
  1815. # def
  1816. next(a)
  1817. """
  1818. self.check(b, a)
  1819. def test_prefix_preservation_3(self):
  1820. b = """
  1821. next = 5
  1822. for a in b:
  1823. foo(a)
  1824. a.next()
  1825. """
  1826. a = """
  1827. next = 5
  1828. for a in b:
  1829. foo(a)
  1830. a.__next__()
  1831. """
  1832. self.check(b, a, ignore_warnings=True)
  1833. def test_prefix_preservation_4(self):
  1834. b = """
  1835. next = 5
  1836. for a in b:
  1837. foo(a) # abc
  1838. # def
  1839. a.next()
  1840. """
  1841. a = """
  1842. next = 5
  1843. for a in b:
  1844. foo(a) # abc
  1845. # def
  1846. a.__next__()
  1847. """
  1848. self.check(b, a, ignore_warnings=True)
  1849. def test_prefix_preservation_5(self):
  1850. b = """
  1851. next = 5
  1852. for a in b:
  1853. foo(foo(a), # abc
  1854. a.next())
  1855. """
  1856. a = """
  1857. next = 5
  1858. for a in b:
  1859. foo(foo(a), # abc
  1860. a.__next__())
  1861. """
  1862. self.check(b, a, ignore_warnings=True)
  1863. def test_prefix_preservation_6(self):
  1864. b = """
  1865. for a in b:
  1866. foo(foo(a), # abc
  1867. a.next())
  1868. """
  1869. a = """
  1870. for a in b:
  1871. foo(foo(a), # abc
  1872. next(a))
  1873. """
  1874. self.check(b, a)
  1875. def test_method_1(self):
  1876. b = """
  1877. class A:
  1878. def next(self):
  1879. pass
  1880. """
  1881. a = """
  1882. class A:
  1883. def __next__(self):
  1884. pass
  1885. """
  1886. self.check(b, a)
  1887. def test_method_2(self):
  1888. b = """
  1889. class A(object):
  1890. def next(self):
  1891. pass
  1892. """
  1893. a = """
  1894. class A(object):
  1895. def __next__(self):
  1896. pass
  1897. """
  1898. self.check(b, a)
  1899. def test_method_3(self):
  1900. b = """
  1901. class A:
  1902. def next(x):
  1903. pass
  1904. """
  1905. a = """
  1906. class A:
  1907. def __next__(x):
  1908. pass
  1909. """
  1910. self.check(b, a)
  1911. def test_method_4(self):
  1912. b = """
  1913. class A:
  1914. def __init__(self, foo):
  1915. self.foo = foo
  1916. def next(self):
  1917. pass
  1918. def __iter__(self):
  1919. return self
  1920. """
  1921. a = """
  1922. class A:
  1923. def __init__(self, foo):
  1924. self.foo = foo
  1925. def __next__(self):
  1926. pass
  1927. def __iter__(self):
  1928. return self
  1929. """
  1930. self.check(b, a)
  1931. def test_method_unchanged(self):
  1932. s = """
  1933. class A:
  1934. def next(self, a, b):
  1935. pass
  1936. """
  1937. self.unchanged(s)
  1938. def test_shadowing_assign_simple(self):
  1939. s = """
  1940. next = foo
  1941. class A:
  1942. def next(self, a, b):
  1943. pass
  1944. """
  1945. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1946. def test_shadowing_assign_tuple_1(self):
  1947. s = """
  1948. (next, a) = foo
  1949. class A:
  1950. def next(self, a, b):
  1951. pass
  1952. """
  1953. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1954. def test_shadowing_assign_tuple_2(self):
  1955. s = """
  1956. (a, (b, (next, c)), a) = foo
  1957. class A:
  1958. def next(self, a, b):
  1959. pass
  1960. """
  1961. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1962. def test_shadowing_assign_list_1(self):
  1963. s = """
  1964. [next, a] = foo
  1965. class A:
  1966. def next(self, a, b):
  1967. pass
  1968. """
  1969. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1970. def test_shadowing_assign_list_2(self):
  1971. s = """
  1972. [a, [b, [next, c]], a] = foo
  1973. class A:
  1974. def next(self, a, b):
  1975. pass
  1976. """
  1977. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1978. def test_builtin_assign(self):
  1979. s = """
  1980. def foo():
  1981. __builtin__.next = foo
  1982. class A:
  1983. def next(self, a, b):
  1984. pass
  1985. """
  1986. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1987. def test_builtin_assign_in_tuple(self):
  1988. s = """
  1989. def foo():
  1990. (a, __builtin__.next) = foo
  1991. class A:
  1992. def next(self, a, b):
  1993. pass
  1994. """
  1995. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  1996. def test_builtin_assign_in_list(self):
  1997. s = """
  1998. def foo():
  1999. [a, __builtin__.next] = foo
  2000. class A:
  2001. def next(self, a, b):
  2002. pass
  2003. """
  2004. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2005. def test_assign_to_next(self):
  2006. s = """
  2007. def foo():
  2008. A.next = foo
  2009. class A:
  2010. def next(self, a, b):
  2011. pass
  2012. """
  2013. self.unchanged(s)
  2014. def test_assign_to_next_in_tuple(self):
  2015. s = """
  2016. def foo():
  2017. (a, A.next) = foo
  2018. class A:
  2019. def next(self, a, b):
  2020. pass
  2021. """
  2022. self.unchanged(s)
  2023. def test_assign_to_next_in_list(self):
  2024. s = """
  2025. def foo():
  2026. [a, A.next] = foo
  2027. class A:
  2028. def next(self, a, b):
  2029. pass
  2030. """
  2031. self.unchanged(s)
  2032. def test_shadowing_import_1(self):
  2033. s = """
  2034. import foo.bar as next
  2035. class A:
  2036. def next(self, a, b):
  2037. pass
  2038. """
  2039. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2040. def test_shadowing_import_2(self):
  2041. s = """
  2042. import bar, bar.foo as next
  2043. class A:
  2044. def next(self, a, b):
  2045. pass
  2046. """
  2047. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2048. def test_shadowing_import_3(self):
  2049. s = """
  2050. import bar, bar.foo as next, baz
  2051. class A:
  2052. def next(self, a, b):
  2053. pass
  2054. """
  2055. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2056. def test_shadowing_import_from_1(self):
  2057. s = """
  2058. from x import next
  2059. class A:
  2060. def next(self, a, b):
  2061. pass
  2062. """
  2063. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2064. def test_shadowing_import_from_2(self):
  2065. s = """
  2066. from x.a import next
  2067. class A:
  2068. def next(self, a, b):
  2069. pass
  2070. """
  2071. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2072. def test_shadowing_import_from_3(self):
  2073. s = """
  2074. from x import a, next, b
  2075. class A:
  2076. def next(self, a, b):
  2077. pass
  2078. """
  2079. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2080. def test_shadowing_import_from_4(self):
  2081. s = """
  2082. from x.a import a, next, b
  2083. class A:
  2084. def next(self, a, b):
  2085. pass
  2086. """
  2087. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2088. def test_shadowing_funcdef_1(self):
  2089. s = """
  2090. def next(a):
  2091. pass
  2092. class A:
  2093. def next(self, a, b):
  2094. pass
  2095. """
  2096. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2097. def test_shadowing_funcdef_2(self):
  2098. b = """
  2099. def next(a):
  2100. pass
  2101. class A:
  2102. def next(self):
  2103. pass
  2104. it.next()
  2105. """
  2106. a = """
  2107. def next(a):
  2108. pass
  2109. class A:
  2110. def __next__(self):
  2111. pass
  2112. it.__next__()
  2113. """
  2114. self.warns(b, a, "Calls to builtin next() possibly shadowed")
  2115. def test_shadowing_global_1(self):
  2116. s = """
  2117. def f():
  2118. global next
  2119. next = 5
  2120. """
  2121. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2122. def test_shadowing_global_2(self):
  2123. s = """
  2124. def f():
  2125. global a, next, b
  2126. next = 5
  2127. """
  2128. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2129. def test_shadowing_for_simple(self):
  2130. s = """
  2131. for next in it():
  2132. pass
  2133. b = 5
  2134. c = 6
  2135. """
  2136. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2137. def test_shadowing_for_tuple_1(self):
  2138. s = """
  2139. for next, b in it():
  2140. pass
  2141. b = 5
  2142. c = 6
  2143. """
  2144. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2145. def test_shadowing_for_tuple_2(self):
  2146. s = """
  2147. for a, (next, c), b in it():
  2148. pass
  2149. b = 5
  2150. c = 6
  2151. """
  2152. self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
  2153. def test_noncall_access_1(self):
  2154. b = """gnext = g.next"""
  2155. a = """gnext = g.__next__"""
  2156. self.check(b, a)
  2157. def test_noncall_access_2(self):
  2158. b = """f(g.next + 5)"""
  2159. a = """f(g.__next__ + 5)"""
  2160. self.check(b, a)
  2161. def test_noncall_access_3(self):
  2162. b = """f(g().next + 5)"""
  2163. a = """f(g().__next__ + 5)"""
  2164. self.check(b, a)
  2165. class Test_nonzero(FixerTestCase):
  2166. fixer = "nonzero"
  2167. def test_1(self):
  2168. b = """
  2169. class A:
  2170. def __nonzero__(self):
  2171. pass
  2172. """
  2173. a = """
  2174. class A:
  2175. def __bool__(self):
  2176. pass
  2177. """
  2178. self.check(b, a)
  2179. def test_2(self):
  2180. b = """
  2181. class A(object):
  2182. def __nonzero__(self):
  2183. pass
  2184. """
  2185. a = """
  2186. class A(object):
  2187. def __bool__(self):
  2188. pass
  2189. """
  2190. self.check(b, a)
  2191. def test_unchanged_1(self):
  2192. s = """
  2193. class A(object):
  2194. def __bool__(self):
  2195. pass
  2196. """
  2197. self.unchanged(s)
  2198. def test_unchanged_2(self):
  2199. s = """
  2200. class A(object):
  2201. def __nonzero__(self, a):
  2202. pass
  2203. """
  2204. self.unchanged(s)
  2205. def test_unchanged_func(self):
  2206. s = """
  2207. def __nonzero__(self):
  2208. pass
  2209. """
  2210. self.unchanged(s)
  2211. class Test_numliterals(FixerTestCase):
  2212. fixer = "numliterals"
  2213. def test_octal_1(self):
  2214. b = """0755"""
  2215. a = """0o755"""
  2216. self.check(b, a)
  2217. def test_long_int_1(self):
  2218. b = """a = 12L"""
  2219. a = """a = 12"""
  2220. self.check(b, a)
  2221. def test_long_int_2(self):
  2222. b = """a = 12l"""
  2223. a = """a = 12"""
  2224. self.check(b, a)
  2225. def test_long_hex(self):
  2226. b = """b = 0x12l"""
  2227. a = """b = 0x12"""
  2228. self.check(b, a)
  2229. def test_comments_and_spacing(self):
  2230. b = """b = 0x12L"""
  2231. a = """b = 0x12"""
  2232. self.check(b, a)
  2233. b = """b = 0755 # spam"""
  2234. a = """b = 0o755 # spam"""
  2235. self.check(b, a)
  2236. def test_unchanged_int(self):
  2237. s = """5"""
  2238. self.unchanged(s)
  2239. def test_unchanged_float(self):
  2240. s = """5.0"""
  2241. self.unchanged(s)
  2242. def test_unchanged_octal(self):
  2243. s = """0o755"""
  2244. self.unchanged(s)
  2245. def test_unchanged_hex(self):
  2246. s = """0xABC"""
  2247. self.unchanged(s)
  2248. def test_unchanged_exp(self):
  2249. s = """5.0e10"""
  2250. self.unchanged(s)
  2251. def test_unchanged_complex_int(self):
  2252. s = """5 + 4j"""
  2253. self.unchanged(s)
  2254. def test_unchanged_complex_float(self):
  2255. s = """5.4 + 4.9j"""
  2256. self.unchanged(s)
  2257. def test_unchanged_complex_bare(self):
  2258. s = """4j"""
  2259. self.unchanged(s)
  2260. s = """4.4j"""
  2261. self.unchanged(s)
  2262. class Test_renames(FixerTestCase):
  2263. fixer = "renames"
  2264. modules = {"sys": ("maxint", "maxsize"),
  2265. }
  2266. def test_import_from(self):
  2267. for mod, (old, new) in list(self.modules.items()):
  2268. b = "from %s import %s" % (mod, old)
  2269. a = "from %s import %s" % (mod, new)
  2270. self.check(b, a)
  2271. s = "from foo import %s" % old
  2272. self.unchanged(s)
  2273. def test_import_from_as(self):
  2274. for mod, (old, new) in list(self.modules.items()):
  2275. b = "from %s import %s as foo_bar" % (mod, old)
  2276. a = "from %s import %s as foo_bar" % (mod, new)
  2277. self.check(b, a)
  2278. def test_import_module_usage(self):
  2279. for mod, (old, new) in list(self.modules.items()):
  2280. b = """
  2281. import %s
  2282. foo(%s, %s.%s)
  2283. """ % (mod, mod, mod, old)
  2284. a = """
  2285. import %s
  2286. foo(%s, %s.%s)
  2287. """ % (mod, mod, mod, new)
  2288. self.check(b, a)
  2289. def XXX_test_from_import_usage(self):
  2290. # not implemented yet
  2291. for mod, (old, new) in list(self.modules.items()):
  2292. b = """
  2293. from %s import %s
  2294. foo(%s, %s)
  2295. """ % (mod, old, mod, old)
  2296. a = """
  2297. from %s import %s
  2298. foo(%s, %s)
  2299. """ % (mod, new, mod, new)
  2300. self.check(b, a)
  2301. class Test_unicode(FixerTestCase):
  2302. fixer = "unicode"
  2303. def test_whitespace(self):
  2304. b = """unicode( x)"""
  2305. a = """str( x)"""
  2306. self.check(b, a)
  2307. b = """ unicode(x )"""
  2308. a = """ str(x )"""
  2309. self.check(b, a)
  2310. b = """ u'h'"""
  2311. a = """ 'h'"""
  2312. self.check(b, a)
  2313. def test_unicode_call(self):
  2314. b = """unicode(x, y, z)"""
  2315. a = """str(x, y, z)"""
  2316. self.check(b, a)
  2317. def test_unichr(self):
  2318. b = """unichr(u'h')"""
  2319. a = """chr('h')"""
  2320. self.check(b, a)
  2321. def test_unicode_literal_1(self):
  2322. b = '''u"x"'''
  2323. a = '''"x"'''
  2324. self.check(b, a)
  2325. def test_unicode_literal_2(self):
  2326. b = """ur'x'"""
  2327. a = """r'x'"""
  2328. self.check(b, a)
  2329. def test_unicode_literal_3(self):
  2330. b = """UR'''x''' """
  2331. a = """R'''x''' """
  2332. self.check(b, a)
  2333. def test_native_literal_escape_u(self):
  2334. b = r"""'\\\u20ac\U0001d121\\u20ac'"""
  2335. a = r"""'\\\\u20ac\\U0001d121\\u20ac'"""
  2336. self.check(b, a)
  2337. b = r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2338. a = r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2339. self.check(b, a)
  2340. def test_bytes_literal_escape_u(self):
  2341. b = r"""b'\\\u20ac\U0001d121\\u20ac'"""
  2342. a = r"""b'\\\u20ac\U0001d121\\u20ac'"""
  2343. self.check(b, a)
  2344. b = r"""br'\\\u20ac\U0001d121\\u20ac'"""
  2345. a = r"""br'\\\u20ac\U0001d121\\u20ac'"""
  2346. self.check(b, a)
  2347. def test_unicode_literal_escape_u(self):
  2348. b = r"""u'\\\u20ac\U0001d121\\u20ac'"""
  2349. a = r"""'\\\u20ac\U0001d121\\u20ac'"""
  2350. self.check(b, a)
  2351. b = r"""ur'\\\u20ac\U0001d121\\u20ac'"""
  2352. a = r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2353. self.check(b, a)
  2354. def test_native_unicode_literal_escape_u(self):
  2355. f = 'from __future__ import unicode_literals\n'
  2356. b = f + r"""'\\\u20ac\U0001d121\\u20ac'"""
  2357. a = f + r"""'\\\u20ac\U0001d121\\u20ac'"""
  2358. self.check(b, a)
  2359. b = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2360. a = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""
  2361. self.check(b, a)
  2362. class Test_filter(FixerTestCase):
  2363. fixer = "filter"
  2364. def test_prefix_preservation(self):
  2365. b = """x = filter( foo, 'abc' )"""
  2366. a = """x = list(filter( foo, 'abc' ))"""
  2367. self.check(b, a)
  2368. b = """x = filter( None , 'abc' )"""
  2369. a = """x = [_f for _f in 'abc' if _f]"""
  2370. self.check(b, a)
  2371. def test_filter_basic(self):
  2372. b = """x = filter(None, 'abc')"""
  2373. a = """x = [_f for _f in 'abc' if _f]"""
  2374. self.check(b, a)
  2375. b = """x = len(filter(f, 'abc'))"""
  2376. a = """x = len(list(filter(f, 'abc')))"""
  2377. self.check(b, a)
  2378. b = """x = filter(lambda x: x%2 == 0, range(10))"""
  2379. a = """x = [x for x in range(10) if x%2 == 0]"""
  2380. self.check(b, a)
  2381. # Note the parens around x
  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. # bpo-38871
  2386. b = """filter(lambda x: True if x > 2 else False, [1, 2, 3])"""
  2387. a = """[x for x in [1, 2, 3] if (True if x > 2 else False)]"""
  2388. self.check(b, a)
  2389. def test_filter_trailers(self):
  2390. b = """x = filter(None, 'abc')[0]"""
  2391. a = """x = [_f for _f in 'abc' if _f][0]"""
  2392. self.check(b, a)
  2393. b = """x = len(filter(f, 'abc')[0])"""
  2394. a = """x = len(list(filter(f, 'abc'))[0])"""
  2395. self.check(b, a)
  2396. b = """x = filter(lambda x: x%2 == 0, range(10))[0]"""
  2397. a = """x = [x for x in range(10) if x%2 == 0][0]"""
  2398. self.check(b, a)
  2399. # Note the parens around x
  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. def test_filter_nochange(self):
  2404. a = """b.join(filter(f, 'abc'))"""
  2405. self.unchanged(a)
  2406. a = """(a + foo(5)).join(filter(f, 'abc'))"""
  2407. self.unchanged(a)
  2408. a = """iter(filter(f, 'abc'))"""
  2409. self.unchanged(a)
  2410. a = """list(filter(f, 'abc'))"""
  2411. self.unchanged(a)
  2412. a = """list(filter(f, 'abc'))[0]"""
  2413. self.unchanged(a)
  2414. a = """set(filter(f, 'abc'))"""
  2415. self.unchanged(a)
  2416. a = """set(filter(f, 'abc')).pop()"""
  2417. self.unchanged(a)
  2418. a = """tuple(filter(f, 'abc'))"""
  2419. self.unchanged(a)
  2420. a = """any(filter(f, 'abc'))"""
  2421. self.unchanged(a)
  2422. a = """all(filter(f, 'abc'))"""
  2423. self.unchanged(a)
  2424. a = """sum(filter(f, 'abc'))"""
  2425. self.unchanged(a)
  2426. a = """sorted(filter(f, 'abc'))"""
  2427. self.unchanged(a)
  2428. a = """sorted(filter(f, 'abc'), key=blah)"""
  2429. self.unchanged(a)
  2430. a = """sorted(filter(f, 'abc'), key=blah)[0]"""
  2431. self.unchanged(a)
  2432. a = """enumerate(filter(f, 'abc'))"""
  2433. self.unchanged(a)
  2434. a = """enumerate(filter(f, 'abc'), start=1)"""
  2435. self.unchanged(a)
  2436. a = """for i in filter(f, 'abc'): pass"""
  2437. self.unchanged(a)
  2438. a = """[x for x in filter(f, 'abc')]"""
  2439. self.unchanged(a)
  2440. a = """(x for x in filter(f, 'abc'))"""
  2441. self.unchanged(a)
  2442. def test_future_builtins(self):
  2443. a = "from future_builtins import spam, filter; filter(f, 'ham')"
  2444. self.unchanged(a)
  2445. b = """from future_builtins import spam; x = filter(f, 'abc')"""
  2446. a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""
  2447. self.check(b, a)
  2448. a = "from future_builtins import *; filter(f, 'ham')"
  2449. self.unchanged(a)
  2450. class Test_map(FixerTestCase):
  2451. fixer = "map"
  2452. def check(self, b, a):
  2453. self.unchanged("from future_builtins import map; " + b, a)
  2454. super(Test_map, self).check(b, a)
  2455. def test_prefix_preservation(self):
  2456. b = """x = map( f, 'abc' )"""
  2457. a = """x = list(map( f, 'abc' ))"""
  2458. self.check(b, a)
  2459. def test_map_trailers(self):
  2460. b = """x = map(f, 'abc')[0]"""
  2461. a = """x = list(map(f, 'abc'))[0]"""
  2462. self.check(b, a)
  2463. b = """x = map(None, l)[0]"""
  2464. a = """x = list(l)[0]"""
  2465. self.check(b, a)
  2466. b = """x = map(lambda x:x, l)[0]"""
  2467. a = """x = [x for x in l][0]"""
  2468. self.check(b, a)
  2469. b = """x = map(f, 'abc')[0][1]"""
  2470. a = """x = list(map(f, 'abc'))[0][1]"""
  2471. self.check(b, a)
  2472. def test_trailing_comment(self):
  2473. b = """x = map(f, 'abc') # foo"""
  2474. a = """x = list(map(f, 'abc')) # foo"""
  2475. self.check(b, a)
  2476. def test_None_with_multiple_arguments(self):
  2477. s = """x = map(None, a, b, c)"""
  2478. self.warns_unchanged(s, "cannot convert map(None, ...) with "
  2479. "multiple arguments")
  2480. def test_map_basic(self):
  2481. b = """x = map(f, 'abc')"""
  2482. a = """x = list(map(f, 'abc'))"""
  2483. self.check(b, a)
  2484. b = """x = len(map(f, 'abc', 'def'))"""
  2485. a = """x = len(list(map(f, 'abc', 'def')))"""
  2486. self.check(b, a)
  2487. b = """x = map(None, 'abc')"""
  2488. a = """x = list('abc')"""
  2489. self.check(b, a)
  2490. b = """x = map(lambda x: x+1, range(4))"""
  2491. a = """x = [x+1 for x in range(4)]"""
  2492. self.check(b, a)
  2493. # Note the parens around x
  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. b = """
  2498. foo()
  2499. # foo
  2500. map(f, x)
  2501. """
  2502. a = """
  2503. foo()
  2504. # foo
  2505. list(map(f, x))
  2506. """
  2507. self.warns(b, a, "You should use a for loop here")
  2508. def test_map_nochange(self):
  2509. a = """b.join(map(f, 'abc'))"""
  2510. self.unchanged(a)
  2511. a = """(a + foo(5)).join(map(f, 'abc'))"""
  2512. self.unchanged(a)
  2513. a = """iter(map(f, 'abc'))"""
  2514. self.unchanged(a)
  2515. a = """list(map(f, 'abc'))"""
  2516. self.unchanged(a)
  2517. a = """list(map(f, 'abc'))[0]"""
  2518. self.unchanged(a)
  2519. a = """set(map(f, 'abc'))"""
  2520. self.unchanged(a)
  2521. a = """set(map(f, 'abc')).pop()"""
  2522. self.unchanged(a)
  2523. a = """tuple(map(f, 'abc'))"""
  2524. self.unchanged(a)
  2525. a = """any(map(f, 'abc'))"""
  2526. self.unchanged(a)
  2527. a = """all(map(f, 'abc'))"""
  2528. self.unchanged(a)
  2529. a = """sum(map(f, 'abc'))"""
  2530. self.unchanged(a)
  2531. a = """sorted(map(f, 'abc'))"""
  2532. self.unchanged(a)
  2533. a = """sorted(map(f, 'abc'), key=blah)"""
  2534. self.unchanged(a)
  2535. a = """sorted(map(f, 'abc'), key=blah)[0]"""
  2536. self.unchanged(a)
  2537. a = """enumerate(map(f, 'abc'))"""
  2538. self.unchanged(a)
  2539. a = """enumerate(map(f, 'abc'), start=1)"""
  2540. self.unchanged(a)
  2541. a = """for i in map(f, 'abc'): pass"""
  2542. self.unchanged(a)
  2543. a = """[x for x in map(f, 'abc')]"""
  2544. self.unchanged(a)
  2545. a = """(x for x in map(f, 'abc'))"""
  2546. self.unchanged(a)
  2547. def test_future_builtins(self):
  2548. a = "from future_builtins import spam, map, eggs; map(f, 'ham')"
  2549. self.unchanged(a)
  2550. b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""
  2551. a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
  2552. self.check(b, a)
  2553. a = "from future_builtins import *; map(f, 'ham')"
  2554. self.unchanged(a)
  2555. class Test_zip(FixerTestCase):
  2556. fixer = "zip"
  2557. def check(self, b, a):
  2558. self.unchanged("from future_builtins import zip; " + b, a)
  2559. super(Test_zip, self).check(b, a)
  2560. def test_zip_basic(self):
  2561. b = """x = zip()"""
  2562. a = """x = list(zip())"""
  2563. self.check(b, a)
  2564. b = """x = zip(a, b, c)"""
  2565. a = """x = list(zip(a, b, c))"""
  2566. self.check(b, a)
  2567. b = """x = len(zip(a, b))"""
  2568. a = """x = len(list(zip(a, b)))"""
  2569. self.check(b, a)
  2570. def test_zip_trailers(self):
  2571. b = """x = zip(a, b, c)[0]"""
  2572. a = """x = list(zip(a, b, c))[0]"""
  2573. self.check(b, a)
  2574. b = """x = zip(a, b, c)[0][1]"""
  2575. a = """x = list(zip(a, b, c))[0][1]"""
  2576. self.check(b, a)
  2577. def test_zip_nochange(self):
  2578. a = """b.join(zip(a, b))"""
  2579. self.unchanged(a)
  2580. a = """(a + foo(5)).join(zip(a, b))"""
  2581. self.unchanged(a)
  2582. a = """iter(zip(a, b))"""
  2583. self.unchanged(a)
  2584. a = """list(zip(a, b))"""
  2585. self.unchanged(a)
  2586. a = """list(zip(a, b))[0]"""
  2587. self.unchanged(a)
  2588. a = """set(zip(a, b))"""
  2589. self.unchanged(a)
  2590. a = """set(zip(a, b)).pop()"""
  2591. self.unchanged(a)
  2592. a = """tuple(zip(a, b))"""
  2593. self.unchanged(a)
  2594. a = """any(zip(a, b))"""
  2595. self.unchanged(a)
  2596. a = """all(zip(a, b))"""
  2597. self.unchanged(a)
  2598. a = """sum(zip(a, b))"""
  2599. self.unchanged(a)
  2600. a = """sorted(zip(a, b))"""
  2601. self.unchanged(a)
  2602. a = """sorted(zip(a, b), key=blah)"""
  2603. self.unchanged(a)
  2604. a = """sorted(zip(a, b), key=blah)[0]"""
  2605. self.unchanged(a)
  2606. a = """enumerate(zip(a, b))"""
  2607. self.unchanged(a)
  2608. a = """enumerate(zip(a, b), start=1)"""
  2609. self.unchanged(a)
  2610. a = """for i in zip(a, b): pass"""
  2611. self.unchanged(a)
  2612. a = """[x for x in zip(a, b)]"""
  2613. self.unchanged(a)
  2614. a = """(x for x in zip(a, b))"""
  2615. self.unchanged(a)
  2616. def test_future_builtins(self):
  2617. a = "from future_builtins import spam, zip, eggs; zip(a, b)"
  2618. self.unchanged(a)
  2619. b = """from future_builtins import spam, eggs; x = zip(a, b)"""
  2620. a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""
  2621. self.check(b, a)
  2622. a = "from future_builtins import *; zip(a, b)"
  2623. self.unchanged(a)
  2624. class Test_standarderror(FixerTestCase):
  2625. fixer = "standarderror"
  2626. def test(self):
  2627. b = """x = StandardError()"""
  2628. a = """x = Exception()"""
  2629. self.check(b, a)
  2630. b = """x = StandardError(a, b, c)"""
  2631. a = """x = Exception(a, b, c)"""
  2632. self.check(b, a)
  2633. b = """f(2 + StandardError(a, b, c))"""
  2634. a = """f(2 + Exception(a, b, c))"""
  2635. self.check(b, a)
  2636. class Test_types(FixerTestCase):
  2637. fixer = "types"
  2638. def test_basic_types_convert(self):
  2639. b = """types.StringType"""
  2640. a = """bytes"""
  2641. self.check(b, a)
  2642. b = """types.DictType"""
  2643. a = """dict"""
  2644. self.check(b, a)
  2645. b = """types . IntType"""
  2646. a = """int"""
  2647. self.check(b, a)
  2648. b = """types.ListType"""
  2649. a = """list"""
  2650. self.check(b, a)
  2651. b = """types.LongType"""
  2652. a = """int"""
  2653. self.check(b, a)
  2654. b = """types.NoneType"""
  2655. a = """type(None)"""
  2656. self.check(b, a)
  2657. b = "types.StringTypes"
  2658. a = "(str,)"
  2659. self.check(b, a)
  2660. class Test_idioms(FixerTestCase):
  2661. fixer = "idioms"
  2662. def test_while(self):
  2663. b = """while 1: foo()"""
  2664. a = """while True: foo()"""
  2665. self.check(b, a)
  2666. b = """while 1: foo()"""
  2667. a = """while True: foo()"""
  2668. self.check(b, a)
  2669. b = """
  2670. while 1:
  2671. foo()
  2672. """
  2673. a = """
  2674. while True:
  2675. foo()
  2676. """
  2677. self.check(b, a)
  2678. def test_while_unchanged(self):
  2679. s = """while 11: foo()"""
  2680. self.unchanged(s)
  2681. s = """while 0: foo()"""
  2682. self.unchanged(s)
  2683. s = """while foo(): foo()"""
  2684. self.unchanged(s)
  2685. s = """while []: foo()"""
  2686. self.unchanged(s)
  2687. def test_eq_simple(self):
  2688. b = """type(x) == T"""
  2689. a = """isinstance(x, T)"""
  2690. self.check(b, a)
  2691. b = """if type(x) == T: pass"""
  2692. a = """if isinstance(x, T): pass"""
  2693. self.check(b, a)
  2694. def test_eq_reverse(self):
  2695. b = """T == type(x)"""
  2696. a = """isinstance(x, T)"""
  2697. self.check(b, a)
  2698. b = """if T == type(x): pass"""
  2699. a = """if isinstance(x, T): pass"""
  2700. self.check(b, a)
  2701. def test_eq_expression(self):
  2702. b = """type(x+y) == d.get('T')"""
  2703. a = """isinstance(x+y, d.get('T'))"""
  2704. self.check(b, a)
  2705. b = """type( x + y) == d.get('T')"""
  2706. a = """isinstance(x + y, d.get('T'))"""
  2707. self.check(b, a)
  2708. def test_is_simple(self):
  2709. b = """type(x) is T"""
  2710. a = """isinstance(x, T)"""
  2711. self.check(b, a)
  2712. b = """if type(x) is T: pass"""
  2713. a = """if isinstance(x, T): pass"""
  2714. self.check(b, a)
  2715. def test_is_reverse(self):
  2716. b = """T is type(x)"""
  2717. a = """isinstance(x, T)"""
  2718. self.check(b, a)
  2719. b = """if T is type(x): pass"""
  2720. a = """if isinstance(x, T): pass"""
  2721. self.check(b, a)
  2722. def test_is_expression(self):
  2723. b = """type(x+y) is d.get('T')"""
  2724. a = """isinstance(x+y, d.get('T'))"""
  2725. self.check(b, a)
  2726. b = """type( x + y) is d.get('T')"""
  2727. a = """isinstance(x + y, d.get('T'))"""
  2728. self.check(b, a)
  2729. def test_is_not_simple(self):
  2730. b = """type(x) is not T"""
  2731. a = """not isinstance(x, T)"""
  2732. self.check(b, a)
  2733. b = """if type(x) is not T: pass"""
  2734. a = """if not isinstance(x, T): pass"""
  2735. self.check(b, a)
  2736. def test_is_not_reverse(self):
  2737. b = """T is not type(x)"""
  2738. a = """not isinstance(x, T)"""
  2739. self.check(b, a)
  2740. b = """if T is not type(x): pass"""
  2741. a = """if not isinstance(x, T): pass"""
  2742. self.check(b, a)
  2743. def test_is_not_expression(self):
  2744. b = """type(x+y) is not d.get('T')"""
  2745. a = """not isinstance(x+y, d.get('T'))"""
  2746. self.check(b, a)
  2747. b = """type( x + y) is not d.get('T')"""
  2748. a = """not isinstance(x + y, d.get('T'))"""
  2749. self.check(b, a)
  2750. def test_ne_simple(self):
  2751. b = """type(x) != T"""
  2752. a = """not isinstance(x, T)"""
  2753. self.check(b, a)
  2754. b = """if type(x) != T: pass"""
  2755. a = """if not isinstance(x, T): pass"""
  2756. self.check(b, a)
  2757. def test_ne_reverse(self):
  2758. b = """T != type(x)"""
  2759. a = """not isinstance(x, T)"""
  2760. self.check(b, a)
  2761. b = """if T != type(x): pass"""
  2762. a = """if not isinstance(x, T): pass"""
  2763. self.check(b, a)
  2764. def test_ne_expression(self):
  2765. b = """type(x+y) != d.get('T')"""
  2766. a = """not isinstance(x+y, d.get('T'))"""
  2767. self.check(b, a)
  2768. b = """type( x + y) != d.get('T')"""
  2769. a = """not isinstance(x + y, d.get('T'))"""
  2770. self.check(b, a)
  2771. def test_type_unchanged(self):
  2772. a = """type(x).__name__"""
  2773. self.unchanged(a)
  2774. def test_sort_list_call(self):
  2775. b = """
  2776. v = list(t)
  2777. v.sort()
  2778. foo(v)
  2779. """
  2780. a = """
  2781. v = sorted(t)
  2782. foo(v)
  2783. """
  2784. self.check(b, a)
  2785. b = """
  2786. v = list(foo(b) + d)
  2787. v.sort()
  2788. foo(v)
  2789. """
  2790. a = """
  2791. v = sorted(foo(b) + d)
  2792. foo(v)
  2793. """
  2794. self.check(b, a)
  2795. b = """
  2796. while x:
  2797. v = list(t)
  2798. v.sort()
  2799. foo(v)
  2800. """
  2801. a = """
  2802. while x:
  2803. v = sorted(t)
  2804. foo(v)
  2805. """
  2806. self.check(b, a)
  2807. b = """
  2808. v = list(t)
  2809. # foo
  2810. v.sort()
  2811. foo(v)
  2812. """
  2813. a = """
  2814. v = sorted(t)
  2815. # foo
  2816. foo(v)
  2817. """
  2818. self.check(b, a)
  2819. b = r"""
  2820. v = list( t)
  2821. v.sort()
  2822. foo(v)
  2823. """
  2824. a = r"""
  2825. v = sorted( t)
  2826. foo(v)
  2827. """
  2828. self.check(b, a)
  2829. b = r"""
  2830. try:
  2831. m = list(s)
  2832. m.sort()
  2833. except: pass
  2834. """
  2835. a = r"""
  2836. try:
  2837. m = sorted(s)
  2838. except: pass
  2839. """
  2840. self.check(b, a)
  2841. b = r"""
  2842. try:
  2843. m = list(s)
  2844. # foo
  2845. m.sort()
  2846. except: pass
  2847. """
  2848. a = r"""
  2849. try:
  2850. m = sorted(s)
  2851. # foo
  2852. except: pass
  2853. """
  2854. self.check(b, a)
  2855. b = r"""
  2856. m = list(s)
  2857. # more comments
  2858. m.sort()"""
  2859. a = r"""
  2860. m = sorted(s)
  2861. # more comments"""
  2862. self.check(b, a)
  2863. def test_sort_simple_expr(self):
  2864. b = """
  2865. v = t
  2866. v.sort()
  2867. foo(v)
  2868. """
  2869. a = """
  2870. v = sorted(t)
  2871. foo(v)
  2872. """
  2873. self.check(b, a)
  2874. b = """
  2875. v = foo(b)
  2876. v.sort()
  2877. foo(v)
  2878. """
  2879. a = """
  2880. v = sorted(foo(b))
  2881. foo(v)
  2882. """
  2883. self.check(b, a)
  2884. b = """
  2885. v = b.keys()
  2886. v.sort()
  2887. foo(v)
  2888. """
  2889. a = """
  2890. v = sorted(b.keys())
  2891. foo(v)
  2892. """
  2893. self.check(b, a)
  2894. b = """
  2895. v = foo(b) + d
  2896. v.sort()
  2897. foo(v)
  2898. """
  2899. a = """
  2900. v = sorted(foo(b) + d)
  2901. foo(v)
  2902. """
  2903. self.check(b, a)
  2904. b = """
  2905. while x:
  2906. v = t
  2907. v.sort()
  2908. foo(v)
  2909. """
  2910. a = """
  2911. while x:
  2912. v = sorted(t)
  2913. foo(v)
  2914. """
  2915. self.check(b, a)
  2916. b = """
  2917. v = t
  2918. # foo
  2919. v.sort()
  2920. foo(v)
  2921. """
  2922. a = """
  2923. v = sorted(t)
  2924. # foo
  2925. foo(v)
  2926. """
  2927. self.check(b, a)
  2928. b = r"""
  2929. v = t
  2930. v.sort()
  2931. foo(v)
  2932. """
  2933. a = r"""
  2934. v = sorted(t)
  2935. foo(v)
  2936. """
  2937. self.check(b, a)
  2938. def test_sort_unchanged(self):
  2939. s = """
  2940. v = list(t)
  2941. w.sort()
  2942. foo(w)
  2943. """
  2944. self.unchanged(s)
  2945. s = """
  2946. v = list(t)
  2947. v.sort(u)
  2948. foo(v)
  2949. """
  2950. self.unchanged(s)
  2951. class Test_basestring(FixerTestCase):
  2952. fixer = "basestring"
  2953. def test_basestring(self):
  2954. b = """isinstance(x, basestring)"""
  2955. a = """isinstance(x, str)"""
  2956. self.check(b, a)
  2957. class Test_buffer(FixerTestCase):
  2958. fixer = "buffer"
  2959. def test_buffer(self):
  2960. b = """x = buffer(y)"""
  2961. a = """x = memoryview(y)"""
  2962. self.check(b, a)
  2963. def test_slicing(self):
  2964. b = """buffer(y)[4:5]"""
  2965. a = """memoryview(y)[4:5]"""
  2966. self.check(b, a)
  2967. class Test_future(FixerTestCase):
  2968. fixer = "future"
  2969. def test_future(self):
  2970. b = """from __future__ import braces"""
  2971. a = """"""
  2972. self.check(b, a)
  2973. b = """# comment\nfrom __future__ import braces"""
  2974. a = """# comment\n"""
  2975. self.check(b, a)
  2976. b = """from __future__ import braces\n# comment"""
  2977. a = """\n# comment"""
  2978. self.check(b, a)
  2979. def test_run_order(self):
  2980. self.assert_runs_after('print')
  2981. class Test_itertools(FixerTestCase):
  2982. fixer = "itertools"
  2983. def checkall(self, before, after):
  2984. # Because we need to check with and without the itertools prefix
  2985. # and on each of the three functions, these loops make it all
  2986. # much easier
  2987. for i in ('itertools.', ''):
  2988. for f in ('map', 'filter', 'zip'):
  2989. b = before %(i+'i'+f)
  2990. a = after %(f)
  2991. self.check(b, a)
  2992. def test_0(self):
  2993. # A simple example -- test_1 covers exactly the same thing,
  2994. # but it's not quite as clear.
  2995. b = "itertools.izip(a, b)"
  2996. a = "zip(a, b)"
  2997. self.check(b, a)
  2998. def test_1(self):
  2999. b = """%s(f, a)"""
  3000. a = """%s(f, a)"""
  3001. self.checkall(b, a)
  3002. def test_qualified(self):
  3003. b = """itertools.ifilterfalse(a, b)"""
  3004. a = """itertools.filterfalse(a, b)"""
  3005. self.check(b, a)
  3006. b = """itertools.izip_longest(a, b)"""
  3007. a = """itertools.zip_longest(a, b)"""
  3008. self.check(b, a)
  3009. def test_2(self):
  3010. b = """ifilterfalse(a, b)"""
  3011. a = """filterfalse(a, b)"""
  3012. self.check(b, a)
  3013. b = """izip_longest(a, b)"""
  3014. a = """zip_longest(a, b)"""
  3015. self.check(b, a)
  3016. def test_space_1(self):
  3017. b = """ %s(f, a)"""
  3018. a = """ %s(f, a)"""
  3019. self.checkall(b, a)
  3020. def test_space_2(self):
  3021. b = """ itertools.ifilterfalse(a, b)"""
  3022. a = """ itertools.filterfalse(a, b)"""
  3023. self.check(b, a)
  3024. b = """ itertools.izip_longest(a, b)"""
  3025. a = """ itertools.zip_longest(a, b)"""
  3026. self.check(b, a)
  3027. def test_run_order(self):
  3028. self.assert_runs_after('map', 'zip', 'filter')
  3029. class Test_itertools_imports(FixerTestCase):
  3030. fixer = 'itertools_imports'
  3031. def test_reduced(self):
  3032. b = "from itertools import imap, izip, foo"
  3033. a = "from itertools import foo"
  3034. self.check(b, a)
  3035. b = "from itertools import bar, imap, izip, foo"
  3036. a = "from itertools import bar, foo"
  3037. self.check(b, a)
  3038. b = "from itertools import chain, imap, izip"
  3039. a = "from itertools import chain"
  3040. self.check(b, a)
  3041. def test_comments(self):
  3042. b = "#foo\nfrom itertools import imap, izip"
  3043. a = "#foo\n"
  3044. self.check(b, a)
  3045. def test_none(self):
  3046. b = "from itertools import imap, izip"
  3047. a = ""
  3048. self.check(b, a)
  3049. b = "from itertools import izip"
  3050. a = ""
  3051. self.check(b, a)
  3052. def test_import_as(self):
  3053. b = "from itertools import izip, bar as bang, imap"
  3054. a = "from itertools import bar as bang"
  3055. self.check(b, a)
  3056. b = "from itertools import izip as _zip, imap, bar"
  3057. a = "from itertools import bar"
  3058. self.check(b, a)
  3059. b = "from itertools import imap as _map"
  3060. a = ""
  3061. self.check(b, a)
  3062. b = "from itertools import imap as _map, izip as _zip"
  3063. a = ""
  3064. self.check(b, a)
  3065. s = "from itertools import bar as bang"
  3066. self.unchanged(s)
  3067. def test_ifilter_and_zip_longest(self):
  3068. for name in "filterfalse", "zip_longest":
  3069. b = "from itertools import i%s" % (name,)
  3070. a = "from itertools import %s" % (name,)
  3071. self.check(b, a)
  3072. b = "from itertools import imap, i%s, foo" % (name,)
  3073. a = "from itertools import %s, foo" % (name,)
  3074. self.check(b, a)
  3075. b = "from itertools import bar, i%s, foo" % (name,)
  3076. a = "from itertools import bar, %s, foo" % (name,)
  3077. self.check(b, a)
  3078. def test_import_star(self):
  3079. s = "from itertools import *"
  3080. self.unchanged(s)
  3081. def test_unchanged(self):
  3082. s = "from itertools import foo"
  3083. self.unchanged(s)
  3084. class Test_import(FixerTestCase):
  3085. fixer = "import"
  3086. def setUp(self):
  3087. super(Test_import, self).setUp()
  3088. # Need to replace fix_import's exists method
  3089. # so we can check that it's doing the right thing
  3090. self.files_checked = []
  3091. self.present_files = set()
  3092. self.always_exists = True
  3093. def fake_exists(name):
  3094. self.files_checked.append(name)
  3095. return self.always_exists or (name in self.present_files)
  3096. from lib2to3.fixes import fix_import
  3097. fix_import.exists = fake_exists
  3098. def tearDown(self):
  3099. from lib2to3.fixes import fix_import
  3100. fix_import.exists = os.path.exists
  3101. def check_both(self, b, a):
  3102. self.always_exists = True
  3103. super(Test_import, self).check(b, a)
  3104. self.always_exists = False
  3105. super(Test_import, self).unchanged(b)
  3106. def test_files_checked(self):
  3107. def p(path):
  3108. # Takes a unix path and returns a path with correct separators
  3109. return os.path.pathsep.join(path.split("/"))
  3110. self.always_exists = False
  3111. self.present_files = set(['__init__.py'])
  3112. expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')
  3113. names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
  3114. for name in names_to_test:
  3115. self.files_checked = []
  3116. self.filename = name
  3117. self.unchanged("import jam")
  3118. if os.path.dirname(name):
  3119. name = os.path.dirname(name) + '/jam'
  3120. else:
  3121. name = 'jam'
  3122. expected_checks = set(name + ext for ext in expected_extensions)
  3123. expected_checks.add("__init__.py")
  3124. self.assertEqual(set(self.files_checked), expected_checks)
  3125. def test_not_in_package(self):
  3126. s = "import bar"
  3127. self.always_exists = False
  3128. self.present_files = set(["bar.py"])
  3129. self.unchanged(s)
  3130. def test_with_absolute_import_enabled(self):
  3131. s = "from __future__ import absolute_import\nimport bar"
  3132. self.always_exists = False
  3133. self.present_files = set(["__init__.py", "bar.py"])
  3134. self.unchanged(s)
  3135. def test_in_package(self):
  3136. b = "import bar"
  3137. a = "from . import bar"
  3138. self.always_exists = False
  3139. self.present_files = set(["__init__.py", "bar.py"])
  3140. self.check(b, a)
  3141. def test_import_from_package(self):
  3142. b = "import bar"
  3143. a = "from . import bar"
  3144. self.always_exists = False
  3145. self.present_files = set(["__init__.py", "bar" + os.path.sep])
  3146. self.check(b, a)
  3147. def test_already_relative_import(self):
  3148. s = "from . import bar"
  3149. self.unchanged(s)
  3150. def test_comments_and_indent(self):
  3151. b = "import bar # Foo"
  3152. a = "from . import bar # Foo"
  3153. self.check(b, a)
  3154. def test_from(self):
  3155. b = "from foo import bar, baz"
  3156. a = "from .foo import bar, baz"
  3157. self.check_both(b, a)
  3158. b = "from foo import bar"
  3159. a = "from .foo import bar"
  3160. self.check_both(b, a)
  3161. b = "from foo import (bar, baz)"
  3162. a = "from .foo import (bar, baz)"
  3163. self.check_both(b, a)
  3164. def test_dotted_from(self):
  3165. b = "from green.eggs import ham"
  3166. a = "from .green.eggs import ham"
  3167. self.check_both(b, a)
  3168. def test_from_as(self):
  3169. b = "from green.eggs import ham as spam"
  3170. a = "from .green.eggs import ham as spam"
  3171. self.check_both(b, a)
  3172. def test_import(self):
  3173. b = "import foo"
  3174. a = "from . import foo"
  3175. self.check_both(b, a)
  3176. b = "import foo, bar"
  3177. a = "from . import foo, bar"
  3178. self.check_both(b, a)
  3179. b = "import foo, bar, x"
  3180. a = "from . import foo, bar, x"
  3181. self.check_both(b, a)
  3182. b = "import x, y, z"
  3183. a = "from . import x, y, z"
  3184. self.check_both(b, a)
  3185. def test_import_as(self):
  3186. b = "import foo as x"
  3187. a = "from . import foo as x"
  3188. self.check_both(b, a)
  3189. b = "import a as b, b as c, c as d"
  3190. a = "from . import a as b, b as c, c as d"
  3191. self.check_both(b, a)
  3192. def test_local_and_absolute(self):
  3193. self.always_exists = False
  3194. self.present_files = set(["foo.py", "__init__.py"])
  3195. s = "import foo, bar"
  3196. self.warns_unchanged(s, "absolute and local imports together")
  3197. def test_dotted_import(self):
  3198. b = "import foo.bar"
  3199. a = "from . import foo.bar"
  3200. self.check_both(b, a)
  3201. def test_dotted_import_as(self):
  3202. b = "import foo.bar as bang"
  3203. a = "from . import foo.bar as bang"
  3204. self.check_both(b, a)
  3205. def test_prefix(self):
  3206. b = """
  3207. # prefix
  3208. import foo.bar
  3209. """
  3210. a = """
  3211. # prefix
  3212. from . import foo.bar
  3213. """
  3214. self.check_both(b, a)
  3215. class Test_set_literal(FixerTestCase):
  3216. fixer = "set_literal"
  3217. def test_basic(self):
  3218. b = """set([1, 2, 3])"""
  3219. a = """{1, 2, 3}"""
  3220. self.check(b, a)
  3221. b = """set((1, 2, 3))"""
  3222. a = """{1, 2, 3}"""
  3223. self.check(b, a)
  3224. b = """set((1,))"""
  3225. a = """{1}"""
  3226. self.check(b, a)
  3227. b = """set([1])"""
  3228. self.check(b, a)
  3229. b = """set((a, b))"""
  3230. a = """{a, b}"""
  3231. self.check(b, a)
  3232. b = """set([a, b])"""
  3233. self.check(b, a)
  3234. b = """set((a*234, f(args=23)))"""
  3235. a = """{a*234, f(args=23)}"""
  3236. self.check(b, a)
  3237. b = """set([a*23, f(23)])"""
  3238. a = """{a*23, f(23)}"""
  3239. self.check(b, a)
  3240. b = """set([a-234**23])"""
  3241. a = """{a-234**23}"""
  3242. self.check(b, a)
  3243. def test_listcomps(self):
  3244. b = """set([x for x in y])"""
  3245. a = """{x for x in y}"""
  3246. self.check(b, a)
  3247. b = """set([x for x in y if x == m])"""
  3248. a = """{x for x in y if x == m}"""
  3249. self.check(b, a)
  3250. b = """set([x for x in y for a in b])"""
  3251. a = """{x for x in y for a in b}"""
  3252. self.check(b, a)
  3253. b = """set([f(x) - 23 for x in y])"""
  3254. a = """{f(x) - 23 for x in y}"""
  3255. self.check(b, a)
  3256. def test_whitespace(self):
  3257. b = """set( [1, 2])"""
  3258. a = """{1, 2}"""
  3259. self.check(b, a)
  3260. b = """set([1 , 2])"""
  3261. a = """{1 , 2}"""
  3262. self.check(b, a)
  3263. b = """set([ 1 ])"""
  3264. a = """{ 1 }"""
  3265. self.check(b, a)
  3266. b = """set( [1] )"""
  3267. a = """{1}"""
  3268. self.check(b, a)
  3269. b = """set([ 1, 2 ])"""
  3270. a = """{ 1, 2 }"""
  3271. self.check(b, a)
  3272. b = """set([x for x in y ])"""
  3273. a = """{x for x in y }"""
  3274. self.check(b, a)
  3275. b = """set(
  3276. [1, 2]
  3277. )
  3278. """
  3279. a = """{1, 2}\n"""
  3280. self.check(b, a)
  3281. def test_comments(self):
  3282. b = """set((1, 2)) # Hi"""
  3283. a = """{1, 2} # Hi"""
  3284. self.check(b, a)
  3285. # This isn't optimal behavior, but the fixer is optional.
  3286. b = """
  3287. # Foo
  3288. set( # Bar
  3289. (1, 2)
  3290. )
  3291. """
  3292. a = """
  3293. # Foo
  3294. {1, 2}
  3295. """
  3296. self.check(b, a)
  3297. def test_unchanged(self):
  3298. s = """set()"""
  3299. self.unchanged(s)
  3300. s = """set(a)"""
  3301. self.unchanged(s)
  3302. s = """set(a, b, c)"""
  3303. self.unchanged(s)
  3304. # Don't transform generators because they might have to be lazy.
  3305. s = """set(x for x in y)"""
  3306. self.unchanged(s)
  3307. s = """set(x for x in y if z)"""
  3308. self.unchanged(s)
  3309. s = """set(a*823-23**2 + f(23))"""
  3310. self.unchanged(s)
  3311. class Test_sys_exc(FixerTestCase):
  3312. fixer = "sys_exc"
  3313. def test_0(self):
  3314. b = "sys.exc_type"
  3315. a = "sys.exc_info()[0]"
  3316. self.check(b, a)
  3317. def test_1(self):
  3318. b = "sys.exc_value"
  3319. a = "sys.exc_info()[1]"
  3320. self.check(b, a)
  3321. def test_2(self):
  3322. b = "sys.exc_traceback"
  3323. a = "sys.exc_info()[2]"
  3324. self.check(b, a)
  3325. def test_3(self):
  3326. b = "sys.exc_type # Foo"
  3327. a = "sys.exc_info()[0] # Foo"
  3328. self.check(b, a)
  3329. def test_4(self):
  3330. b = "sys. exc_type"
  3331. a = "sys. exc_info()[0]"
  3332. self.check(b, a)
  3333. def test_5(self):
  3334. b = "sys .exc_type"
  3335. a = "sys .exc_info()[0]"
  3336. self.check(b, a)
  3337. class Test_paren(FixerTestCase):
  3338. fixer = "paren"
  3339. def test_0(self):
  3340. b = """[i for i in 1, 2 ]"""
  3341. a = """[i for i in (1, 2) ]"""
  3342. self.check(b, a)
  3343. def test_1(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_2(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_3(self):
  3352. b = """[i for i in 1, 2 if i]"""
  3353. a = """[i for i in (1, 2) if i]"""
  3354. self.check(b, a)
  3355. def test_4(self):
  3356. b = """[i for i in 1, 2 ]"""
  3357. a = """[i for i in (1, 2) ]"""
  3358. self.check(b, a)
  3359. def test_5(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_6(self):
  3364. b = """(i for i in 1 ,2 if i)"""
  3365. a = """(i for i in (1 ,2) if i)"""
  3366. self.check(b, a)
  3367. def test_unchanged_0(self):
  3368. s = """[i for i in (1, 2)]"""
  3369. self.unchanged(s)
  3370. def test_unchanged_1(self):
  3371. s = """[i for i in foo()]"""
  3372. self.unchanged(s)
  3373. def test_unchanged_2(self):
  3374. s = """[i for i in (1, 2) if nothing]"""
  3375. self.unchanged(s)
  3376. def test_unchanged_3(self):
  3377. s = """(i for i in (1, 2))"""
  3378. self.unchanged(s)
  3379. def test_unchanged_4(self):
  3380. s = """[i for i in m]"""
  3381. self.unchanged(s)
  3382. class Test_metaclass(FixerTestCase):
  3383. fixer = 'metaclass'
  3384. def test_unchanged(self):
  3385. self.unchanged("class X(): pass")
  3386. self.unchanged("class X(object): pass")
  3387. self.unchanged("class X(object1, object2): pass")
  3388. self.unchanged("class X(object1, object2, object3): pass")
  3389. self.unchanged("class X(metaclass=Meta): pass")
  3390. self.unchanged("class X(b, arg=23, metclass=Meta): pass")
  3391. self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
  3392. s = """
  3393. class X:
  3394. def __metaclass__(self): pass
  3395. """
  3396. self.unchanged(s)
  3397. s = """
  3398. class X:
  3399. a[23] = 74
  3400. """
  3401. self.unchanged(s)
  3402. def test_comments(self):
  3403. b = """
  3404. class X:
  3405. # hi
  3406. __metaclass__ = AppleMeta
  3407. """
  3408. a = """
  3409. class X(metaclass=AppleMeta):
  3410. # hi
  3411. pass
  3412. """
  3413. self.check(b, a)
  3414. b = """
  3415. class X:
  3416. __metaclass__ = Meta
  3417. # Bedtime!
  3418. """
  3419. a = """
  3420. class X(metaclass=Meta):
  3421. pass
  3422. # Bedtime!
  3423. """
  3424. self.check(b, a)
  3425. def test_meta(self):
  3426. # no-parent class, odd body
  3427. b = """
  3428. class X():
  3429. __metaclass__ = Q
  3430. pass
  3431. """
  3432. a = """
  3433. class X(metaclass=Q):
  3434. pass
  3435. """
  3436. self.check(b, a)
  3437. # one parent class, no body
  3438. b = """class X(object): __metaclass__ = Q"""
  3439. a = """class X(object, metaclass=Q): pass"""
  3440. self.check(b, a)
  3441. # one parent, simple body
  3442. b = """
  3443. class X(object):
  3444. __metaclass__ = Meta
  3445. bar = 7
  3446. """
  3447. a = """
  3448. class X(object, metaclass=Meta):
  3449. bar = 7
  3450. """
  3451. self.check(b, a)
  3452. b = """
  3453. class X:
  3454. __metaclass__ = Meta; x = 4; g = 23
  3455. """
  3456. a = """
  3457. class X(metaclass=Meta):
  3458. x = 4; g = 23
  3459. """
  3460. self.check(b, a)
  3461. # one parent, simple body, __metaclass__ last
  3462. b = """
  3463. class X(object):
  3464. bar = 7
  3465. __metaclass__ = Meta
  3466. """
  3467. a = """
  3468. class X(object, metaclass=Meta):
  3469. bar = 7
  3470. """
  3471. self.check(b, a)
  3472. # redefining __metaclass__
  3473. b = """
  3474. class X():
  3475. __metaclass__ = A
  3476. __metaclass__ = B
  3477. bar = 7
  3478. """
  3479. a = """
  3480. class X(metaclass=B):
  3481. bar = 7
  3482. """
  3483. self.check(b, a)
  3484. # multiple inheritance, simple body
  3485. b = """
  3486. class X(clsA, clsB):
  3487. __metaclass__ = Meta
  3488. bar = 7
  3489. """
  3490. a = """
  3491. class X(clsA, clsB, metaclass=Meta):
  3492. bar = 7
  3493. """
  3494. self.check(b, a)
  3495. # keywords in the class statement
  3496. b = """class m(a, arg=23): __metaclass__ = Meta"""
  3497. a = """class m(a, arg=23, metaclass=Meta): pass"""
  3498. self.check(b, a)
  3499. b = """
  3500. class X(expression(2 + 4)):
  3501. __metaclass__ = Meta
  3502. """
  3503. a = """
  3504. class X(expression(2 + 4), metaclass=Meta):
  3505. pass
  3506. """
  3507. self.check(b, a)
  3508. b = """
  3509. class X(expression(2 + 4), x**4):
  3510. __metaclass__ = Meta
  3511. """
  3512. a = """
  3513. class X(expression(2 + 4), x**4, metaclass=Meta):
  3514. pass
  3515. """
  3516. self.check(b, a)
  3517. b = """
  3518. class X:
  3519. __metaclass__ = Meta
  3520. save.py = 23
  3521. """
  3522. a = """
  3523. class X(metaclass=Meta):
  3524. save.py = 23
  3525. """
  3526. self.check(b, a)
  3527. class Test_getcwdu(FixerTestCase):
  3528. fixer = 'getcwdu'
  3529. def test_basic(self):
  3530. b = """os.getcwdu"""
  3531. a = """os.getcwd"""
  3532. self.check(b, a)
  3533. b = """os.getcwdu()"""
  3534. a = """os.getcwd()"""
  3535. self.check(b, a)
  3536. b = """meth = os.getcwdu"""
  3537. a = """meth = os.getcwd"""
  3538. self.check(b, a)
  3539. b = """os.getcwdu(args)"""
  3540. a = """os.getcwd(args)"""
  3541. self.check(b, a)
  3542. def test_comment(self):
  3543. b = """os.getcwdu() # Foo"""
  3544. a = """os.getcwd() # Foo"""
  3545. self.check(b, a)
  3546. def test_unchanged(self):
  3547. s = """os.getcwd()"""
  3548. self.unchanged(s)
  3549. s = """getcwdu()"""
  3550. self.unchanged(s)
  3551. s = """os.getcwdb()"""
  3552. self.unchanged(s)
  3553. def test_indentation(self):
  3554. b = """
  3555. if 1:
  3556. os.getcwdu()
  3557. """
  3558. a = """
  3559. if 1:
  3560. os.getcwd()
  3561. """
  3562. self.check(b, a)
  3563. def test_multilation(self):
  3564. b = """os .getcwdu()"""
  3565. a = """os .getcwd()"""
  3566. self.check(b, a)
  3567. b = """os. getcwdu"""
  3568. a = """os. getcwd"""
  3569. self.check(b, a)
  3570. b = """os.getcwdu ( )"""
  3571. a = """os.getcwd ( )"""
  3572. self.check(b, a)
  3573. class Test_operator(FixerTestCase):
  3574. fixer = "operator"
  3575. def test_operator_isCallable(self):
  3576. b = "operator.isCallable(x)"
  3577. a = "callable(x)"
  3578. self.check(b, a)
  3579. def test_operator_sequenceIncludes(self):
  3580. b = "operator.sequenceIncludes(x, y)"
  3581. a = "operator.contains(x, y)"
  3582. self.check(b, a)
  3583. b = "operator .sequenceIncludes(x, y)"
  3584. a = "operator .contains(x, y)"
  3585. self.check(b, a)
  3586. b = "operator. sequenceIncludes(x, y)"
  3587. a = "operator. contains(x, y)"
  3588. self.check(b, a)
  3589. def test_operator_isSequenceType(self):
  3590. b = "operator.isSequenceType(x)"
  3591. a = "import collections.abc\nisinstance(x, collections.abc.Sequence)"
  3592. self.check(b, a)
  3593. def test_operator_isMappingType(self):
  3594. b = "operator.isMappingType(x)"
  3595. a = "import collections.abc\nisinstance(x, collections.abc.Mapping)"
  3596. self.check(b, a)
  3597. def test_operator_isNumberType(self):
  3598. b = "operator.isNumberType(x)"
  3599. a = "import numbers\nisinstance(x, numbers.Number)"
  3600. self.check(b, a)
  3601. def test_operator_repeat(self):
  3602. b = "operator.repeat(x, n)"
  3603. a = "operator.mul(x, n)"
  3604. self.check(b, a)
  3605. b = "operator .repeat(x, n)"
  3606. a = "operator .mul(x, n)"
  3607. self.check(b, a)
  3608. b = "operator. repeat(x, n)"
  3609. a = "operator. mul(x, n)"
  3610. self.check(b, a)
  3611. def test_operator_irepeat(self):
  3612. b = "operator.irepeat(x, n)"
  3613. a = "operator.imul(x, n)"
  3614. self.check(b, a)
  3615. b = "operator .irepeat(x, n)"
  3616. a = "operator .imul(x, n)"
  3617. self.check(b, a)
  3618. b = "operator. irepeat(x, n)"
  3619. a = "operator. imul(x, n)"
  3620. self.check(b, a)
  3621. def test_bare_isCallable(self):
  3622. s = "isCallable(x)"
  3623. t = "You should use 'callable(x)' here."
  3624. self.warns_unchanged(s, t)
  3625. def test_bare_sequenceIncludes(self):
  3626. s = "sequenceIncludes(x, y)"
  3627. t = "You should use 'operator.contains(x, y)' here."
  3628. self.warns_unchanged(s, t)
  3629. def test_bare_operator_isSequenceType(self):
  3630. s = "isSequenceType(z)"
  3631. t = "You should use 'isinstance(z, collections.abc.Sequence)' here."
  3632. self.warns_unchanged(s, t)
  3633. def test_bare_operator_isMappingType(self):
  3634. s = "isMappingType(x)"
  3635. t = "You should use 'isinstance(x, collections.abc.Mapping)' here."
  3636. self.warns_unchanged(s, t)
  3637. def test_bare_operator_isNumberType(self):
  3638. s = "isNumberType(y)"
  3639. t = "You should use 'isinstance(y, numbers.Number)' here."
  3640. self.warns_unchanged(s, t)
  3641. def test_bare_operator_repeat(self):
  3642. s = "repeat(x, n)"
  3643. t = "You should use 'operator.mul(x, n)' here."
  3644. self.warns_unchanged(s, t)
  3645. def test_bare_operator_irepeat(self):
  3646. s = "irepeat(y, 187)"
  3647. t = "You should use 'operator.imul(y, 187)' here."
  3648. self.warns_unchanged(s, t)
  3649. class Test_exitfunc(FixerTestCase):
  3650. fixer = "exitfunc"
  3651. def test_simple(self):
  3652. b = """
  3653. import sys
  3654. sys.exitfunc = my_atexit
  3655. """
  3656. a = """
  3657. import sys
  3658. import atexit
  3659. atexit.register(my_atexit)
  3660. """
  3661. self.check(b, a)
  3662. def test_names_import(self):
  3663. b = """
  3664. import sys, crumbs
  3665. sys.exitfunc = my_func
  3666. """
  3667. a = """
  3668. import sys, crumbs, atexit
  3669. atexit.register(my_func)
  3670. """
  3671. self.check(b, a)
  3672. def test_complex_expression(self):
  3673. b = """
  3674. import sys
  3675. sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
  3676. """
  3677. a = """
  3678. import sys
  3679. import atexit
  3680. atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
  3681. """
  3682. self.check(b, a)
  3683. def test_comments(self):
  3684. b = """
  3685. import sys # Foo
  3686. sys.exitfunc = f # Blah
  3687. """
  3688. a = """
  3689. import sys
  3690. import atexit # Foo
  3691. atexit.register(f) # Blah
  3692. """
  3693. self.check(b, a)
  3694. b = """
  3695. import apples, sys, crumbs, larry # Pleasant comments
  3696. sys.exitfunc = func
  3697. """
  3698. a = """
  3699. import apples, sys, crumbs, larry, atexit # Pleasant comments
  3700. atexit.register(func)
  3701. """
  3702. self.check(b, a)
  3703. def test_in_a_function(self):
  3704. b = """
  3705. import sys
  3706. def f():
  3707. sys.exitfunc = func
  3708. """
  3709. a = """
  3710. import sys
  3711. import atexit
  3712. def f():
  3713. atexit.register(func)
  3714. """
  3715. self.check(b, a)
  3716. def test_no_sys_import(self):
  3717. b = """sys.exitfunc = f"""
  3718. a = """atexit.register(f)"""
  3719. msg = ("Can't find sys import; Please add an atexit import at the "
  3720. "top of your file.")
  3721. self.warns(b, a, msg)
  3722. def test_unchanged(self):
  3723. s = """f(sys.exitfunc)"""
  3724. self.unchanged(s)
  3725. class Test_asserts(FixerTestCase):
  3726. fixer = "asserts"
  3727. def test_deprecated_names(self):
  3728. tests = [
  3729. ('self.assert_(True)', 'self.assertTrue(True)'),
  3730. ('self.assertEquals(2, 2)', 'self.assertEqual(2, 2)'),
  3731. ('self.assertNotEquals(2, 3)', 'self.assertNotEqual(2, 3)'),
  3732. ('self.assertAlmostEquals(2, 3)', 'self.assertAlmostEqual(2, 3)'),
  3733. ('self.assertNotAlmostEquals(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),
  3734. ('self.failUnlessEqual(2, 2)', 'self.assertEqual(2, 2)'),
  3735. ('self.failIfEqual(2, 3)', 'self.assertNotEqual(2, 3)'),
  3736. ('self.failUnlessAlmostEqual(2, 3)', 'self.assertAlmostEqual(2, 3)'),
  3737. ('self.failIfAlmostEqual(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),
  3738. ('self.failUnless(True)', 'self.assertTrue(True)'),
  3739. ('self.failUnlessRaises(foo)', 'self.assertRaises(foo)'),
  3740. ('self.failIf(False)', 'self.assertFalse(False)'),
  3741. ]
  3742. for b, a in tests:
  3743. self.check(b, a)
  3744. def test_variants(self):
  3745. b = 'eq = self.assertEquals'
  3746. a = 'eq = self.assertEqual'
  3747. self.check(b, a)
  3748. b = 'self.assertEquals(2, 3, msg="fail")'
  3749. a = 'self.assertEqual(2, 3, msg="fail")'
  3750. self.check(b, a)
  3751. b = 'self.assertEquals(2, 3, msg="fail") # foo'
  3752. a = 'self.assertEqual(2, 3, msg="fail") # foo'
  3753. self.check(b, a)
  3754. b = 'self.assertEquals (2, 3)'
  3755. a = 'self.assertEqual (2, 3)'
  3756. self.check(b, a)
  3757. b = ' self.assertEquals (2, 3)'
  3758. a = ' self.assertEqual (2, 3)'
  3759. self.check(b, a)
  3760. b = 'with self.failUnlessRaises(Explosion): explode()'
  3761. a = 'with self.assertRaises(Explosion): explode()'
  3762. self.check(b, a)
  3763. b = 'with self.failUnlessRaises(Explosion) as cm: explode()'
  3764. a = 'with self.assertRaises(Explosion) as cm: explode()'
  3765. self.check(b, a)
  3766. def test_unchanged(self):
  3767. self.unchanged('self.assertEqualsOnSaturday')
  3768. self.unchanged('self.assertEqualsOnSaturday(3, 5)')