test_imports.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. from pyflakes import messages as m
  2. from pyflakes.checker import (
  3. FutureImportation,
  4. Importation,
  5. ImportationFrom,
  6. StarImportation,
  7. SubmoduleImportation,
  8. )
  9. from pyflakes.test.harness import TestCase, skip
  10. class TestImportationObject(TestCase):
  11. def test_import_basic(self):
  12. binding = Importation('a', None, 'a')
  13. assert binding.source_statement == 'import a'
  14. assert str(binding) == 'a'
  15. def test_import_as(self):
  16. binding = Importation('c', None, 'a')
  17. assert binding.source_statement == 'import a as c'
  18. assert str(binding) == 'a as c'
  19. def test_import_submodule(self):
  20. binding = SubmoduleImportation('a.b', None)
  21. assert binding.source_statement == 'import a.b'
  22. assert str(binding) == 'a.b'
  23. def test_import_submodule_as(self):
  24. # A submodule import with an as clause is not a SubmoduleImportation
  25. binding = Importation('c', None, 'a.b')
  26. assert binding.source_statement == 'import a.b as c'
  27. assert str(binding) == 'a.b as c'
  28. def test_import_submodule_as_source_name(self):
  29. binding = Importation('a', None, 'a.b')
  30. assert binding.source_statement == 'import a.b as a'
  31. assert str(binding) == 'a.b as a'
  32. def test_importfrom_relative(self):
  33. binding = ImportationFrom('a', None, '.', 'a')
  34. assert binding.source_statement == 'from . import a'
  35. assert str(binding) == '.a'
  36. def test_importfrom_relative_parent(self):
  37. binding = ImportationFrom('a', None, '..', 'a')
  38. assert binding.source_statement == 'from .. import a'
  39. assert str(binding) == '..a'
  40. def test_importfrom_relative_with_module(self):
  41. binding = ImportationFrom('b', None, '..a', 'b')
  42. assert binding.source_statement == 'from ..a import b'
  43. assert str(binding) == '..a.b'
  44. def test_importfrom_relative_with_module_as(self):
  45. binding = ImportationFrom('c', None, '..a', 'b')
  46. assert binding.source_statement == 'from ..a import b as c'
  47. assert str(binding) == '..a.b as c'
  48. def test_importfrom_member(self):
  49. binding = ImportationFrom('b', None, 'a', 'b')
  50. assert binding.source_statement == 'from a import b'
  51. assert str(binding) == 'a.b'
  52. def test_importfrom_submodule_member(self):
  53. binding = ImportationFrom('c', None, 'a.b', 'c')
  54. assert binding.source_statement == 'from a.b import c'
  55. assert str(binding) == 'a.b.c'
  56. def test_importfrom_member_as(self):
  57. binding = ImportationFrom('c', None, 'a', 'b')
  58. assert binding.source_statement == 'from a import b as c'
  59. assert str(binding) == 'a.b as c'
  60. def test_importfrom_submodule_member_as(self):
  61. binding = ImportationFrom('d', None, 'a.b', 'c')
  62. assert binding.source_statement == 'from a.b import c as d'
  63. assert str(binding) == 'a.b.c as d'
  64. def test_importfrom_star(self):
  65. binding = StarImportation('a.b', None)
  66. assert binding.source_statement == 'from a.b import *'
  67. assert str(binding) == 'a.b.*'
  68. def test_importfrom_star_relative(self):
  69. binding = StarImportation('.b', None)
  70. assert binding.source_statement == 'from .b import *'
  71. assert str(binding) == '.b.*'
  72. def test_importfrom_future(self):
  73. binding = FutureImportation('print_function', None, None)
  74. assert binding.source_statement == 'from __future__ import print_function'
  75. assert str(binding) == '__future__.print_function'
  76. def test_unusedImport_underscore(self):
  77. """
  78. The magic underscore var should be reported as unused when used as an
  79. import alias.
  80. """
  81. self.flakes('import fu as _', m.UnusedImport)
  82. class Test(TestCase):
  83. def test_unusedImport(self):
  84. self.flakes('import fu, bar', m.UnusedImport, m.UnusedImport)
  85. self.flakes('from baz import fu, bar', m.UnusedImport, m.UnusedImport)
  86. def test_unusedImport_relative(self):
  87. self.flakes('from . import fu', m.UnusedImport)
  88. self.flakes('from . import fu as baz', m.UnusedImport)
  89. self.flakes('from .. import fu', m.UnusedImport)
  90. self.flakes('from ... import fu', m.UnusedImport)
  91. self.flakes('from .. import fu as baz', m.UnusedImport)
  92. self.flakes('from .bar import fu', m.UnusedImport)
  93. self.flakes('from ..bar import fu', m.UnusedImport)
  94. self.flakes('from ...bar import fu', m.UnusedImport)
  95. self.flakes('from ...bar import fu as baz', m.UnusedImport)
  96. checker = self.flakes('from . import fu', m.UnusedImport)
  97. error = checker.messages[0]
  98. assert error.message == '%r imported but unused'
  99. assert error.message_args == ('.fu', )
  100. checker = self.flakes('from . import fu as baz', m.UnusedImport)
  101. error = checker.messages[0]
  102. assert error.message == '%r imported but unused'
  103. assert error.message_args == ('.fu as baz', )
  104. def test_aliasedImport(self):
  105. self.flakes('import fu as FU, bar as FU',
  106. m.RedefinedWhileUnused, m.UnusedImport)
  107. self.flakes('from moo import fu as FU, bar as FU',
  108. m.RedefinedWhileUnused, m.UnusedImport)
  109. def test_aliasedImportShadowModule(self):
  110. """Imported aliases can shadow the source of the import."""
  111. self.flakes('from moo import fu as moo; moo')
  112. self.flakes('import fu as fu; fu')
  113. self.flakes('import fu.bar as fu; fu')
  114. def test_usedImport(self):
  115. self.flakes('import fu; print(fu)')
  116. self.flakes('from baz import fu; print(fu)')
  117. self.flakes('import fu; del fu')
  118. def test_usedImport_relative(self):
  119. self.flakes('from . import fu; assert fu')
  120. self.flakes('from .bar import fu; assert fu')
  121. self.flakes('from .. import fu; assert fu')
  122. self.flakes('from ..bar import fu as baz; assert baz')
  123. def test_redefinedWhileUnused(self):
  124. self.flakes('import fu; fu = 3', m.RedefinedWhileUnused)
  125. self.flakes('import fu; fu, bar = 3', m.RedefinedWhileUnused)
  126. self.flakes('import fu; [fu, bar] = 3', m.RedefinedWhileUnused)
  127. def test_redefinedIf(self):
  128. """
  129. Test that importing a module twice within an if
  130. block does raise a warning.
  131. """
  132. self.flakes('''
  133. i = 2
  134. if i==1:
  135. import os
  136. import os
  137. os.path''', m.RedefinedWhileUnused)
  138. def test_redefinedIfElse(self):
  139. """
  140. Test that importing a module twice in if
  141. and else blocks does not raise a warning.
  142. """
  143. self.flakes('''
  144. i = 2
  145. if i==1:
  146. import os
  147. else:
  148. import os
  149. os.path''')
  150. def test_redefinedTry(self):
  151. """
  152. Test that importing a module twice in a try block
  153. does raise a warning.
  154. """
  155. self.flakes('''
  156. try:
  157. import os
  158. import os
  159. except:
  160. pass
  161. os.path''', m.RedefinedWhileUnused)
  162. def test_redefinedTryExcept(self):
  163. """
  164. Test that importing a module twice in a try
  165. and except block does not raise a warning.
  166. """
  167. self.flakes('''
  168. try:
  169. import os
  170. except:
  171. import os
  172. os.path''')
  173. def test_redefinedTryNested(self):
  174. """
  175. Test that importing a module twice using a nested
  176. try/except and if blocks does not issue a warning.
  177. """
  178. self.flakes('''
  179. try:
  180. if True:
  181. if True:
  182. import os
  183. except:
  184. import os
  185. os.path''')
  186. def test_redefinedTryExceptMulti(self):
  187. self.flakes("""
  188. try:
  189. from aa import mixer
  190. except AttributeError:
  191. from bb import mixer
  192. except RuntimeError:
  193. from cc import mixer
  194. except:
  195. from dd import mixer
  196. mixer(123)
  197. """)
  198. def test_redefinedTryElse(self):
  199. self.flakes("""
  200. try:
  201. from aa import mixer
  202. except ImportError:
  203. pass
  204. else:
  205. from bb import mixer
  206. mixer(123)
  207. """, m.RedefinedWhileUnused)
  208. def test_redefinedTryExceptElse(self):
  209. self.flakes("""
  210. try:
  211. import funca
  212. except ImportError:
  213. from bb import funca
  214. from bb import funcb
  215. else:
  216. from bbb import funcb
  217. print(funca, funcb)
  218. """)
  219. def test_redefinedTryExceptFinally(self):
  220. self.flakes("""
  221. try:
  222. from aa import a
  223. except ImportError:
  224. from bb import a
  225. finally:
  226. a = 42
  227. print(a)
  228. """)
  229. def test_redefinedTryExceptElseFinally(self):
  230. self.flakes("""
  231. try:
  232. import b
  233. except ImportError:
  234. b = Ellipsis
  235. from bb import a
  236. else:
  237. from aa import a
  238. finally:
  239. a = 42
  240. print(a, b)
  241. """)
  242. def test_redefinedByFunction(self):
  243. self.flakes('''
  244. import fu
  245. def fu():
  246. pass
  247. ''', m.RedefinedWhileUnused)
  248. def test_redefinedInNestedFunction(self):
  249. """
  250. Test that shadowing a global name with a nested function definition
  251. generates a warning.
  252. """
  253. self.flakes('''
  254. import fu
  255. def bar():
  256. def baz():
  257. def fu():
  258. pass
  259. ''', m.RedefinedWhileUnused, m.UnusedImport)
  260. def test_redefinedInNestedFunctionTwice(self):
  261. """
  262. Test that shadowing a global name with a nested function definition
  263. generates a warning.
  264. """
  265. self.flakes('''
  266. import fu
  267. def bar():
  268. import fu
  269. def baz():
  270. def fu():
  271. pass
  272. ''',
  273. m.RedefinedWhileUnused, m.RedefinedWhileUnused,
  274. m.UnusedImport, m.UnusedImport)
  275. def test_redefinedButUsedLater(self):
  276. """
  277. Test that a global import which is redefined locally,
  278. but used later in another scope does not generate a warning.
  279. """
  280. self.flakes('''
  281. import unittest, transport
  282. class GetTransportTestCase(unittest.TestCase):
  283. def test_get_transport(self):
  284. transport = 'transport'
  285. self.assertIsNotNone(transport)
  286. class TestTransportMethodArgs(unittest.TestCase):
  287. def test_send_defaults(self):
  288. transport.Transport()
  289. ''')
  290. def test_redefinedByClass(self):
  291. self.flakes('''
  292. import fu
  293. class fu:
  294. pass
  295. ''', m.RedefinedWhileUnused)
  296. def test_redefinedBySubclass(self):
  297. """
  298. If an imported name is redefined by a class statement which also uses
  299. that name in the bases list, no warning is emitted.
  300. """
  301. self.flakes('''
  302. from fu import bar
  303. class bar(bar):
  304. pass
  305. ''')
  306. def test_redefinedInClass(self):
  307. """
  308. Test that shadowing a global with a class attribute does not produce a
  309. warning.
  310. """
  311. self.flakes('''
  312. import fu
  313. class bar:
  314. fu = 1
  315. print(fu)
  316. ''')
  317. def test_importInClass(self):
  318. """
  319. Test that import within class is a locally scoped attribute.
  320. """
  321. self.flakes('''
  322. class bar:
  323. import fu
  324. ''')
  325. self.flakes('''
  326. class bar:
  327. import fu
  328. fu
  329. ''', m.UndefinedName)
  330. def test_usedInFunction(self):
  331. self.flakes('''
  332. import fu
  333. def fun():
  334. print(fu)
  335. ''')
  336. def test_shadowedByParameter(self):
  337. self.flakes('''
  338. import fu
  339. def fun(fu):
  340. print(fu)
  341. ''', m.UnusedImport, m.RedefinedWhileUnused)
  342. self.flakes('''
  343. import fu
  344. def fun(fu):
  345. print(fu)
  346. print(fu)
  347. ''')
  348. def test_newAssignment(self):
  349. self.flakes('fu = None')
  350. def test_usedInGetattr(self):
  351. self.flakes('import fu; fu.bar.baz')
  352. self.flakes('import fu; "bar".fu.baz', m.UnusedImport)
  353. def test_usedInSlice(self):
  354. self.flakes('import fu; print(fu.bar[1:])')
  355. def test_usedInIfBody(self):
  356. self.flakes('''
  357. import fu
  358. if True: print(fu)
  359. ''')
  360. def test_usedInIfConditional(self):
  361. self.flakes('''
  362. import fu
  363. if fu: pass
  364. ''')
  365. def test_usedInElifConditional(self):
  366. self.flakes('''
  367. import fu
  368. if False: pass
  369. elif fu: pass
  370. ''')
  371. def test_usedInElse(self):
  372. self.flakes('''
  373. import fu
  374. if False: pass
  375. else: print(fu)
  376. ''')
  377. def test_usedInCall(self):
  378. self.flakes('import fu; fu.bar()')
  379. def test_usedInClass(self):
  380. self.flakes('''
  381. import fu
  382. class bar:
  383. bar = fu
  384. ''')
  385. def test_usedInClassBase(self):
  386. self.flakes('''
  387. import fu
  388. class bar(object, fu.baz):
  389. pass
  390. ''')
  391. def test_notUsedInNestedScope(self):
  392. self.flakes('''
  393. import fu
  394. def bleh():
  395. pass
  396. print(fu)
  397. ''')
  398. def test_usedInFor(self):
  399. self.flakes('''
  400. import fu
  401. for bar in range(9):
  402. print(fu)
  403. ''')
  404. def test_usedInForElse(self):
  405. self.flakes('''
  406. import fu
  407. for bar in range(10):
  408. pass
  409. else:
  410. print(fu)
  411. ''')
  412. def test_redefinedByFor(self):
  413. self.flakes('''
  414. import fu
  415. for fu in range(2):
  416. pass
  417. ''', m.ImportShadowedByLoopVar)
  418. def test_shadowedByFor(self):
  419. """
  420. Test that shadowing a global name with a for loop variable generates a
  421. warning.
  422. """
  423. self.flakes('''
  424. import fu
  425. fu.bar()
  426. for fu in ():
  427. pass
  428. ''', m.ImportShadowedByLoopVar)
  429. def test_shadowedByForDeep(self):
  430. """
  431. Test that shadowing a global name with a for loop variable nested in a
  432. tuple unpack generates a warning.
  433. """
  434. self.flakes('''
  435. import fu
  436. fu.bar()
  437. for (x, y, z, (a, b, c, (fu,))) in ():
  438. pass
  439. ''', m.ImportShadowedByLoopVar)
  440. # Same with a list instead of a tuple
  441. self.flakes('''
  442. import fu
  443. fu.bar()
  444. for [x, y, z, (a, b, c, (fu,))] in ():
  445. pass
  446. ''', m.ImportShadowedByLoopVar)
  447. def test_usedInReturn(self):
  448. self.flakes('''
  449. import fu
  450. def fun():
  451. return fu
  452. ''')
  453. def test_usedInOperators(self):
  454. self.flakes('import fu; 3 + fu.bar')
  455. self.flakes('import fu; 3 % fu.bar')
  456. self.flakes('import fu; 3 - fu.bar')
  457. self.flakes('import fu; 3 * fu.bar')
  458. self.flakes('import fu; 3 ** fu.bar')
  459. self.flakes('import fu; 3 / fu.bar')
  460. self.flakes('import fu; 3 // fu.bar')
  461. self.flakes('import fu; -fu.bar')
  462. self.flakes('import fu; ~fu.bar')
  463. self.flakes('import fu; 1 == fu.bar')
  464. self.flakes('import fu; 1 | fu.bar')
  465. self.flakes('import fu; 1 & fu.bar')
  466. self.flakes('import fu; 1 ^ fu.bar')
  467. self.flakes('import fu; 1 >> fu.bar')
  468. self.flakes('import fu; 1 << fu.bar')
  469. def test_usedInAssert(self):
  470. self.flakes('import fu; assert fu.bar')
  471. def test_usedInSubscript(self):
  472. self.flakes('import fu; fu.bar[1]')
  473. def test_usedInLogic(self):
  474. self.flakes('import fu; fu and False')
  475. self.flakes('import fu; fu or False')
  476. self.flakes('import fu; not fu.bar')
  477. def test_usedInList(self):
  478. self.flakes('import fu; [fu]')
  479. def test_usedInTuple(self):
  480. self.flakes('import fu; (fu,)')
  481. def test_usedInTry(self):
  482. self.flakes('''
  483. import fu
  484. try: fu
  485. except: pass
  486. ''')
  487. def test_usedInExcept(self):
  488. self.flakes('''
  489. import fu
  490. try: fu
  491. except: pass
  492. ''')
  493. def test_redefinedByExcept(self):
  494. expected = [m.RedefinedWhileUnused]
  495. # The exc variable is unused inside the exception handler.
  496. expected.append(m.UnusedVariable)
  497. self.flakes('''
  498. import fu
  499. try: pass
  500. except Exception as fu: pass
  501. ''', *expected)
  502. def test_usedInRaise(self):
  503. self.flakes('''
  504. import fu
  505. raise fu.bar
  506. ''')
  507. def test_usedInYield(self):
  508. self.flakes('''
  509. import fu
  510. def gen():
  511. yield fu
  512. ''')
  513. def test_usedInDict(self):
  514. self.flakes('import fu; {fu:None}')
  515. self.flakes('import fu; {1:fu}')
  516. def test_usedInParameterDefault(self):
  517. self.flakes('''
  518. import fu
  519. def f(bar=fu):
  520. pass
  521. ''')
  522. def test_usedInAttributeAssign(self):
  523. self.flakes('import fu; fu.bar = 1')
  524. def test_usedInKeywordArg(self):
  525. self.flakes('import fu; fu.bar(stuff=fu)')
  526. def test_usedInAssignment(self):
  527. self.flakes('import fu; bar=fu')
  528. self.flakes('import fu; n=0; n+=fu')
  529. def test_usedInListComp(self):
  530. self.flakes('import fu; [fu for _ in range(1)]')
  531. self.flakes('import fu; [1 for _ in range(1) if fu]')
  532. def test_usedInTryFinally(self):
  533. self.flakes('''
  534. import fu
  535. try: pass
  536. finally: fu
  537. ''')
  538. self.flakes('''
  539. import fu
  540. try: fu
  541. finally: pass
  542. ''')
  543. def test_usedInWhile(self):
  544. self.flakes('''
  545. import fu
  546. while 0:
  547. fu
  548. ''')
  549. self.flakes('''
  550. import fu
  551. while fu: pass
  552. ''')
  553. def test_usedInGlobal(self):
  554. """
  555. A 'global' statement shadowing an unused import should not prevent it
  556. from being reported.
  557. """
  558. self.flakes('''
  559. import fu
  560. def f(): global fu
  561. ''', m.UnusedImport)
  562. def test_usedAndGlobal(self):
  563. """
  564. A 'global' statement shadowing a used import should not cause it to be
  565. reported as unused.
  566. """
  567. self.flakes('''
  568. import foo
  569. def f(): global foo
  570. def g(): foo.is_used()
  571. ''')
  572. def test_assignedToGlobal(self):
  573. """
  574. Binding an import to a declared global should not cause it to be
  575. reported as unused.
  576. """
  577. self.flakes('''
  578. def f(): global foo; import foo
  579. def g(): foo.is_used()
  580. ''')
  581. def test_usedInExec(self):
  582. exec_stmt = 'exec("print(1)", fu.bar)'
  583. self.flakes('import fu; %s' % exec_stmt)
  584. def test_usedInLambda(self):
  585. self.flakes('import fu; lambda: fu')
  586. def test_shadowedByLambda(self):
  587. self.flakes('import fu; lambda fu: fu',
  588. m.UnusedImport, m.RedefinedWhileUnused)
  589. self.flakes('import fu; lambda fu: fu\nfu()')
  590. def test_usedInSliceObj(self):
  591. self.flakes('import fu; "meow"[::fu]')
  592. def test_unusedInNestedScope(self):
  593. self.flakes('''
  594. def bar():
  595. import fu
  596. fu
  597. ''', m.UnusedImport, m.UndefinedName)
  598. def test_methodsDontUseClassScope(self):
  599. self.flakes('''
  600. class bar:
  601. import fu
  602. def fun(self):
  603. fu
  604. ''', m.UndefinedName)
  605. def test_nestedFunctionsNestScope(self):
  606. self.flakes('''
  607. def a():
  608. def b():
  609. fu
  610. import fu
  611. ''')
  612. def test_nestedClassAndFunctionScope(self):
  613. self.flakes('''
  614. def a():
  615. import fu
  616. class b:
  617. def c(self):
  618. print(fu)
  619. ''')
  620. def test_importStar(self):
  621. """Use of import * at module level is reported."""
  622. self.flakes('from fu import *', m.ImportStarUsed, m.UnusedImport)
  623. self.flakes('''
  624. try:
  625. from fu import *
  626. except:
  627. pass
  628. ''', m.ImportStarUsed, m.UnusedImport)
  629. checker = self.flakes('from fu import *',
  630. m.ImportStarUsed, m.UnusedImport)
  631. error = checker.messages[0]
  632. assert error.message.startswith("'from %s import *' used; unable ")
  633. assert error.message_args == ('fu', )
  634. error = checker.messages[1]
  635. assert error.message == '%r imported but unused'
  636. assert error.message_args == ('fu.*', )
  637. def test_importStar_relative(self):
  638. """Use of import * from a relative import is reported."""
  639. self.flakes('from .fu import *', m.ImportStarUsed, m.UnusedImport)
  640. self.flakes('''
  641. try:
  642. from .fu import *
  643. except:
  644. pass
  645. ''', m.ImportStarUsed, m.UnusedImport)
  646. checker = self.flakes('from .fu import *',
  647. m.ImportStarUsed, m.UnusedImport)
  648. error = checker.messages[0]
  649. assert error.message.startswith("'from %s import *' used; unable ")
  650. assert error.message_args == ('.fu', )
  651. error = checker.messages[1]
  652. assert error.message == '%r imported but unused'
  653. assert error.message_args == ('.fu.*', )
  654. checker = self.flakes('from .. import *',
  655. m.ImportStarUsed, m.UnusedImport)
  656. error = checker.messages[0]
  657. assert error.message.startswith("'from %s import *' used; unable ")
  658. assert error.message_args == ('..', )
  659. error = checker.messages[1]
  660. assert error.message == '%r imported but unused'
  661. assert error.message_args == ('from .. import *', )
  662. def test_localImportStar(self):
  663. """import * is only allowed at module level."""
  664. self.flakes('''
  665. def a():
  666. from fu import *
  667. ''', m.ImportStarNotPermitted)
  668. self.flakes('''
  669. class a:
  670. from fu import *
  671. ''', m.ImportStarNotPermitted)
  672. checker = self.flakes('''
  673. class a:
  674. from .. import *
  675. ''', m.ImportStarNotPermitted)
  676. error = checker.messages[0]
  677. assert error.message == "'from %s import *' only allowed at module level"
  678. assert error.message_args == ('..', )
  679. def test_packageImport(self):
  680. """
  681. If a dotted name is imported and used, no warning is reported.
  682. """
  683. self.flakes('''
  684. import fu.bar
  685. fu.bar
  686. ''')
  687. def test_unusedPackageImport(self):
  688. """
  689. If a dotted name is imported and not used, an unused import warning is
  690. reported.
  691. """
  692. self.flakes('import fu.bar', m.UnusedImport)
  693. def test_duplicateSubmoduleImport(self):
  694. """
  695. If a submodule of a package is imported twice, an unused import warning
  696. and a redefined while unused warning are reported.
  697. """
  698. self.flakes('''
  699. import fu.bar, fu.bar
  700. fu.bar
  701. ''', m.RedefinedWhileUnused)
  702. self.flakes('''
  703. import fu.bar
  704. import fu.bar
  705. fu.bar
  706. ''', m.RedefinedWhileUnused)
  707. def test_differentSubmoduleImport(self):
  708. """
  709. If two different submodules of a package are imported, no duplicate
  710. import warning is reported for the package.
  711. """
  712. self.flakes('''
  713. import fu.bar, fu.baz
  714. fu.bar, fu.baz
  715. ''')
  716. self.flakes('''
  717. import fu.bar
  718. import fu.baz
  719. fu.bar, fu.baz
  720. ''')
  721. def test_used_package_with_submodule_import(self):
  722. """
  723. Usage of package marks submodule imports as used.
  724. """
  725. self.flakes('''
  726. import fu
  727. import fu.bar
  728. fu.x
  729. ''')
  730. self.flakes('''
  731. import fu.bar
  732. import fu
  733. fu.x
  734. ''')
  735. def test_used_package_with_submodule_import_of_alias(self):
  736. """
  737. Usage of package by alias marks submodule imports as used.
  738. """
  739. self.flakes('''
  740. import foo as f
  741. import foo.bar
  742. f.bar.do_something()
  743. ''')
  744. self.flakes('''
  745. import foo as f
  746. import foo.bar.blah
  747. f.bar.blah.do_something()
  748. ''')
  749. def test_unused_package_with_submodule_import(self):
  750. """
  751. When a package and its submodule are imported, only report once.
  752. """
  753. checker = self.flakes('''
  754. import fu
  755. import fu.bar
  756. ''', m.UnusedImport)
  757. error = checker.messages[0]
  758. assert error.message == '%r imported but unused'
  759. assert error.message_args == ('fu.bar', )
  760. assert error.lineno == 5 if self.withDoctest else 3
  761. def test_assignRHSFirst(self):
  762. self.flakes('import fu; fu = fu')
  763. self.flakes('import fu; fu, bar = fu')
  764. self.flakes('import fu; [fu, bar] = fu')
  765. self.flakes('import fu; fu += fu')
  766. def test_tryingMultipleImports(self):
  767. self.flakes('''
  768. try:
  769. import fu
  770. except ImportError:
  771. import bar as fu
  772. fu
  773. ''')
  774. def test_nonGlobalDoesNotRedefine(self):
  775. self.flakes('''
  776. import fu
  777. def a():
  778. fu = 3
  779. return fu
  780. fu
  781. ''')
  782. def test_functionsRunLater(self):
  783. self.flakes('''
  784. def a():
  785. fu
  786. import fu
  787. ''')
  788. def test_functionNamesAreBoundNow(self):
  789. self.flakes('''
  790. import fu
  791. def fu():
  792. fu
  793. fu
  794. ''', m.RedefinedWhileUnused)
  795. def test_ignoreNonImportRedefinitions(self):
  796. self.flakes('a = 1; a = 2')
  797. @skip("todo")
  798. def test_importingForImportError(self):
  799. self.flakes('''
  800. try:
  801. import fu
  802. except ImportError:
  803. pass
  804. ''')
  805. def test_importedInClass(self):
  806. """Imports in class scope can be used through self."""
  807. self.flakes('''
  808. class c:
  809. import i
  810. def __init__(self):
  811. self.i
  812. ''')
  813. def test_importUsedInMethodDefinition(self):
  814. """
  815. Method named 'foo' with default args referring to module named 'foo'.
  816. """
  817. self.flakes('''
  818. import foo
  819. class Thing(object):
  820. def foo(self, parser=foo.parse_foo):
  821. pass
  822. ''')
  823. def test_futureImport(self):
  824. """__future__ is special."""
  825. self.flakes('from __future__ import division')
  826. self.flakes('''
  827. "docstring is allowed before future import"
  828. from __future__ import division
  829. ''')
  830. def test_futureImportFirst(self):
  831. """
  832. __future__ imports must come before anything else.
  833. """
  834. self.flakes('''
  835. x = 5
  836. from __future__ import division
  837. ''', m.LateFutureImport)
  838. self.flakes('''
  839. from foo import bar
  840. from __future__ import division
  841. bar
  842. ''', m.LateFutureImport)
  843. def test_futureImportUsed(self):
  844. """__future__ is special, but names are injected in the namespace."""
  845. self.flakes('''
  846. from __future__ import division
  847. from __future__ import print_function
  848. assert print_function is not division
  849. ''')
  850. def test_futureImportUndefined(self):
  851. """Importing undefined names from __future__ fails."""
  852. self.flakes('''
  853. from __future__ import print_statement
  854. ''', m.FutureFeatureNotDefined)
  855. def test_futureImportStar(self):
  856. """Importing '*' from __future__ fails."""
  857. self.flakes('''
  858. from __future__ import *
  859. ''', m.FutureFeatureNotDefined)
  860. class TestSpecialAll(TestCase):
  861. """
  862. Tests for suppression of unused import warnings by C{__all__}.
  863. """
  864. def test_ignoredInFunction(self):
  865. """
  866. An C{__all__} definition does not suppress unused import warnings in a
  867. function scope.
  868. """
  869. self.flakes('''
  870. def foo():
  871. import bar
  872. __all__ = ["bar"]
  873. ''', m.UnusedImport, m.UnusedVariable)
  874. def test_ignoredInClass(self):
  875. """
  876. An C{__all__} definition in a class does not suppress unused import warnings.
  877. """
  878. self.flakes('''
  879. import bar
  880. class foo:
  881. __all__ = ["bar"]
  882. ''', m.UnusedImport)
  883. def test_ignored_when_not_directly_assigned(self):
  884. self.flakes('''
  885. import bar
  886. (__all__,) = ("foo",)
  887. ''', m.UnusedImport)
  888. def test_warningSuppressed(self):
  889. """
  890. If a name is imported and unused but is named in C{__all__}, no warning
  891. is reported.
  892. """
  893. self.flakes('''
  894. import foo
  895. __all__ = ["foo"]
  896. ''')
  897. self.flakes('''
  898. import foo
  899. __all__ = ("foo",)
  900. ''')
  901. def test_augmentedAssignment(self):
  902. """
  903. The C{__all__} variable is defined incrementally.
  904. """
  905. self.flakes('''
  906. import a
  907. import c
  908. __all__ = ['a']
  909. __all__ += ['b']
  910. if 1 < 3:
  911. __all__ += ['c', 'd']
  912. ''', m.UndefinedExport, m.UndefinedExport)
  913. def test_list_concatenation_assignment(self):
  914. """
  915. The C{__all__} variable is defined through list concatenation.
  916. """
  917. self.flakes('''
  918. import sys
  919. __all__ = ['a'] + ['b'] + ['c']
  920. ''', m.UndefinedExport, m.UndefinedExport, m.UndefinedExport, m.UnusedImport)
  921. def test_tuple_concatenation_assignment(self):
  922. """
  923. The C{__all__} variable is defined through tuple concatenation.
  924. """
  925. self.flakes('''
  926. import sys
  927. __all__ = ('a',) + ('b',) + ('c',)
  928. ''', m.UndefinedExport, m.UndefinedExport, m.UndefinedExport, m.UnusedImport)
  929. def test_all_with_attributes(self):
  930. self.flakes('''
  931. from foo import bar
  932. __all__ = [bar.__name__]
  933. ''')
  934. def test_all_with_names(self):
  935. # not actually valid, but shouldn't produce a crash
  936. self.flakes('''
  937. from foo import bar
  938. __all__ = [bar]
  939. ''')
  940. def test_all_with_attributes_added(self):
  941. self.flakes('''
  942. from foo import bar
  943. from bar import baz
  944. __all__ = [bar.__name__] + [baz.__name__]
  945. ''')
  946. def test_all_mixed_attributes_and_strings(self):
  947. self.flakes('''
  948. from foo import bar
  949. from foo import baz
  950. __all__ = ['bar', baz.__name__]
  951. ''')
  952. def test_unboundExported(self):
  953. """
  954. If C{__all__} includes a name which is not bound, a warning is emitted.
  955. """
  956. self.flakes('''
  957. __all__ = ["foo"]
  958. ''', m.UndefinedExport)
  959. # Skip this in __init__.py though, since the rules there are a little
  960. # different.
  961. for filename in ["foo/__init__.py", "__init__.py"]:
  962. self.flakes('''
  963. __all__ = ["foo"]
  964. ''', filename=filename)
  965. def test_importStarExported(self):
  966. """
  967. Report undefined if import * is used
  968. """
  969. self.flakes('''
  970. from math import *
  971. __all__ = ['sin', 'cos']
  972. csc(1)
  973. ''', m.ImportStarUsed, m.ImportStarUsage, m.ImportStarUsage, m.ImportStarUsage)
  974. def test_importStarNotExported(self):
  975. """Report unused import when not needed to satisfy __all__."""
  976. self.flakes('''
  977. from foolib import *
  978. a = 1
  979. __all__ = ['a']
  980. ''', m.ImportStarUsed, m.UnusedImport)
  981. def test_usedInGenExp(self):
  982. """
  983. Using a global in a generator expression results in no warnings.
  984. """
  985. self.flakes('import fu; (fu for _ in range(1))')
  986. self.flakes('import fu; (1 for _ in range(1) if fu)')
  987. def test_redefinedByGenExp(self):
  988. """
  989. Re-using a global name as the loop variable for a generator
  990. expression results in a redefinition warning.
  991. """
  992. self.flakes('import fu; (1 for fu in range(1))',
  993. m.RedefinedWhileUnused, m.UnusedImport)
  994. def test_usedAsDecorator(self):
  995. """
  996. Using a global name in a decorator statement results in no warnings,
  997. but using an undefined name in a decorator statement results in an
  998. undefined name warning.
  999. """
  1000. self.flakes('''
  1001. from interior import decorate
  1002. @decorate
  1003. def f():
  1004. return "hello"
  1005. ''')
  1006. self.flakes('''
  1007. from interior import decorate
  1008. @decorate('value')
  1009. def f():
  1010. return "hello"
  1011. ''')
  1012. self.flakes('''
  1013. @decorate
  1014. def f():
  1015. return "hello"
  1016. ''', m.UndefinedName)
  1017. def test_usedAsClassDecorator(self):
  1018. """
  1019. Using an imported name as a class decorator results in no warnings,
  1020. but using an undefined name as a class decorator results in an
  1021. undefined name warning.
  1022. """
  1023. self.flakes('''
  1024. from interior import decorate
  1025. @decorate
  1026. class foo:
  1027. pass
  1028. ''')
  1029. self.flakes('''
  1030. from interior import decorate
  1031. @decorate("foo")
  1032. class bar:
  1033. pass
  1034. ''')
  1035. self.flakes('''
  1036. @decorate
  1037. class foo:
  1038. pass
  1039. ''', m.UndefinedName)