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