2 Tests for various Pyflakes behavior.
5 from sys
import version_info
7 from pyflakes
import messages
as m
8 from pyflakes
.test
.harness
import TestCase
, skip
, skipIf
13 def test_duplicateArgs(self
):
14 self
.flakes('def fu(bar, bar): pass', m
.DuplicateArgument
)
16 def test_localReferencedBeforeAssignment(self
):
22 ''', m
.UndefinedLocal
, m
.UnusedVariable
)
24 def test_redefinedInGenerator(self
):
26 Test that reusing a variable in a generator does not raise
31 (1 for a, b in [(1, 2)])
36 list(1 for a, b in [(1, 2)])
41 (1 for a, b in [(1, 2)])
42 ''', m
.UnusedVariable
)
44 (1 for a, b in [(1, 2)])
45 (1 for a, b in [(1, 2)])
50 (1 for a, b in [(1, 2)])
53 def test_redefinedInSetComprehension(self
):
55 Test that reusing a variable in a set comprehension does not raise
60 {1 for a, b in [(1, 2)]}
65 {1 for a, b in [(1, 2)]}
70 {1 for a, b in [(1, 2)]}
71 ''', m
.UnusedVariable
)
73 {1 for a, b in [(1, 2)]}
74 {1 for a, b in [(1, 2)]}
79 {1 for a, b in [(1, 2)]}
82 def test_redefinedInDictComprehension(self
):
84 Test that reusing a variable in a dict comprehension does not raise
89 {1: 42 for a, b in [(1, 2)]}
94 {1: 42 for a, b in [(1, 2)]}
99 {1: 42 for a, b in [(1, 2)]}
100 ''', m
.UnusedVariable
)
102 {1: 42 for a, b in [(1, 2)]}
103 {1: 42 for a, b in [(1, 2)]}
106 for a, b in [(1, 2)]:
108 {1: 42 for a, b in [(1, 2)]}
111 def test_redefinedFunction(self
):
113 Test that shadowing a function definition with another one raises a
119 ''', m
.RedefinedWhileUnused
)
121 def test_redefined_function_shadows_variable(self
):
125 ''', m
.RedefinedWhileUnused
)
127 def test_redefinedUnderscoreFunction(self
):
129 Test that shadowing a function definition named with underscore doesn't
137 def test_redefinedUnderscoreImportation(self
):
139 Test that shadowing an underscore importation raises a warning.
144 ''', m
.RedefinedWhileUnused
)
146 def test_redefinedClassFunction(self
):
148 Test that shadowing a function definition in a class suite with another
149 one raises a warning.
155 ''', m
.RedefinedWhileUnused
)
157 def test_redefinedIfElseFunction(self
):
159 Test that shadowing a function definition twice in an if
160 and else block does not raise a warning.
169 def test_redefinedIfFunction(self
):
171 Test that shadowing a function definition within an if block
178 ''', m
.RedefinedWhileUnused
)
180 def test_redefinedTryExceptFunction(self
):
182 Test that shadowing a function definition twice in try
183 and except block does not raise a warning.
192 def test_redefinedTryFunction(self
):
194 Test that shadowing a function definition within a try block
203 ''', m
.RedefinedWhileUnused
)
205 def test_redefinedIfElseInListComp(self
):
207 Test that shadowing a variable in a list comprehension in
208 an if and else block does not raise a warning.
217 def test_functionDecorator(self
):
219 Test that shadowing a function definition with a decorated version of
220 that function does not raise a warning.
223 from somewhere import somedecorator
229 def test_classFunctionDecorator(self
):
231 Test that shadowing a function definition in a class suite with a
232 decorated version of that function does not raise a warning.
240 def test_modernProperty(self
):
254 def test_unaryPlus(self
):
255 """Don't die on unary +."""
258 def test_undefinedBaseClass(self
):
260 If a name in the base list of a class definition is undefined, a
266 ''', m
.UndefinedName
)
268 def test_classNameUndefinedInClassBody(self
):
270 If a class name is used in the body of that class's definition and
271 the name is not already defined, a warning is emitted.
276 ''', m
.UndefinedName
)
278 def test_classNameDefinedPreviously(self
):
280 If a class name is used in the body of that class's definition and
281 the name was previously defined in some other way, no warning is
290 def test_classRedefinition(self
):
292 If a class is defined twice in the same module, a warning is emitted.
299 ''', m
.RedefinedWhileUnused
)
301 def test_functionRedefinedAsClass(self
):
303 If a function is redefined as a class, a warning is emitted.
310 ''', m
.RedefinedWhileUnused
)
312 def test_classRedefinedAsFunction(self
):
314 If a class is redefined as a function, a warning is emitted.
321 ''', m
.RedefinedWhileUnused
)
323 def test_classWithReturn(self
):
325 If a return is used inside a class, a warning is emitted.
330 ''', m
.ReturnOutsideFunction
)
332 def test_moduleWithReturn(self
):
334 If a return is used at the module level, a warning is emitted.
338 ''', m
.ReturnOutsideFunction
)
340 def test_classWithYield(self
):
342 If a yield is used inside a class, a warning is emitted.
347 ''', m
.YieldOutsideFunction
)
349 def test_moduleWithYield(self
):
351 If a yield is used at the module level, a warning is emitted.
355 ''', m
.YieldOutsideFunction
)
357 def test_classWithYieldFrom(self
):
359 If a yield from is used inside a class, a warning is emitted.
364 ''', m
.YieldOutsideFunction
)
366 def test_moduleWithYieldFrom(self
):
368 If a yield from is used at the module level, a warning is emitted.
372 ''', m
.YieldOutsideFunction
)
374 def test_continueOutsideLoop(self
):
377 ''', m
.ContinueOutsideLoop
)
382 ''', m
.ContinueOutsideLoop
)
389 ''', m
.ContinueOutsideLoop
)
398 ''', m
.ContinueOutsideLoop
)
404 ''', m
.ContinueOutsideLoop
)
410 ''', m
.ContinueOutsideLoop
)
412 def test_continueInsideLoop(self
):
454 def test_breakOutsideLoop(self
):
457 ''', m
.BreakOutsideLoop
)
462 ''', m
.BreakOutsideLoop
)
469 ''', m
.BreakOutsideLoop
)
478 ''', m
.BreakOutsideLoop
)
484 ''', m
.BreakOutsideLoop
)
490 ''', m
.BreakOutsideLoop
)
497 ''', m
.BreakOutsideLoop
)
499 def test_breakInsideLoop(self
):
559 def test_defaultExceptLast(self
):
561 A default except block should be last.
633 def test_defaultExceptNotLast(self
):
641 ''', m
.DefaultExceptNotLast
)
650 ''', m
.DefaultExceptNotLast
)
661 ''', m
.DefaultExceptNotLast
)
674 ''', m
.DefaultExceptNotLast
, m
.DefaultExceptNotLast
)
685 ''', m
.DefaultExceptNotLast
)
696 ''', m
.DefaultExceptNotLast
)
709 ''', m
.DefaultExceptNotLast
)
724 ''', m
.DefaultExceptNotLast
, m
.DefaultExceptNotLast
)
735 ''', m
.DefaultExceptNotLast
)
746 ''', m
.DefaultExceptNotLast
)
759 ''', m
.DefaultExceptNotLast
)
774 ''', m
.DefaultExceptNotLast
, m
.DefaultExceptNotLast
)
787 ''', m
.DefaultExceptNotLast
)
800 ''', m
.DefaultExceptNotLast
)
815 ''', m
.DefaultExceptNotLast
)
832 ''', m
.DefaultExceptNotLast
, m
.DefaultExceptNotLast
)
834 def test_starredAssignmentNoError(self
):
836 Python 3 extended iterable unpacking
859 (a, *b, c) = range(10)
871 [a, *b, c] = range(10)
874 # Taken from test_unpack_ex.py in the cPython source
875 s
= ", ".join("a%d" % i
for i
in range(1 << 8 - 1)) + \
876 ", *rest = range(1<<8)"
879 s
= "(" + ", ".join("a%d" % i
for i
in range(1 << 8 - 1)) + \
880 ", *rest) = range(1<<8)"
883 s
= "[" + ", ".join("a%d" % i
for i
in range(1 << 8 - 1)) + \
884 ", *rest] = range(1<<8)"
887 def test_starredAssignmentErrors(self
):
889 SyntaxErrors (not encoded in the ast) surrounding Python 3 extended
892 # Taken from test_unpack_ex.py in the cPython source
893 s
= ", ".join("a%d" % i
for i
in range(1 << 8)) + \
894 ", *rest = range(1<<8 + 1)"
895 self
.flakes(s
, m
.TooManyExpressionsInStarredAssignment
)
897 s
= "(" + ", ".join("a%d" % i
for i
in range(1 << 8)) + \
898 ", *rest) = range(1<<8 + 1)"
899 self
.flakes(s
, m
.TooManyExpressionsInStarredAssignment
)
901 s
= "[" + ", ".join("a%d" % i
for i
in range(1 << 8)) + \
902 ", *rest] = range(1<<8 + 1)"
903 self
.flakes(s
, m
.TooManyExpressionsInStarredAssignment
)
905 s
= ", ".join("a%d" % i
for i
in range(1 << 8 + 1)) + \
906 ", *rest = range(1<<8 + 2)"
907 self
.flakes(s
, m
.TooManyExpressionsInStarredAssignment
)
909 s
= "(" + ", ".join("a%d" % i
for i
in range(1 << 8 + 1)) + \
910 ", *rest) = range(1<<8 + 2)"
911 self
.flakes(s
, m
.TooManyExpressionsInStarredAssignment
)
913 s
= "[" + ", ".join("a%d" % i
for i
in range(1 << 8 + 1)) + \
914 ", *rest] = range(1<<8 + 2)"
915 self
.flakes(s
, m
.TooManyExpressionsInStarredAssignment
)
917 # No way we can actually test this!
918 # s = "*rest, " + ", ".join("a%d" % i for i in range(1<<24)) + \
919 # ", *rest = range(1<<24 + 1)"
920 # self.flakes(s, m.TooManyExpressionsInStarredAssignment)
923 a, *b, *c = range(10)
924 ''', m
.TwoStarredExpressions
)
927 a, *b, c, *d = range(10)
928 ''', m
.TwoStarredExpressions
)
931 *a, *b, *c = range(10)
932 ''', m
.TwoStarredExpressions
)
935 (a, *b, *c) = range(10)
936 ''', m
.TwoStarredExpressions
)
939 (a, *b, c, *d) = range(10)
940 ''', m
.TwoStarredExpressions
)
943 (*a, *b, *c) = range(10)
944 ''', m
.TwoStarredExpressions
)
947 [a, *b, *c] = range(10)
948 ''', m
.TwoStarredExpressions
)
951 [a, *b, c, *d] = range(10)
952 ''', m
.TwoStarredExpressions
)
955 [*a, *b, *c] = range(10)
956 ''', m
.TwoStarredExpressions
)
958 @skip("todo: Too hard to make this warn but other cases stay silent")
959 def test_doubleAssignment(self
):
961 If a variable is re-assigned to without being used, no warning is
967 ''', m
.RedefinedWhileUnused
)
969 def test_doubleAssignmentConditionally(self
):
971 If a variable is re-assigned within a conditional, no warning is
980 def test_doubleAssignmentWithUse(self
):
982 If a variable is re-assigned to after being used, no warning is
991 def test_comparison(self
):
993 If a defined name is used on either side of any of the six comparison
994 operators, no warning is emitted.
1007 def test_identity(self
):
1009 If a defined name is used on either side of an identity test, no
1019 def test_containment(self
):
1021 If a defined name is used on either side of a containment test, no
1031 def test_loopControl(self
):
1033 break and continue statements are supported.
1044 def test_ellipsis(self
):
1046 Ellipsis in a slice is supported.
1052 def test_extendedSlice(self
):
1054 Extended slices are supported.
1061 def test_varAugmentedAssignment(self
):
1063 Augmented assignment of a variable is supported.
1064 We don't care about var refs.
1071 def test_attrAugmentedAssignment(self
):
1073 Augmented assignment of attributes is supported.
1074 We don't care about attr refs.
1081 def test_globalDeclaredInDifferentScope(self
):
1083 A 'global' can be declared in one scope and reused in another.
1087 def g(): foo = 'anything'; foo.is_used()
1090 def test_function_arguments(self
):
1092 Test to traverse ARG and ARGUMENT handler
1105 def foo(a, b, c=0, *args):
1110 def foo(a, b, c=0, *args, **kwargs):
1114 def test_function_arguments_python3(self
):
1116 def foo(a, b, c=0, *args, d=0, **kwargs):
1121 class TestUnusedAssignment(TestCase
):
1123 Tests for warning about unused assignments.
1126 def test_unusedVariable(self
):
1128 Warn when a variable in a function is assigned a value that's never
1134 ''', m
.UnusedVariable
)
1136 def test_unusedUnderscoreVariable(self
):
1138 Don't warn when the magic "_" (underscore) variable is unused.
1142 def a(unused_param):
1146 def test_unusedVariableAsLocals(self
):
1148 Using locals() it is perfectly valid to have unused variables
1156 def test_unusedVariableNoLocals(self
):
1158 Using locals() in wrong scope should not matter
1166 ''', m
.UnusedVariable
)
1168 @skip("todo: Difficult because it doesn't apply in the context of a loop")
1169 def test_unusedReassignedVariable(self
):
1171 Shadowing a used variable can still raise an UnusedVariable warning.
1178 ''', m
.UnusedVariable
)
1180 def test_variableUsedInLoop(self
):
1182 Shadowing a used variable cannot raise an UnusedVariable warning in the
1192 def test_assignToGlobal(self
):
1194 Assigning to a global and then not using that global is perfectly
1195 acceptable. Do not mistake it for an unused local variable.
1204 def test_assignToNonlocal(self
):
1206 Assigning to a nonlocal and then not using that binding is perfectly
1207 acceptable. Do not mistake it for an unused local variable.
1216 def test_assignToMember(self
):
1218 Assigning to a member of another object and then not using that member
1219 variable is perfectly acceptable. Do not mistake it for an unused
1222 # XXX: Adding this test didn't generate a failure. Maybe not
1231 def test_assignInForLoop(self
):
1233 Don't warn when a variable in a for loop is assigned to but not used.
1241 def test_assignInListComprehension(self
):
1243 Don't warn when a variable in a list comprehension is
1244 assigned to but not used.
1248 [None for i in range(10)]
1251 def test_generatorExpression(self
):
1253 Don't warn when a variable in a generator expression is
1254 assigned to but not used.
1258 (None for i in range(10))
1261 def test_assignmentInsideLoop(self
):
1263 Don't warn when a variable assignment occurs lexically after its use.
1274 def test_tupleUnpacking(self
):
1276 Don't warn when a variable included in tuple unpacking is unused. It's
1277 very common for variables in a tuple unpacking assignment to be unused
1278 in good Python code, so warning will only create false positives.
1287 ''', m
.UnusedVariable
, m
.UnusedVariable
)
1290 (x, y) = coords = 1, 2
1296 (x, y) = coords = 1, 2
1297 ''', m
.UnusedVariable
)
1300 coords = (x, y) = 1, 2
1301 ''', m
.UnusedVariable
)
1303 def test_listUnpacking(self
):
1305 Don't warn when a variable included in list unpacking is unused.
1314 ''', m
.UnusedVariable
, m
.UnusedVariable
)
1316 def test_closedOver(self
):
1318 Don't warn when the assignment is used in an inner function.
1328 def test_doubleClosedOver(self
):
1330 Don't warn when the assignment is used in an inner function, even if
1331 that inner function itself is in an inner function.
1342 def test_tracebackhideSpecialVariable(self
):
1344 Do not warn about unused local variable __tracebackhide__, which is
1345 a special variable for py.test.
1349 __tracebackhide__ = True
1352 def test_ifexp(self
):
1354 Test C{foo if bar else baz} statements.
1356 self
.flakes("a = 'moo' if True else 'oink'")
1357 self
.flakes("a = foo if True else 'oink'", m
.UndefinedName
)
1358 self
.flakes("a = 'moo' if True else bar", m
.UndefinedName
)
1360 def test_if_tuple(self
):
1362 Test C{if (foo,)} conditions.
1364 self
.flakes("""if (): pass""")
1383 def test_withStatementNoNames(self
):
1385 No warnings are emitted for using inside or after a nameless C{with}
1386 statement a name defined beforehand.
1395 def test_withStatementSingleName(self
):
1397 No warnings are emitted for using a name defined by a C{with} statement
1398 within the suite or afterwards.
1401 with open('foo') as bar:
1406 def test_withStatementAttributeName(self
):
1408 No warnings are emitted for using an attribute as the target of a
1413 with open('foo') as foo.bar:
1417 def test_withStatementSubscript(self
):
1419 No warnings are emitted for using a subscript as the target of a
1424 with open('foo') as foo[0]:
1428 def test_withStatementSubscriptUndefined(self
):
1430 An undefined name warning is emitted if the subscript used as the
1431 target of a C{with} statement is not defined.
1435 with open('foo') as foo[bar]:
1437 ''', m
.UndefinedName
)
1439 def test_withStatementTupleNames(self
):
1441 No warnings are emitted for using any of the tuple of names defined by
1442 a C{with} statement within the suite or afterwards.
1445 with open('foo') as (bar, baz):
1450 def test_withStatementListNames(self
):
1452 No warnings are emitted for using any of the list of names defined by a
1453 C{with} statement within the suite or afterwards.
1456 with open('foo') as [bar, baz]:
1461 def test_withStatementComplicatedTarget(self
):
1463 If the target of a C{with} statement uses any or all of the valid forms
1464 for that part of the grammar (See
1465 U{http://docs.python.org/reference/compound_stmts.html#the-with-statement}),
1466 the names involved are checked both for definedness and any bindings
1467 created are respected in the suite of the statement and afterwards.
1470 c = d = e = g = h = i = None
1471 with open('foo') as [(a, b), c[d], e.f, g[h:i]]:
1472 a, b, c, d, e, g, h, i
1473 a, b, c, d, e, g, h, i
1476 def test_withStatementSingleNameUndefined(self
):
1478 An undefined name warning is emitted if the name first defined by a
1479 C{with} statement is used before the C{with} statement.
1483 with open('foo') as bar:
1485 ''', m
.UndefinedName
)
1487 def test_withStatementTupleNamesUndefined(self
):
1489 An undefined name warning is emitted if a name first defined by the
1490 tuple-unpacking form of the C{with} statement is used before the
1495 with open('foo') as (bar, baz):
1497 ''', m
.UndefinedName
)
1499 def test_withStatementSingleNameRedefined(self
):
1501 A redefined name warning is emitted if a name bound by an import is
1502 rebound by the name defined by a C{with} statement.
1506 with open('foo') as bar:
1508 ''', m
.RedefinedWhileUnused
)
1510 def test_withStatementTupleNamesRedefined(self
):
1512 A redefined name warning is emitted if a name bound by an import is
1513 rebound by one of the names defined by the tuple-unpacking form of a
1518 with open('foo') as (bar, baz):
1520 ''', m
.RedefinedWhileUnused
)
1522 def test_withStatementUndefinedInside(self
):
1524 An undefined name warning is emitted if a name is used inside the
1525 body of a C{with} statement without first being bound.
1528 with open('foo') as bar:
1530 ''', m
.UndefinedName
)
1532 def test_withStatementNameDefinedInBody(self
):
1534 A name defined in the body of a C{with} statement can be used after
1535 the body ends without warning.
1538 with open('foo') as bar:
1543 def test_withStatementUndefinedInExpression(self
):
1545 An undefined name warning is emitted if a name in the I{test}
1546 expression of a C{with} statement is undefined.
1551 ''', m
.UndefinedName
)
1556 ''', m
.UndefinedName
)
1558 def test_dictComprehension(self
):
1560 Dict comprehensions are properly handled.
1563 a = {1: x for x in range(10)}
1566 def test_setComprehensionAndLiteral(self
):
1568 Set comprehensions are properly handled.
1572 b = {x for x in range(10)}
1575 def test_exceptionUsedInExcept(self
):
1578 except Exception as e: e
1582 def download_review():
1584 except Exception as e: e
1587 def test_exceptionUnusedInExcept(self
):
1590 except Exception as e: pass
1591 ''', m
.UnusedVariable
)
1593 @skipIf(version_info
< (3, 11), 'new in Python 3.11')
1594 def test_exception_unused_in_except_star(self
):
1598 except* OSError as e:
1600 ''', m
.UnusedVariable
)
1602 def test_exceptionUnusedInExceptInFunction(self
):
1604 def download_review():
1606 except Exception as e: pass
1607 ''', m
.UnusedVariable
)
1609 def test_exceptWithoutNameInFunction(self
):
1611 Don't issue false warning when an unnamed exception is used.
1612 Previously, there would be a false warning, but only when the
1613 try..except was in a function
1619 except tokenize.TokenError: pass
1622 def test_exceptWithoutNameInFunctionTuple(self
):
1624 Don't issue false warning when an unnamed exception is used.
1625 This example catches a tuple of exception types.
1631 except (tokenize.TokenError, IndentationError): pass
1634 def test_augmentedAssignmentImportedFunctionCall(self
):
1636 Consider a function that is called on the right part of an
1637 augassign operation to be used.
1645 def test_assert_without_message(self
):
1646 """An assert without a message is not an error."""
1652 def test_assert_with_message(self
):
1653 """An assert with a message is not an error."""
1659 def test_assert_tuple(self
):
1660 """An assert of a non-empty tuple is always True."""
1664 ''', m
.AssertTuple
, m
.AssertTuple
)
1666 def test_assert_tuple_empty(self
):
1667 """An assert of an empty tuple is always False."""
1672 def test_assert_static(self
):
1673 """An assert of a static value is not an error."""
1679 def test_yieldFromUndefined(self
):
1681 Test C{yield from} statement
1686 ''', m
.UndefinedName
)
1688 def test_f_string(self
):
1689 """Test PEP 498 f-strings are treated as a usage."""
1692 print(f'\x7b4*baz\N{RIGHT CURLY BRACKET}')
1695 def test_assign_expr(self
):
1696 """Test PEP 572 assignment expressions are treated as usage / write."""
1703 def test_assign_expr_generator_scope(self
):
1704 """Test assignment expressions in generator expressions."""
1706 if (any((y := x[0]) for x in [[True]])):
1710 def test_assign_expr_nested(self
):
1711 """Test assignment expressions in nested expressions."""
1713 if ([(y:=x) for x in range(4) if [(z:=q) for q in range(4)]]):
1719 class TestStringFormatting(TestCase
):
1721 def test_f_string_without_placeholders(self
):
1722 self
.flakes("f'foo'", m
.FStringMissingPlaceholders
)
1727 ''', m
.FStringMissingPlaceholders
)
1733 ''', m
.FStringMissingPlaceholders
)
1734 # this is an "escaped placeholder" but not a placeholder
1735 self
.flakes("f'{{}}'", m
.FStringMissingPlaceholders
)
1736 # ok: f-string with placeholders
1741 # ok: f-string with format specifiers
1746 # ok: f-string with multiple format specifiers
1749 print(f'{x:>2} {y:>2}')
1752 def test_invalid_dot_format_calls(self
):
1755 ''', m
.StringDotFormatInvalidFormat
)
1757 '{} {1}'.format(1, 2)
1758 ''', m
.StringDotFormatMixingAutomatic
)
1760 '{0} {}'.format(1, 2)
1761 ''', m
.StringDotFormatMixingAutomatic
)
1764 ''', m
.StringDotFormatExtraPositionalArguments
)
1766 '{}'.format(1, bar=2)
1767 ''', m
.StringDotFormatExtraNamedArguments
)
1770 ''', m
.StringDotFormatMissingArgument
)
1773 ''', m
.StringDotFormatMissingArgument
)
1776 ''', m
.StringDotFormatMissingArgument
)
1777 # too much string recursion (placeholder-in-placeholder)
1779 '{:{:{}}}'.format(1, 2, 3)
1780 ''', m
.StringDotFormatInvalidFormat
)
1781 # ok: dotted / bracketed names need to handle the param differently
1782 self
.flakes("'{.__class__}'.format('')")
1783 self
.flakes("'{foo[bar]}'.format(foo={'bar': 'barv'})")
1784 # ok: placeholder-placeholders
1786 print('{:{}} {}'.format(1, 15, 2))
1788 # ok: not a placeholder-placeholder
1790 print('{:2}'.format(1))
1792 # ok: not mixed automatic
1794 '{foo}-{}'.format(1, foo=2)
1796 # ok: we can't determine statically the format args
1806 def test_invalid_percent_format_calls(self
):
1808 '%(foo)' % {'foo': 'bar'}
1809 ''', m
.PercentFormatInvalidFormat
)
1811 '%s %(foo)s' % {'foo': 'bar'}
1812 ''', m
.PercentFormatMixedPositionalAndNamed
)
1814 '%(foo)s %s' % {'foo': 'bar'}
1815 ''', m
.PercentFormatMixedPositionalAndNamed
)
1818 ''', m
.PercentFormatUnsupportedFormatCharacter
)
1821 ''', m
.PercentFormatPositionalCountMismatch
)
1824 ''', m
.PercentFormatPositionalCountMismatch
)
1827 ''', m
.PercentFormatMissingArgument
,)
1829 '%(bar)s' % {'bar': 1, 'baz': 2}
1830 ''', m
.PercentFormatExtraNamedArguments
)
1832 '%(bar)s' % (1, 2, 3)
1833 ''', m
.PercentFormatExpectedMapping
)
1835 '%s %s' % {'k': 'v'}
1836 ''', m
.PercentFormatExpectedSequence
)
1838 '%(bar)*s' % {'bar': 'baz'}
1839 ''', m
.PercentFormatStarRequiresSequence
)
1840 # ok: single %s with mapping
1842 '%s' % {'foo': 'bar', 'baz': 'womp'}
1844 # ok: does not cause a MemoryError (the strings aren't evaluated)
1846 "%1000000000000f" % 1
1848 # ok: %% should not count towards placeholder count
1850 '%% %s %% %s' % (1, 2)
1852 # ok: * consumes one positional argument
1854 '%.*f' % (2, 1.1234)
1855 '%*.*f' % (5, 2, 3.1234)
1858 def test_ok_percent_format_cannot_determine_element_count(self
):
1870 class TestAsyncStatements(TestCase
):
1872 def test_asyncDef(self
):
1878 def test_asyncDefAwait(self
):
1880 async def read_data(db):
1881 await db.fetch('SELECT ...')
1884 def test_asyncDefUndefined(self
):
1888 ''', m
.UndefinedName
)
1890 def test_asyncFor(self
):
1892 async def read_data(db):
1894 async for row in db.cursor():
1899 def test_asyncForUnderscoreLoopVar(self
):
1906 def test_loopControlInAsyncFor(self
):
1908 async def read_data(db):
1910 async for row in db.cursor():
1911 if row[0] == 'skip':
1918 async def read_data(db):
1920 async for row in db.cursor():
1921 if row[0] == 'stop':
1927 def test_loopControlInAsyncForElse(self
):
1929 async def read_data(db):
1931 async for row in db.cursor():
1936 ''', m
.ContinueOutsideLoop
)
1939 async def read_data(db):
1941 async for row in db.cursor():
1946 ''', m
.BreakOutsideLoop
)
1948 def test_asyncWith(self
):
1950 async def commit(session, data):
1951 async with session.transaction():
1952 await session.update(data)
1955 def test_asyncWithItem(self
):
1957 async def commit(session, data):
1958 async with session.transaction() as trans:
1964 def test_matmul(self
):
1970 def test_formatstring(self
):
1977 def test_raise_notimplemented(self
):
1979 raise NotImplementedError("This is fine")
1983 raise NotImplementedError
1987 raise NotImplemented("This isn't gonna work")
1988 ''', m
.RaiseNotImplemented
)
1991 raise NotImplemented
1992 ''', m
.RaiseNotImplemented
)
1995 class TestIncompatiblePrintOperator(TestCase
):
1997 Tests for warning about invalid use of print function.
2000 def test_valid_print(self
):
2005 def test_invalid_print_when_imported_from_future(self
):
2006 exc
= self
.flakes('''
2007 from __future__ import print_function
2009 print >>sys.stderr, "Hello"
2010 ''', m
.InvalidPrintSyntax
).messages
[0]
2012 self
.assertEqual(exc
.lineno
, 4)
2013 self
.assertEqual(exc
.col
, 0)
2015 def test_print_augmented_assign(self
):
2016 # nonsense, but shouldn't crash pyflakes
2017 self
.flakes('print += 1')
2019 def test_print_function_assignment(self
):
2021 A valid assignment, tested for catching false positives.
2024 from __future__ import print_function
2029 def test_print_in_lambda(self
):
2031 from __future__ import print_function
2035 def test_print_returned_in_function(self
):
2037 from __future__ import print_function
2042 def test_print_as_condition_test(self
):
2044 from __future__ import print_function