test_other.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046
  1. """
  2. Tests for various Pyflakes behavior.
  3. """
  4. from sys import version_info
  5. from pyflakes import messages as m
  6. from pyflakes.test.harness import TestCase, skip, skipIf
  7. class Test(TestCase):
  8. def test_duplicateArgs(self):
  9. self.flakes('def fu(bar, bar): pass', m.DuplicateArgument)
  10. def test_localReferencedBeforeAssignment(self):
  11. self.flakes('''
  12. a = 1
  13. def f():
  14. a; a=1
  15. f()
  16. ''', m.UndefinedLocal, m.UnusedVariable)
  17. def test_redefinedInGenerator(self):
  18. """
  19. Test that reusing a variable in a generator does not raise
  20. a warning.
  21. """
  22. self.flakes('''
  23. a = 1
  24. (1 for a, b in [(1, 2)])
  25. ''')
  26. self.flakes('''
  27. class A:
  28. a = 1
  29. list(1 for a, b in [(1, 2)])
  30. ''')
  31. self.flakes('''
  32. def f():
  33. a = 1
  34. (1 for a, b in [(1, 2)])
  35. ''', m.UnusedVariable)
  36. self.flakes('''
  37. (1 for a, b in [(1, 2)])
  38. (1 for a, b in [(1, 2)])
  39. ''')
  40. self.flakes('''
  41. for a, b in [(1, 2)]:
  42. pass
  43. (1 for a, b in [(1, 2)])
  44. ''')
  45. def test_redefinedInSetComprehension(self):
  46. """
  47. Test that reusing a variable in a set comprehension does not raise
  48. a warning.
  49. """
  50. self.flakes('''
  51. a = 1
  52. {1 for a, b in [(1, 2)]}
  53. ''')
  54. self.flakes('''
  55. class A:
  56. a = 1
  57. {1 for a, b in [(1, 2)]}
  58. ''')
  59. self.flakes('''
  60. def f():
  61. a = 1
  62. {1 for a, b in [(1, 2)]}
  63. ''', m.UnusedVariable)
  64. self.flakes('''
  65. {1 for a, b in [(1, 2)]}
  66. {1 for a, b in [(1, 2)]}
  67. ''')
  68. self.flakes('''
  69. for a, b in [(1, 2)]:
  70. pass
  71. {1 for a, b in [(1, 2)]}
  72. ''')
  73. def test_redefinedInDictComprehension(self):
  74. """
  75. Test that reusing a variable in a dict comprehension does not raise
  76. a warning.
  77. """
  78. self.flakes('''
  79. a = 1
  80. {1: 42 for a, b in [(1, 2)]}
  81. ''')
  82. self.flakes('''
  83. class A:
  84. a = 1
  85. {1: 42 for a, b in [(1, 2)]}
  86. ''')
  87. self.flakes('''
  88. def f():
  89. a = 1
  90. {1: 42 for a, b in [(1, 2)]}
  91. ''', m.UnusedVariable)
  92. self.flakes('''
  93. {1: 42 for a, b in [(1, 2)]}
  94. {1: 42 for a, b in [(1, 2)]}
  95. ''')
  96. self.flakes('''
  97. for a, b in [(1, 2)]:
  98. pass
  99. {1: 42 for a, b in [(1, 2)]}
  100. ''')
  101. def test_redefinedFunction(self):
  102. """
  103. Test that shadowing a function definition with another one raises a
  104. warning.
  105. """
  106. self.flakes('''
  107. def a(): pass
  108. def a(): pass
  109. ''', m.RedefinedWhileUnused)
  110. def test_redefined_function_shadows_variable(self):
  111. self.flakes('''
  112. x = 1
  113. def x(): pass
  114. ''', m.RedefinedWhileUnused)
  115. def test_redefinedUnderscoreFunction(self):
  116. """
  117. Test that shadowing a function definition named with underscore doesn't
  118. raise anything.
  119. """
  120. self.flakes('''
  121. def _(): pass
  122. def _(): pass
  123. ''')
  124. def test_redefinedUnderscoreImportation(self):
  125. """
  126. Test that shadowing an underscore importation raises a warning.
  127. """
  128. self.flakes('''
  129. from .i18n import _
  130. def _(): pass
  131. ''', m.RedefinedWhileUnused)
  132. def test_redefinedClassFunction(self):
  133. """
  134. Test that shadowing a function definition in a class suite with another
  135. one raises a warning.
  136. """
  137. self.flakes('''
  138. class A:
  139. def a(): pass
  140. def a(): pass
  141. ''', m.RedefinedWhileUnused)
  142. def test_redefinedIfElseFunction(self):
  143. """
  144. Test that shadowing a function definition twice in an if
  145. and else block does not raise a warning.
  146. """
  147. self.flakes('''
  148. if True:
  149. def a(): pass
  150. else:
  151. def a(): pass
  152. ''')
  153. def test_redefinedIfFunction(self):
  154. """
  155. Test that shadowing a function definition within an if block
  156. raises a warning.
  157. """
  158. self.flakes('''
  159. if True:
  160. def a(): pass
  161. def a(): pass
  162. ''', m.RedefinedWhileUnused)
  163. def test_redefinedTryExceptFunction(self):
  164. """
  165. Test that shadowing a function definition twice in try
  166. and except block does not raise a warning.
  167. """
  168. self.flakes('''
  169. try:
  170. def a(): pass
  171. except:
  172. def a(): pass
  173. ''')
  174. def test_redefinedTryFunction(self):
  175. """
  176. Test that shadowing a function definition within a try block
  177. raises a warning.
  178. """
  179. self.flakes('''
  180. try:
  181. def a(): pass
  182. def a(): pass
  183. except:
  184. pass
  185. ''', m.RedefinedWhileUnused)
  186. def test_redefinedIfElseInListComp(self):
  187. """
  188. Test that shadowing a variable in a list comprehension in
  189. an if and else block does not raise a warning.
  190. """
  191. self.flakes('''
  192. if False:
  193. a = 1
  194. else:
  195. [a for a in '12']
  196. ''')
  197. def test_functionDecorator(self):
  198. """
  199. Test that shadowing a function definition with a decorated version of
  200. that function does not raise a warning.
  201. """
  202. self.flakes('''
  203. from somewhere import somedecorator
  204. def a(): pass
  205. a = somedecorator(a)
  206. ''')
  207. def test_classFunctionDecorator(self):
  208. """
  209. Test that shadowing a function definition in a class suite with a
  210. decorated version of that function does not raise a warning.
  211. """
  212. self.flakes('''
  213. class A:
  214. def a(): pass
  215. a = classmethod(a)
  216. ''')
  217. def test_modernProperty(self):
  218. self.flakes("""
  219. class A:
  220. @property
  221. def t(self):
  222. pass
  223. @t.setter
  224. def t(self, value):
  225. pass
  226. @t.deleter
  227. def t(self):
  228. pass
  229. """)
  230. def test_unaryPlus(self):
  231. """Don't die on unary +."""
  232. self.flakes('+1')
  233. def test_undefinedBaseClass(self):
  234. """
  235. If a name in the base list of a class definition is undefined, a
  236. warning is emitted.
  237. """
  238. self.flakes('''
  239. class foo(foo):
  240. pass
  241. ''', m.UndefinedName)
  242. def test_classNameUndefinedInClassBody(self):
  243. """
  244. If a class name is used in the body of that class's definition and
  245. the name is not already defined, a warning is emitted.
  246. """
  247. self.flakes('''
  248. class foo:
  249. foo
  250. ''', m.UndefinedName)
  251. def test_classNameDefinedPreviously(self):
  252. """
  253. If a class name is used in the body of that class's definition and
  254. the name was previously defined in some other way, no warning is
  255. emitted.
  256. """
  257. self.flakes('''
  258. foo = None
  259. class foo:
  260. foo
  261. ''')
  262. def test_classRedefinition(self):
  263. """
  264. If a class is defined twice in the same module, a warning is emitted.
  265. """
  266. self.flakes('''
  267. class Foo:
  268. pass
  269. class Foo:
  270. pass
  271. ''', m.RedefinedWhileUnused)
  272. def test_functionRedefinedAsClass(self):
  273. """
  274. If a function is redefined as a class, a warning is emitted.
  275. """
  276. self.flakes('''
  277. def Foo():
  278. pass
  279. class Foo:
  280. pass
  281. ''', m.RedefinedWhileUnused)
  282. def test_classRedefinedAsFunction(self):
  283. """
  284. If a class is redefined as a function, a warning is emitted.
  285. """
  286. self.flakes('''
  287. class Foo:
  288. pass
  289. def Foo():
  290. pass
  291. ''', m.RedefinedWhileUnused)
  292. def test_classWithReturn(self):
  293. """
  294. If a return is used inside a class, a warning is emitted.
  295. """
  296. self.flakes('''
  297. class Foo(object):
  298. return
  299. ''', m.ReturnOutsideFunction)
  300. def test_moduleWithReturn(self):
  301. """
  302. If a return is used at the module level, a warning is emitted.
  303. """
  304. self.flakes('''
  305. return
  306. ''', m.ReturnOutsideFunction)
  307. def test_classWithYield(self):
  308. """
  309. If a yield is used inside a class, a warning is emitted.
  310. """
  311. self.flakes('''
  312. class Foo(object):
  313. yield
  314. ''', m.YieldOutsideFunction)
  315. def test_moduleWithYield(self):
  316. """
  317. If a yield is used at the module level, a warning is emitted.
  318. """
  319. self.flakes('''
  320. yield
  321. ''', m.YieldOutsideFunction)
  322. def test_classWithYieldFrom(self):
  323. """
  324. If a yield from is used inside a class, a warning is emitted.
  325. """
  326. self.flakes('''
  327. class Foo(object):
  328. yield from range(10)
  329. ''', m.YieldOutsideFunction)
  330. def test_moduleWithYieldFrom(self):
  331. """
  332. If a yield from is used at the module level, a warning is emitted.
  333. """
  334. self.flakes('''
  335. yield from range(10)
  336. ''', m.YieldOutsideFunction)
  337. def test_continueOutsideLoop(self):
  338. self.flakes('''
  339. continue
  340. ''', m.ContinueOutsideLoop)
  341. self.flakes('''
  342. def f():
  343. continue
  344. ''', m.ContinueOutsideLoop)
  345. self.flakes('''
  346. while True:
  347. pass
  348. else:
  349. continue
  350. ''', m.ContinueOutsideLoop)
  351. self.flakes('''
  352. while True:
  353. pass
  354. else:
  355. if 1:
  356. if 2:
  357. continue
  358. ''', m.ContinueOutsideLoop)
  359. self.flakes('''
  360. while True:
  361. def f():
  362. continue
  363. ''', m.ContinueOutsideLoop)
  364. self.flakes('''
  365. while True:
  366. class A:
  367. continue
  368. ''', m.ContinueOutsideLoop)
  369. def test_continueInsideLoop(self):
  370. self.flakes('''
  371. while True:
  372. continue
  373. ''')
  374. self.flakes('''
  375. for i in range(10):
  376. continue
  377. ''')
  378. self.flakes('''
  379. while True:
  380. if 1:
  381. continue
  382. ''')
  383. self.flakes('''
  384. for i in range(10):
  385. if 1:
  386. continue
  387. ''')
  388. self.flakes('''
  389. while True:
  390. while True:
  391. pass
  392. else:
  393. continue
  394. else:
  395. pass
  396. ''')
  397. self.flakes('''
  398. while True:
  399. try:
  400. pass
  401. finally:
  402. while True:
  403. continue
  404. ''')
  405. def test_breakOutsideLoop(self):
  406. self.flakes('''
  407. break
  408. ''', m.BreakOutsideLoop)
  409. self.flakes('''
  410. def f():
  411. break
  412. ''', m.BreakOutsideLoop)
  413. self.flakes('''
  414. while True:
  415. pass
  416. else:
  417. break
  418. ''', m.BreakOutsideLoop)
  419. self.flakes('''
  420. while True:
  421. pass
  422. else:
  423. if 1:
  424. if 2:
  425. break
  426. ''', m.BreakOutsideLoop)
  427. self.flakes('''
  428. while True:
  429. def f():
  430. break
  431. ''', m.BreakOutsideLoop)
  432. self.flakes('''
  433. while True:
  434. class A:
  435. break
  436. ''', m.BreakOutsideLoop)
  437. self.flakes('''
  438. try:
  439. pass
  440. finally:
  441. break
  442. ''', m.BreakOutsideLoop)
  443. def test_breakInsideLoop(self):
  444. self.flakes('''
  445. while True:
  446. break
  447. ''')
  448. self.flakes('''
  449. for i in range(10):
  450. break
  451. ''')
  452. self.flakes('''
  453. while True:
  454. if 1:
  455. break
  456. ''')
  457. self.flakes('''
  458. for i in range(10):
  459. if 1:
  460. break
  461. ''')
  462. self.flakes('''
  463. while True:
  464. while True:
  465. pass
  466. else:
  467. break
  468. else:
  469. pass
  470. ''')
  471. self.flakes('''
  472. while True:
  473. try:
  474. pass
  475. finally:
  476. while True:
  477. break
  478. ''')
  479. self.flakes('''
  480. while True:
  481. try:
  482. pass
  483. finally:
  484. break
  485. ''')
  486. self.flakes('''
  487. while True:
  488. try:
  489. pass
  490. finally:
  491. if 1:
  492. if 2:
  493. break
  494. ''')
  495. def test_defaultExceptLast(self):
  496. """
  497. A default except block should be last.
  498. YES:
  499. try:
  500. ...
  501. except Exception:
  502. ...
  503. except:
  504. ...
  505. NO:
  506. try:
  507. ...
  508. except:
  509. ...
  510. except Exception:
  511. ...
  512. """
  513. self.flakes('''
  514. try:
  515. pass
  516. except ValueError:
  517. pass
  518. ''')
  519. self.flakes('''
  520. try:
  521. pass
  522. except ValueError:
  523. pass
  524. except:
  525. pass
  526. ''')
  527. self.flakes('''
  528. try:
  529. pass
  530. except:
  531. pass
  532. ''')
  533. self.flakes('''
  534. try:
  535. pass
  536. except ValueError:
  537. pass
  538. else:
  539. pass
  540. ''')
  541. self.flakes('''
  542. try:
  543. pass
  544. except:
  545. pass
  546. else:
  547. pass
  548. ''')
  549. self.flakes('''
  550. try:
  551. pass
  552. except ValueError:
  553. pass
  554. except:
  555. pass
  556. else:
  557. pass
  558. ''')
  559. def test_defaultExceptNotLast(self):
  560. self.flakes('''
  561. try:
  562. pass
  563. except:
  564. pass
  565. except ValueError:
  566. pass
  567. ''', m.DefaultExceptNotLast)
  568. self.flakes('''
  569. try:
  570. pass
  571. except:
  572. pass
  573. except:
  574. pass
  575. ''', m.DefaultExceptNotLast)
  576. self.flakes('''
  577. try:
  578. pass
  579. except:
  580. pass
  581. except ValueError:
  582. pass
  583. except:
  584. pass
  585. ''', m.DefaultExceptNotLast)
  586. self.flakes('''
  587. try:
  588. pass
  589. except:
  590. pass
  591. except ValueError:
  592. pass
  593. except:
  594. pass
  595. except ValueError:
  596. pass
  597. ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast)
  598. self.flakes('''
  599. try:
  600. pass
  601. except:
  602. pass
  603. except ValueError:
  604. pass
  605. else:
  606. pass
  607. ''', m.DefaultExceptNotLast)
  608. self.flakes('''
  609. try:
  610. pass
  611. except:
  612. pass
  613. except:
  614. pass
  615. else:
  616. pass
  617. ''', m.DefaultExceptNotLast)
  618. self.flakes('''
  619. try:
  620. pass
  621. except:
  622. pass
  623. except ValueError:
  624. pass
  625. except:
  626. pass
  627. else:
  628. pass
  629. ''', m.DefaultExceptNotLast)
  630. self.flakes('''
  631. try:
  632. pass
  633. except:
  634. pass
  635. except ValueError:
  636. pass
  637. except:
  638. pass
  639. except ValueError:
  640. pass
  641. else:
  642. pass
  643. ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast)
  644. self.flakes('''
  645. try:
  646. pass
  647. except:
  648. pass
  649. except ValueError:
  650. pass
  651. finally:
  652. pass
  653. ''', m.DefaultExceptNotLast)
  654. self.flakes('''
  655. try:
  656. pass
  657. except:
  658. pass
  659. except:
  660. pass
  661. finally:
  662. pass
  663. ''', m.DefaultExceptNotLast)
  664. self.flakes('''
  665. try:
  666. pass
  667. except:
  668. pass
  669. except ValueError:
  670. pass
  671. except:
  672. pass
  673. finally:
  674. pass
  675. ''', m.DefaultExceptNotLast)
  676. self.flakes('''
  677. try:
  678. pass
  679. except:
  680. pass
  681. except ValueError:
  682. pass
  683. except:
  684. pass
  685. except ValueError:
  686. pass
  687. finally:
  688. pass
  689. ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast)
  690. self.flakes('''
  691. try:
  692. pass
  693. except:
  694. pass
  695. except ValueError:
  696. pass
  697. else:
  698. pass
  699. finally:
  700. pass
  701. ''', m.DefaultExceptNotLast)
  702. self.flakes('''
  703. try:
  704. pass
  705. except:
  706. pass
  707. except:
  708. pass
  709. else:
  710. pass
  711. finally:
  712. pass
  713. ''', m.DefaultExceptNotLast)
  714. self.flakes('''
  715. try:
  716. pass
  717. except:
  718. pass
  719. except ValueError:
  720. pass
  721. except:
  722. pass
  723. else:
  724. pass
  725. finally:
  726. pass
  727. ''', m.DefaultExceptNotLast)
  728. self.flakes('''
  729. try:
  730. pass
  731. except:
  732. pass
  733. except ValueError:
  734. pass
  735. except:
  736. pass
  737. except ValueError:
  738. pass
  739. else:
  740. pass
  741. finally:
  742. pass
  743. ''', m.DefaultExceptNotLast, m.DefaultExceptNotLast)
  744. def test_starredAssignmentNoError(self):
  745. """
  746. Python 3 extended iterable unpacking
  747. """
  748. self.flakes('''
  749. a, *b = range(10)
  750. ''')
  751. self.flakes('''
  752. *a, b = range(10)
  753. ''')
  754. self.flakes('''
  755. a, *b, c = range(10)
  756. ''')
  757. self.flakes('''
  758. (a, *b) = range(10)
  759. ''')
  760. self.flakes('''
  761. (*a, b) = range(10)
  762. ''')
  763. self.flakes('''
  764. (a, *b, c) = range(10)
  765. ''')
  766. self.flakes('''
  767. [a, *b] = range(10)
  768. ''')
  769. self.flakes('''
  770. [*a, b] = range(10)
  771. ''')
  772. self.flakes('''
  773. [a, *b, c] = range(10)
  774. ''')
  775. # Taken from test_unpack_ex.py in the cPython source
  776. s = ", ".join("a%d" % i for i in range(1 << 8 - 1)) + \
  777. ", *rest = range(1<<8)"
  778. self.flakes(s)
  779. s = "(" + ", ".join("a%d" % i for i in range(1 << 8 - 1)) + \
  780. ", *rest) = range(1<<8)"
  781. self.flakes(s)
  782. s = "[" + ", ".join("a%d" % i for i in range(1 << 8 - 1)) + \
  783. ", *rest] = range(1<<8)"
  784. self.flakes(s)
  785. def test_starredAssignmentErrors(self):
  786. """
  787. SyntaxErrors (not encoded in the ast) surrounding Python 3 extended
  788. iterable unpacking
  789. """
  790. # Taken from test_unpack_ex.py in the cPython source
  791. s = ", ".join("a%d" % i for i in range(1 << 8)) + \
  792. ", *rest = range(1<<8 + 1)"
  793. self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  794. s = "(" + ", ".join("a%d" % i for i in range(1 << 8)) + \
  795. ", *rest) = range(1<<8 + 1)"
  796. self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  797. s = "[" + ", ".join("a%d" % i for i in range(1 << 8)) + \
  798. ", *rest] = range(1<<8 + 1)"
  799. self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  800. s = ", ".join("a%d" % i for i in range(1 << 8 + 1)) + \
  801. ", *rest = range(1<<8 + 2)"
  802. self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  803. s = "(" + ", ".join("a%d" % i for i in range(1 << 8 + 1)) + \
  804. ", *rest) = range(1<<8 + 2)"
  805. self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  806. s = "[" + ", ".join("a%d" % i for i in range(1 << 8 + 1)) + \
  807. ", *rest] = range(1<<8 + 2)"
  808. self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  809. # No way we can actually test this!
  810. # s = "*rest, " + ", ".join("a%d" % i for i in range(1<<24)) + \
  811. # ", *rest = range(1<<24 + 1)"
  812. # self.flakes(s, m.TooManyExpressionsInStarredAssignment)
  813. self.flakes('''
  814. a, *b, *c = range(10)
  815. ''', m.TwoStarredExpressions)
  816. self.flakes('''
  817. a, *b, c, *d = range(10)
  818. ''', m.TwoStarredExpressions)
  819. self.flakes('''
  820. *a, *b, *c = range(10)
  821. ''', m.TwoStarredExpressions)
  822. self.flakes('''
  823. (a, *b, *c) = range(10)
  824. ''', m.TwoStarredExpressions)
  825. self.flakes('''
  826. (a, *b, c, *d) = range(10)
  827. ''', m.TwoStarredExpressions)
  828. self.flakes('''
  829. (*a, *b, *c) = range(10)
  830. ''', m.TwoStarredExpressions)
  831. self.flakes('''
  832. [a, *b, *c] = range(10)
  833. ''', m.TwoStarredExpressions)
  834. self.flakes('''
  835. [a, *b, c, *d] = range(10)
  836. ''', m.TwoStarredExpressions)
  837. self.flakes('''
  838. [*a, *b, *c] = range(10)
  839. ''', m.TwoStarredExpressions)
  840. @skip("todo: Too hard to make this warn but other cases stay silent")
  841. def test_doubleAssignment(self):
  842. """
  843. If a variable is re-assigned to without being used, no warning is
  844. emitted.
  845. """
  846. self.flakes('''
  847. x = 10
  848. x = 20
  849. ''', m.RedefinedWhileUnused)
  850. def test_doubleAssignmentConditionally(self):
  851. """
  852. If a variable is re-assigned within a conditional, no warning is
  853. emitted.
  854. """
  855. self.flakes('''
  856. x = 10
  857. if True:
  858. x = 20
  859. ''')
  860. def test_doubleAssignmentWithUse(self):
  861. """
  862. If a variable is re-assigned to after being used, no warning is
  863. emitted.
  864. """
  865. self.flakes('''
  866. x = 10
  867. y = x * 2
  868. x = 20
  869. ''')
  870. def test_comparison(self):
  871. """
  872. If a defined name is used on either side of any of the six comparison
  873. operators, no warning is emitted.
  874. """
  875. self.flakes('''
  876. x = 10
  877. y = 20
  878. x < y
  879. x <= y
  880. x == y
  881. x != y
  882. x >= y
  883. x > y
  884. ''')
  885. def test_identity(self):
  886. """
  887. If a defined name is used on either side of an identity test, no
  888. warning is emitted.
  889. """
  890. self.flakes('''
  891. x = 10
  892. y = 20
  893. x is y
  894. x is not y
  895. ''')
  896. def test_containment(self):
  897. """
  898. If a defined name is used on either side of a containment test, no
  899. warning is emitted.
  900. """
  901. self.flakes('''
  902. x = 10
  903. y = 20
  904. x in y
  905. x not in y
  906. ''')
  907. def test_loopControl(self):
  908. """
  909. break and continue statements are supported.
  910. """
  911. self.flakes('''
  912. for x in [1, 2]:
  913. break
  914. ''')
  915. self.flakes('''
  916. for x in [1, 2]:
  917. continue
  918. ''')
  919. def test_ellipsis(self):
  920. """
  921. Ellipsis in a slice is supported.
  922. """
  923. self.flakes('''
  924. [1, 2][...]
  925. ''')
  926. def test_extendedSlice(self):
  927. """
  928. Extended slices are supported.
  929. """
  930. self.flakes('''
  931. x = 3
  932. [1, 2][x,:]
  933. ''')
  934. def test_varAugmentedAssignment(self):
  935. """
  936. Augmented assignment of a variable is supported.
  937. We don't care about var refs.
  938. """
  939. self.flakes('''
  940. foo = 0
  941. foo += 1
  942. ''')
  943. def test_attrAugmentedAssignment(self):
  944. """
  945. Augmented assignment of attributes is supported.
  946. We don't care about attr refs.
  947. """
  948. self.flakes('''
  949. foo = None
  950. foo.bar += foo.baz
  951. ''')
  952. def test_globalDeclaredInDifferentScope(self):
  953. """
  954. A 'global' can be declared in one scope and reused in another.
  955. """
  956. self.flakes('''
  957. def f(): global foo
  958. def g(): foo = 'anything'; foo.is_used()
  959. ''')
  960. def test_function_arguments(self):
  961. """
  962. Test to traverse ARG and ARGUMENT handler
  963. """
  964. self.flakes('''
  965. def foo(a, b):
  966. pass
  967. ''')
  968. self.flakes('''
  969. def foo(a, b, c=0):
  970. pass
  971. ''')
  972. self.flakes('''
  973. def foo(a, b, c=0, *args):
  974. pass
  975. ''')
  976. self.flakes('''
  977. def foo(a, b, c=0, *args, **kwargs):
  978. pass
  979. ''')
  980. def test_function_arguments_python3(self):
  981. self.flakes('''
  982. def foo(a, b, c=0, *args, d=0, **kwargs):
  983. pass
  984. ''')
  985. class TestUnusedAssignment(TestCase):
  986. """
  987. Tests for warning about unused assignments.
  988. """
  989. def test_unusedVariable(self):
  990. """
  991. Warn when a variable in a function is assigned a value that's never
  992. used.
  993. """
  994. self.flakes('''
  995. def a():
  996. b = 1
  997. ''', m.UnusedVariable)
  998. def test_unusedUnderscoreVariable(self):
  999. """
  1000. Don't warn when the magic "_" (underscore) variable is unused.
  1001. See issue #202.
  1002. """
  1003. self.flakes('''
  1004. def a(unused_param):
  1005. _ = unused_param
  1006. ''')
  1007. def test_unusedVariableAsLocals(self):
  1008. """
  1009. Using locals() it is perfectly valid to have unused variables
  1010. """
  1011. self.flakes('''
  1012. def a():
  1013. b = 1
  1014. return locals()
  1015. ''')
  1016. def test_unusedVariableNoLocals(self):
  1017. """
  1018. Using locals() in wrong scope should not matter
  1019. """
  1020. self.flakes('''
  1021. def a():
  1022. locals()
  1023. def a():
  1024. b = 1
  1025. return
  1026. ''', m.UnusedVariable)
  1027. @skip("todo: Difficult because it doesn't apply in the context of a loop")
  1028. def test_unusedReassignedVariable(self):
  1029. """
  1030. Shadowing a used variable can still raise an UnusedVariable warning.
  1031. """
  1032. self.flakes('''
  1033. def a():
  1034. b = 1
  1035. b.foo()
  1036. b = 2
  1037. ''', m.UnusedVariable)
  1038. def test_variableUsedInLoop(self):
  1039. """
  1040. Shadowing a used variable cannot raise an UnusedVariable warning in the
  1041. context of a loop.
  1042. """
  1043. self.flakes('''
  1044. def a():
  1045. b = True
  1046. while b:
  1047. b = False
  1048. ''')
  1049. def test_assignToGlobal(self):
  1050. """
  1051. Assigning to a global and then not using that global is perfectly
  1052. acceptable. Do not mistake it for an unused local variable.
  1053. """
  1054. self.flakes('''
  1055. b = 0
  1056. def a():
  1057. global b
  1058. b = 1
  1059. ''')
  1060. def test_assignToNonlocal(self):
  1061. """
  1062. Assigning to a nonlocal and then not using that binding is perfectly
  1063. acceptable. Do not mistake it for an unused local variable.
  1064. """
  1065. self.flakes('''
  1066. b = b'0'
  1067. def a():
  1068. nonlocal b
  1069. b = b'1'
  1070. ''')
  1071. def test_assignToMember(self):
  1072. """
  1073. Assigning to a member of another object and then not using that member
  1074. variable is perfectly acceptable. Do not mistake it for an unused
  1075. local variable.
  1076. """
  1077. # XXX: Adding this test didn't generate a failure. Maybe not
  1078. # necessary?
  1079. self.flakes('''
  1080. class b:
  1081. pass
  1082. def a():
  1083. b.foo = 1
  1084. ''')
  1085. def test_assignInForLoop(self):
  1086. """
  1087. Don't warn when a variable in a for loop is assigned to but not used.
  1088. """
  1089. self.flakes('''
  1090. def f():
  1091. for i in range(10):
  1092. pass
  1093. ''')
  1094. def test_assignInListComprehension(self):
  1095. """
  1096. Don't warn when a variable in a list comprehension is
  1097. assigned to but not used.
  1098. """
  1099. self.flakes('''
  1100. def f():
  1101. [None for i in range(10)]
  1102. ''')
  1103. def test_generatorExpression(self):
  1104. """
  1105. Don't warn when a variable in a generator expression is
  1106. assigned to but not used.
  1107. """
  1108. self.flakes('''
  1109. def f():
  1110. (None for i in range(10))
  1111. ''')
  1112. def test_assignmentInsideLoop(self):
  1113. """
  1114. Don't warn when a variable assignment occurs lexically after its use.
  1115. """
  1116. self.flakes('''
  1117. def f():
  1118. x = None
  1119. for i in range(10):
  1120. if i > 2:
  1121. return x
  1122. x = i * 2
  1123. ''')
  1124. def test_tupleUnpacking(self):
  1125. """
  1126. Don't warn when a variable included in tuple unpacking is unused. It's
  1127. very common for variables in a tuple unpacking assignment to be unused
  1128. in good Python code, so warning will only create false positives.
  1129. """
  1130. self.flakes('''
  1131. def f(tup):
  1132. (x, y) = tup
  1133. ''')
  1134. self.flakes('''
  1135. def f():
  1136. (x, y) = 1, 2
  1137. ''', m.UnusedVariable, m.UnusedVariable)
  1138. self.flakes('''
  1139. def f():
  1140. (x, y) = coords = 1, 2
  1141. if x > 1:
  1142. print(coords)
  1143. ''')
  1144. self.flakes('''
  1145. def f():
  1146. (x, y) = coords = 1, 2
  1147. ''', m.UnusedVariable)
  1148. self.flakes('''
  1149. def f():
  1150. coords = (x, y) = 1, 2
  1151. ''', m.UnusedVariable)
  1152. def test_listUnpacking(self):
  1153. """
  1154. Don't warn when a variable included in list unpacking is unused.
  1155. """
  1156. self.flakes('''
  1157. def f(tup):
  1158. [x, y] = tup
  1159. ''')
  1160. self.flakes('''
  1161. def f():
  1162. [x, y] = [1, 2]
  1163. ''', m.UnusedVariable, m.UnusedVariable)
  1164. def test_closedOver(self):
  1165. """
  1166. Don't warn when the assignment is used in an inner function.
  1167. """
  1168. self.flakes('''
  1169. def barMaker():
  1170. foo = 5
  1171. def bar():
  1172. return foo
  1173. return bar
  1174. ''')
  1175. def test_doubleClosedOver(self):
  1176. """
  1177. Don't warn when the assignment is used in an inner function, even if
  1178. that inner function itself is in an inner function.
  1179. """
  1180. self.flakes('''
  1181. def barMaker():
  1182. foo = 5
  1183. def bar():
  1184. def baz():
  1185. return foo
  1186. return bar
  1187. ''')
  1188. def test_tracebackhideSpecialVariable(self):
  1189. """
  1190. Do not warn about unused local variable __tracebackhide__, which is
  1191. a special variable for py.test.
  1192. """
  1193. self.flakes("""
  1194. def helper():
  1195. __tracebackhide__ = True
  1196. """)
  1197. def test_ifexp(self):
  1198. """
  1199. Test C{foo if bar else baz} statements.
  1200. """
  1201. self.flakes("a = 'moo' if True else 'oink'")
  1202. self.flakes("a = foo if True else 'oink'", m.UndefinedName)
  1203. self.flakes("a = 'moo' if True else bar", m.UndefinedName)
  1204. def test_if_tuple(self):
  1205. """
  1206. Test C{if (foo,)} conditions.
  1207. """
  1208. self.flakes("""if (): pass""")
  1209. self.flakes("""
  1210. if (
  1211. True
  1212. ):
  1213. pass
  1214. """)
  1215. self.flakes("""
  1216. if (
  1217. True,
  1218. ):
  1219. pass
  1220. """, m.IfTuple)
  1221. self.flakes("""
  1222. x = 1 if (
  1223. True,
  1224. ) else 2
  1225. """, m.IfTuple)
  1226. def test_withStatementNoNames(self):
  1227. """
  1228. No warnings are emitted for using inside or after a nameless C{with}
  1229. statement a name defined beforehand.
  1230. """
  1231. self.flakes('''
  1232. bar = None
  1233. with open("foo"):
  1234. bar
  1235. bar
  1236. ''')
  1237. def test_withStatementSingleName(self):
  1238. """
  1239. No warnings are emitted for using a name defined by a C{with} statement
  1240. within the suite or afterwards.
  1241. """
  1242. self.flakes('''
  1243. with open('foo') as bar:
  1244. bar
  1245. bar
  1246. ''')
  1247. def test_withStatementAttributeName(self):
  1248. """
  1249. No warnings are emitted for using an attribute as the target of a
  1250. C{with} statement.
  1251. """
  1252. self.flakes('''
  1253. import foo
  1254. with open('foo') as foo.bar:
  1255. pass
  1256. ''')
  1257. def test_withStatementSubscript(self):
  1258. """
  1259. No warnings are emitted for using a subscript as the target of a
  1260. C{with} statement.
  1261. """
  1262. self.flakes('''
  1263. import foo
  1264. with open('foo') as foo[0]:
  1265. pass
  1266. ''')
  1267. def test_withStatementSubscriptUndefined(self):
  1268. """
  1269. An undefined name warning is emitted if the subscript used as the
  1270. target of a C{with} statement is not defined.
  1271. """
  1272. self.flakes('''
  1273. import foo
  1274. with open('foo') as foo[bar]:
  1275. pass
  1276. ''', m.UndefinedName)
  1277. def test_withStatementTupleNames(self):
  1278. """
  1279. No warnings are emitted for using any of the tuple of names defined by
  1280. a C{with} statement within the suite or afterwards.
  1281. """
  1282. self.flakes('''
  1283. with open('foo') as (bar, baz):
  1284. bar, baz
  1285. bar, baz
  1286. ''')
  1287. def test_withStatementListNames(self):
  1288. """
  1289. No warnings are emitted for using any of the list of names defined by a
  1290. C{with} statement within the suite or afterwards.
  1291. """
  1292. self.flakes('''
  1293. with open('foo') as [bar, baz]:
  1294. bar, baz
  1295. bar, baz
  1296. ''')
  1297. def test_withStatementComplicatedTarget(self):
  1298. """
  1299. If the target of a C{with} statement uses any or all of the valid forms
  1300. for that part of the grammar (See
  1301. U{http://docs.python.org/reference/compound_stmts.html#the-with-statement}),
  1302. the names involved are checked both for definedness and any bindings
  1303. created are respected in the suite of the statement and afterwards.
  1304. """
  1305. self.flakes('''
  1306. c = d = e = g = h = i = None
  1307. with open('foo') as [(a, b), c[d], e.f, g[h:i]]:
  1308. a, b, c, d, e, g, h, i
  1309. a, b, c, d, e, g, h, i
  1310. ''')
  1311. def test_withStatementSingleNameUndefined(self):
  1312. """
  1313. An undefined name warning is emitted if the name first defined by a
  1314. C{with} statement is used before the C{with} statement.
  1315. """
  1316. self.flakes('''
  1317. bar
  1318. with open('foo') as bar:
  1319. pass
  1320. ''', m.UndefinedName)
  1321. def test_withStatementTupleNamesUndefined(self):
  1322. """
  1323. An undefined name warning is emitted if a name first defined by the
  1324. tuple-unpacking form of the C{with} statement is used before the
  1325. C{with} statement.
  1326. """
  1327. self.flakes('''
  1328. baz
  1329. with open('foo') as (bar, baz):
  1330. pass
  1331. ''', m.UndefinedName)
  1332. def test_withStatementSingleNameRedefined(self):
  1333. """
  1334. A redefined name warning is emitted if a name bound by an import is
  1335. rebound by the name defined by a C{with} statement.
  1336. """
  1337. self.flakes('''
  1338. import bar
  1339. with open('foo') as bar:
  1340. pass
  1341. ''', m.RedefinedWhileUnused)
  1342. def test_withStatementTupleNamesRedefined(self):
  1343. """
  1344. A redefined name warning is emitted if a name bound by an import is
  1345. rebound by one of the names defined by the tuple-unpacking form of a
  1346. C{with} statement.
  1347. """
  1348. self.flakes('''
  1349. import bar
  1350. with open('foo') as (bar, baz):
  1351. pass
  1352. ''', m.RedefinedWhileUnused)
  1353. def test_withStatementUndefinedInside(self):
  1354. """
  1355. An undefined name warning is emitted if a name is used inside the
  1356. body of a C{with} statement without first being bound.
  1357. """
  1358. self.flakes('''
  1359. with open('foo') as bar:
  1360. baz
  1361. ''', m.UndefinedName)
  1362. def test_withStatementNameDefinedInBody(self):
  1363. """
  1364. A name defined in the body of a C{with} statement can be used after
  1365. the body ends without warning.
  1366. """
  1367. self.flakes('''
  1368. with open('foo') as bar:
  1369. baz = 10
  1370. baz
  1371. ''')
  1372. def test_withStatementUndefinedInExpression(self):
  1373. """
  1374. An undefined name warning is emitted if a name in the I{test}
  1375. expression of a C{with} statement is undefined.
  1376. """
  1377. self.flakes('''
  1378. with bar as baz:
  1379. pass
  1380. ''', m.UndefinedName)
  1381. self.flakes('''
  1382. with bar as bar:
  1383. pass
  1384. ''', m.UndefinedName)
  1385. def test_dictComprehension(self):
  1386. """
  1387. Dict comprehensions are properly handled.
  1388. """
  1389. self.flakes('''
  1390. a = {1: x for x in range(10)}
  1391. ''')
  1392. def test_setComprehensionAndLiteral(self):
  1393. """
  1394. Set comprehensions are properly handled.
  1395. """
  1396. self.flakes('''
  1397. a = {1, 2, 3}
  1398. b = {x for x in range(10)}
  1399. ''')
  1400. def test_exceptionUsedInExcept(self):
  1401. self.flakes('''
  1402. try: pass
  1403. except Exception as e: e
  1404. ''')
  1405. self.flakes('''
  1406. def download_review():
  1407. try: pass
  1408. except Exception as e: e
  1409. ''')
  1410. def test_exceptionUnusedInExcept(self):
  1411. self.flakes('''
  1412. try: pass
  1413. except Exception as e: pass
  1414. ''', m.UnusedVariable)
  1415. @skipIf(version_info < (3, 11), 'new in Python 3.11')
  1416. def test_exception_unused_in_except_star(self):
  1417. self.flakes('''
  1418. try:
  1419. pass
  1420. except* OSError as e:
  1421. pass
  1422. ''', m.UnusedVariable)
  1423. def test_exceptionUnusedInExceptInFunction(self):
  1424. self.flakes('''
  1425. def download_review():
  1426. try: pass
  1427. except Exception as e: pass
  1428. ''', m.UnusedVariable)
  1429. def test_exceptWithoutNameInFunction(self):
  1430. """
  1431. Don't issue false warning when an unnamed exception is used.
  1432. Previously, there would be a false warning, but only when the
  1433. try..except was in a function
  1434. """
  1435. self.flakes('''
  1436. import tokenize
  1437. def foo():
  1438. try: pass
  1439. except tokenize.TokenError: pass
  1440. ''')
  1441. def test_exceptWithoutNameInFunctionTuple(self):
  1442. """
  1443. Don't issue false warning when an unnamed exception is used.
  1444. This example catches a tuple of exception types.
  1445. """
  1446. self.flakes('''
  1447. import tokenize
  1448. def foo():
  1449. try: pass
  1450. except (tokenize.TokenError, IndentationError): pass
  1451. ''')
  1452. def test_augmentedAssignmentImportedFunctionCall(self):
  1453. """
  1454. Consider a function that is called on the right part of an
  1455. augassign operation to be used.
  1456. """
  1457. self.flakes('''
  1458. from foo import bar
  1459. baz = 0
  1460. baz += bar()
  1461. ''')
  1462. def test_assert_without_message(self):
  1463. """An assert without a message is not an error."""
  1464. self.flakes('''
  1465. a = 1
  1466. assert a
  1467. ''')
  1468. def test_assert_with_message(self):
  1469. """An assert with a message is not an error."""
  1470. self.flakes('''
  1471. a = 1
  1472. assert a, 'x'
  1473. ''')
  1474. def test_assert_tuple(self):
  1475. """An assert of a non-empty tuple is always True."""
  1476. self.flakes('''
  1477. assert (False, 'x')
  1478. assert (False, )
  1479. ''', m.AssertTuple, m.AssertTuple)
  1480. def test_assert_tuple_empty(self):
  1481. """An assert of an empty tuple is always False."""
  1482. self.flakes('''
  1483. assert ()
  1484. ''')
  1485. def test_assert_static(self):
  1486. """An assert of a static value is not an error."""
  1487. self.flakes('''
  1488. assert True
  1489. assert 1
  1490. ''')
  1491. def test_yieldFromUndefined(self):
  1492. """
  1493. Test C{yield from} statement
  1494. """
  1495. self.flakes('''
  1496. def bar():
  1497. yield from foo()
  1498. ''', m.UndefinedName)
  1499. def test_f_string(self):
  1500. """Test PEP 498 f-strings are treated as a usage."""
  1501. self.flakes('''
  1502. baz = 0
  1503. print(f'\x7b4*baz\N{RIGHT CURLY BRACKET}')
  1504. ''')
  1505. def test_assign_expr(self):
  1506. """Test PEP 572 assignment expressions are treated as usage / write."""
  1507. self.flakes('''
  1508. from foo import y
  1509. print(x := y)
  1510. print(x)
  1511. ''')
  1512. def test_assign_expr_generator_scope(self):
  1513. """Test assignment expressions in generator expressions."""
  1514. self.flakes('''
  1515. if (any((y := x[0]) for x in [[True]])):
  1516. print(y)
  1517. ''')
  1518. def test_assign_expr_nested(self):
  1519. """Test assignment expressions in nested expressions."""
  1520. self.flakes('''
  1521. if ([(y:=x) for x in range(4) if [(z:=q) for q in range(4)]]):
  1522. print(y)
  1523. print(z)
  1524. ''')
  1525. class TestStringFormatting(TestCase):
  1526. def test_f_string_without_placeholders(self):
  1527. self.flakes("f'foo'", m.FStringMissingPlaceholders)
  1528. self.flakes('''
  1529. f"""foo
  1530. bar
  1531. """
  1532. ''', m.FStringMissingPlaceholders)
  1533. self.flakes('''
  1534. print(
  1535. f'foo'
  1536. f'bar'
  1537. )
  1538. ''', m.FStringMissingPlaceholders)
  1539. # this is an "escaped placeholder" but not a placeholder
  1540. self.flakes("f'{{}}'", m.FStringMissingPlaceholders)
  1541. # ok: f-string with placeholders
  1542. self.flakes('''
  1543. x = 5
  1544. print(f'{x}')
  1545. ''')
  1546. # ok: f-string with format specifiers
  1547. self.flakes('''
  1548. x = 'a' * 90
  1549. print(f'{x:.8}')
  1550. ''')
  1551. # ok: f-string with multiple format specifiers
  1552. self.flakes('''
  1553. x = y = 5
  1554. print(f'{x:>2} {y:>2}')
  1555. ''')
  1556. def test_invalid_dot_format_calls(self):
  1557. self.flakes('''
  1558. '{'.format(1)
  1559. ''', m.StringDotFormatInvalidFormat)
  1560. self.flakes('''
  1561. '{} {1}'.format(1, 2)
  1562. ''', m.StringDotFormatMixingAutomatic)
  1563. self.flakes('''
  1564. '{0} {}'.format(1, 2)
  1565. ''', m.StringDotFormatMixingAutomatic)
  1566. self.flakes('''
  1567. '{}'.format(1, 2)
  1568. ''', m.StringDotFormatExtraPositionalArguments)
  1569. self.flakes('''
  1570. '{}'.format(1, bar=2)
  1571. ''', m.StringDotFormatExtraNamedArguments)
  1572. self.flakes('''
  1573. '{} {}'.format(1)
  1574. ''', m.StringDotFormatMissingArgument)
  1575. self.flakes('''
  1576. '{2}'.format()
  1577. ''', m.StringDotFormatMissingArgument)
  1578. self.flakes('''
  1579. '{bar}'.format()
  1580. ''', m.StringDotFormatMissingArgument)
  1581. # too much string recursion (placeholder-in-placeholder)
  1582. self.flakes('''
  1583. '{:{:{}}}'.format(1, 2, 3)
  1584. ''', m.StringDotFormatInvalidFormat)
  1585. # ok: dotted / bracketed names need to handle the param differently
  1586. self.flakes("'{.__class__}'.format('')")
  1587. self.flakes("'{foo[bar]}'.format(foo={'bar': 'barv'})")
  1588. # ok: placeholder-placeholders
  1589. self.flakes('''
  1590. print('{:{}} {}'.format(1, 15, 2))
  1591. ''')
  1592. # ok: not a placeholder-placeholder
  1593. self.flakes('''
  1594. print('{:2}'.format(1))
  1595. ''')
  1596. # ok: not mixed automatic
  1597. self.flakes('''
  1598. '{foo}-{}'.format(1, foo=2)
  1599. ''')
  1600. # ok: we can't determine statically the format args
  1601. self.flakes('''
  1602. a = ()
  1603. "{}".format(*a)
  1604. ''')
  1605. self.flakes('''
  1606. k = {}
  1607. "{foo}".format(**k)
  1608. ''')
  1609. def test_invalid_percent_format_calls(self):
  1610. self.flakes('''
  1611. '%(foo)' % {'foo': 'bar'}
  1612. ''', m.PercentFormatInvalidFormat)
  1613. self.flakes('''
  1614. '%s %(foo)s' % {'foo': 'bar'}
  1615. ''', m.PercentFormatMixedPositionalAndNamed)
  1616. self.flakes('''
  1617. '%(foo)s %s' % {'foo': 'bar'}
  1618. ''', m.PercentFormatMixedPositionalAndNamed)
  1619. self.flakes('''
  1620. '%j' % (1,)
  1621. ''', m.PercentFormatUnsupportedFormatCharacter)
  1622. self.flakes('''
  1623. '%s %s' % (1,)
  1624. ''', m.PercentFormatPositionalCountMismatch)
  1625. self.flakes('''
  1626. '%s %s' % (1, 2, 3)
  1627. ''', m.PercentFormatPositionalCountMismatch)
  1628. self.flakes('''
  1629. '%(bar)s' % {}
  1630. ''', m.PercentFormatMissingArgument,)
  1631. self.flakes('''
  1632. '%(bar)s' % {'bar': 1, 'baz': 2}
  1633. ''', m.PercentFormatExtraNamedArguments)
  1634. self.flakes('''
  1635. '%(bar)s' % (1, 2, 3)
  1636. ''', m.PercentFormatExpectedMapping)
  1637. self.flakes('''
  1638. '%s %s' % {'k': 'v'}
  1639. ''', m.PercentFormatExpectedSequence)
  1640. self.flakes('''
  1641. '%(bar)*s' % {'bar': 'baz'}
  1642. ''', m.PercentFormatStarRequiresSequence)
  1643. # ok: single %s with mapping
  1644. self.flakes('''
  1645. '%s' % {'foo': 'bar', 'baz': 'womp'}
  1646. ''')
  1647. # ok: does not cause a MemoryError (the strings aren't evaluated)
  1648. self.flakes('''
  1649. "%1000000000000f" % 1
  1650. ''')
  1651. # ok: %% should not count towards placeholder count
  1652. self.flakes('''
  1653. '%% %s %% %s' % (1, 2)
  1654. ''')
  1655. # ok: * consumes one positional argument
  1656. self.flakes('''
  1657. '%.*f' % (2, 1.1234)
  1658. '%*.*f' % (5, 2, 3.1234)
  1659. ''')
  1660. def test_ok_percent_format_cannot_determine_element_count(self):
  1661. self.flakes('''
  1662. a = []
  1663. '%s %s' % [*a]
  1664. '%s %s' % (*a,)
  1665. ''')
  1666. self.flakes('''
  1667. k = {}
  1668. '%(k)s' % {**k}
  1669. ''')
  1670. class TestAsyncStatements(TestCase):
  1671. def test_asyncDef(self):
  1672. self.flakes('''
  1673. async def bar():
  1674. return 42
  1675. ''')
  1676. def test_asyncDefAwait(self):
  1677. self.flakes('''
  1678. async def read_data(db):
  1679. await db.fetch('SELECT ...')
  1680. ''')
  1681. def test_asyncDefUndefined(self):
  1682. self.flakes('''
  1683. async def bar():
  1684. return foo()
  1685. ''', m.UndefinedName)
  1686. def test_asyncFor(self):
  1687. self.flakes('''
  1688. async def read_data(db):
  1689. output = []
  1690. async for row in db.cursor():
  1691. output.append(row)
  1692. return output
  1693. ''')
  1694. def test_asyncForUnderscoreLoopVar(self):
  1695. self.flakes('''
  1696. async def coro(it):
  1697. async for _ in it:
  1698. pass
  1699. ''')
  1700. def test_loopControlInAsyncFor(self):
  1701. self.flakes('''
  1702. async def read_data(db):
  1703. output = []
  1704. async for row in db.cursor():
  1705. if row[0] == 'skip':
  1706. continue
  1707. output.append(row)
  1708. return output
  1709. ''')
  1710. self.flakes('''
  1711. async def read_data(db):
  1712. output = []
  1713. async for row in db.cursor():
  1714. if row[0] == 'stop':
  1715. break
  1716. output.append(row)
  1717. return output
  1718. ''')
  1719. def test_loopControlInAsyncForElse(self):
  1720. self.flakes('''
  1721. async def read_data(db):
  1722. output = []
  1723. async for row in db.cursor():
  1724. output.append(row)
  1725. else:
  1726. continue
  1727. return output
  1728. ''', m.ContinueOutsideLoop)
  1729. self.flakes('''
  1730. async def read_data(db):
  1731. output = []
  1732. async for row in db.cursor():
  1733. output.append(row)
  1734. else:
  1735. break
  1736. return output
  1737. ''', m.BreakOutsideLoop)
  1738. def test_asyncWith(self):
  1739. self.flakes('''
  1740. async def commit(session, data):
  1741. async with session.transaction():
  1742. await session.update(data)
  1743. ''')
  1744. def test_asyncWithItem(self):
  1745. self.flakes('''
  1746. async def commit(session, data):
  1747. async with session.transaction() as trans:
  1748. await trans.begin()
  1749. ...
  1750. await trans.end()
  1751. ''')
  1752. def test_matmul(self):
  1753. self.flakes('''
  1754. def foo(a, b):
  1755. return a @ b
  1756. ''')
  1757. def test_formatstring(self):
  1758. self.flakes('''
  1759. hi = 'hi'
  1760. mom = 'mom'
  1761. f'{hi} {mom}'
  1762. ''')
  1763. def test_raise_notimplemented(self):
  1764. self.flakes('''
  1765. raise NotImplementedError("This is fine")
  1766. ''')
  1767. self.flakes('''
  1768. raise NotImplementedError
  1769. ''')
  1770. self.flakes('''
  1771. raise NotImplemented("This isn't gonna work")
  1772. ''', m.RaiseNotImplemented)
  1773. self.flakes('''
  1774. raise NotImplemented
  1775. ''', m.RaiseNotImplemented)
  1776. class TestIncompatiblePrintOperator(TestCase):
  1777. """
  1778. Tests for warning about invalid use of print function.
  1779. """
  1780. def test_valid_print(self):
  1781. self.flakes('''
  1782. print("Hello")
  1783. ''')
  1784. def test_invalid_print_when_imported_from_future(self):
  1785. exc = self.flakes('''
  1786. from __future__ import print_function
  1787. import sys
  1788. print >>sys.stderr, "Hello"
  1789. ''', m.InvalidPrintSyntax).messages[0]
  1790. self.assertEqual(exc.lineno, 4)
  1791. self.assertEqual(exc.col, 0)
  1792. def test_print_augmented_assign(self):
  1793. # nonsense, but shouldn't crash pyflakes
  1794. self.flakes('print += 1')
  1795. def test_print_function_assignment(self):
  1796. """
  1797. A valid assignment, tested for catching false positives.
  1798. """
  1799. self.flakes('''
  1800. from __future__ import print_function
  1801. log = print
  1802. log("Hello")
  1803. ''')
  1804. def test_print_in_lambda(self):
  1805. self.flakes('''
  1806. from __future__ import print_function
  1807. a = lambda: print
  1808. ''')
  1809. def test_print_returned_in_function(self):
  1810. self.flakes('''
  1811. from __future__ import print_function
  1812. def a():
  1813. return print
  1814. ''')
  1815. def test_print_as_condition_test(self):
  1816. self.flakes('''
  1817. from __future__ import print_function
  1818. if print: pass
  1819. ''')