Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes
test.test_grammar.GrammarTests Class Reference

List of all members.

Public Member Functions

def testEvalInput
def testFuncdef
def testLambdef
def testSimpleStmt
 stmt: simple_stmt | compound_stmt Tested below
def testExprStmt
 small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt Tested below
def testDelStmt
def testPassStmt
def testBreakStmt
def testContinueStmt
def test_break_continue_loop
def testReturn
def testYield
def testRaise
def testImport
def testGlobal
def testNonlocal
def testAssert
def testIf
 compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef Tested below
def testWhile
def testFor
def testTry
def testSuite
def testTest
def testComparison
def testBinaryMaskOps
def testShiftOps
def testAdditiveOps
def testMultiplicativeOps
def testUnaryOps
def testSelectors
def testAtoms
def testClassdef
 exprlist: expr (',' expr)* [','] testlist: test (',' test)* [','] These have been exercised enough above
def testDictcomps
def testListcomps
def testGenexps
def testComprehensionSpecials
def test_with_statement
def testIfElseExpr
def test_paren_evaluation

Public Attributes

 max
 sofar

Detailed Description

Definition at line 128 of file test_grammar.py.


Member Function Documentation

Definition at line 419 of file test_grammar.py.

00419 
00420     def test_break_continue_loop(self):
00421         # This test warrants an explanation. It is a test specifically for SF bugs
00422         # #463359 and #462937. The bug is that a 'break' statement executed or
00423         # exception raised inside a try/except inside a loop, *after* a continue
00424         # statement has been executed in that loop, will cause the wrong number of
00425         # arguments to be popped off the stack and the instruction pointer reset to
00426         # a very small number (usually 0.) Because of this, the following test
00427         # *must* written as a function, and the tracking vars *must* be function
00428         # arguments with default values. Otherwise, the test will loop and loop.
00429 
00430         def test_inner(extra_burning_oil = 1, count=0):
00431             big_hippo = 2
00432             while big_hippo:
00433                 count += 1
00434                 try:
00435                     if extra_burning_oil and big_hippo == 1:
00436                         extra_burning_oil -= 1
00437                         break
00438                     big_hippo -= 1
00439                     continue
00440                 except:
00441                     raise
00442             if count > 2 or big_hippo != 1:
00443                 self.fail("continue then break in try/except in loop broken!")
00444         test_inner()

Here is the call graph for this function:

Definition at line 912 of file test_grammar.py.

00912 
00913     def test_paren_evaluation(self):
00914         self.assertEqual(16 // (4 // 2), 8)
00915         self.assertEqual((16 // 4) // 2, 2)
00916         self.assertEqual(16 // 4 // 2, 2)
00917         self.assertTrue(False is (2 is 3))
00918         self.assertFalse((False is 2) is 3)
00919         self.assertFalse(False is 2 is 3)
00920 

Here is the call graph for this function:

Definition at line 865 of file test_grammar.py.

00865 
00866     def test_with_statement(self):
00867         class manager(object):
00868             def __enter__(self):
00869                 return (1, 2)
00870             def __exit__(self, *args):
00871                 pass
00872 
00873         with manager():
00874             pass
00875         with manager() as x:
00876             pass
00877         with manager() as (x, y):
00878             pass
00879         with manager(), manager():
00880             pass
00881         with manager() as x, manager() as y:
00882             pass
00883         with manager() as x, manager():
00884             pass

Here is the call graph for this function:

Definition at line 638 of file test_grammar.py.

00638 
00639     def testAdditiveOps(self):
00640         x = 1
00641         x = 1 + 1
00642         x = 1 - 1 - 1
00643         x = 1 - 1 + 1 - 1 + 1

Definition at line 490 of file test_grammar.py.

00490 
00491     def testAssert(self):
00492         # assertTruestmt: 'assert' test [',' test]
00493         assert 1
00494         assert 1, 1
00495         assert lambda x:x
00496         assert 1, lambda x:x+1
00497         try:
00498             assert 0, "msg"
00499         except AssertionError as e:
00500             self.assertEqual(e.args[0], "msg")
00501         else:
00502             if __debug__:
00503                 self.fail("AssertionError not raised by assert 0")

Here is the call graph for this function:

Definition at line 687 of file test_grammar.py.

00687 
00688     def testAtoms(self):
00689         ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
00690         ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
00691 
00692         x = (1)
00693         x = (1 or 2 or 3)
00694         x = (1 or 2 or 3, 2, 3)
00695 
00696         x = []
00697         x = [1]
00698         x = [1 or 2 or 3]
00699         x = [1 or 2 or 3, 2, 3]
00700         x = []
00701 
00702         x = {}
00703         x = {'one': 1}
00704         x = {'one': 1,}
00705         x = {'one' or 'two': 1 or 2}
00706         x = {'one': 1, 'two': 2}
00707         x = {'one': 1, 'two': 2,}
00708         x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
00709 
00710         x = {'one'}
00711         x = {'one', 1,}
00712         x = {'one', 'two', 'three'}
00713         x = {2, 3, 4,}
00714 
00715         x = x
00716         x = 'x'
00717         x = 123

Definition at line 628 of file test_grammar.py.

00628 
00629     def testBinaryMaskOps(self):
00630         x = 1 & 1
00631         x = 1 ^ 1
00632         x = 1 | 1

Definition at line 389 of file test_grammar.py.

00389 
00390     def testBreakStmt(self):
00391         # 'break'
00392         while 1: break

exprlist: expr (',' expr)* [','] testlist: test (',' test)* [','] These have been exercised enough above

Definition at line 722 of file test_grammar.py.

00722 
00723     def testClassdef(self):
00724         # 'class' NAME ['(' [testlist] ')'] ':' suite
00725         class B: pass
00726         class B2(): pass
00727         class C1(B): pass
00728         class C2(B): pass
00729         class D(C1, C2, B): pass
00730         class C:
00731             def meth1(self): pass
00732             def meth2(self, arg): pass
00733             def meth3(self, a1, a2): pass
00734 
00735         # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
00736         # decorators: decorator+
00737         # decorated: decorators (classdef | funcdef)
00738         def class_decorator(x): return x
00739         @class_decorator
00740         class G: pass

Definition at line 611 of file test_grammar.py.

00611 
00612     def testComparison(self):
00613         ### comparison: expr (comp_op expr)*
00614         ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
00615         if 1: pass
00616         x = (1 == 1)
00617         if 1 == 1: pass
00618         if 1 != 1: pass
00619         if 1 < 1: pass
00620         if 1 > 1: pass
00621         if 1 <= 1: pass
00622         if 1 >= 1: pass
00623         if 1 is 1: pass
00624         if 1 is not 1: pass
00625         if 1 in (): pass
00626         if 1 not in (): pass
00627         if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass

Definition at line 846 of file test_grammar.py.

00846 
00847     def testComprehensionSpecials(self):
00848         # test for outmost iterable precomputation
00849         x = 10; g = (i for i in range(x)); x = 5
00850         self.assertEqual(len(list(g)), 10)
00851 
00852         # This should hold, since we're only precomputing outmost iterable.
00853         x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
00854         x = 5; t = True;
00855         self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
00856 
00857         # Grammar allows multiple adjacent 'if's in listcomps and genexps,
00858         # even though it's silly. Make sure it works (ifelse broke this.)
00859         self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
00860         self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
00861 
00862         # verify unpacking single element tuples in listcomp/genexp.
00863         self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
00864         self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])

Here is the call graph for this function:

Definition at line 393 of file test_grammar.py.

00393 
00394     def testContinueStmt(self):
00395         # 'continue'
00396         i = 1
00397         while i: i = 0; continue
00398 
00399         msg = ""
00400         while not msg:
00401             msg = "ok"
00402             try:
00403                 continue
00404                 msg = "continue failed to continue inside try"
00405             except:
00406                 msg = "continue inside try called except block"
00407         if msg != "ok":
00408             self.fail(msg)
00409 
00410         msg = ""
00411         while not msg:
00412             msg = "finally block not called"
00413             try:
00414                 continue
00415             finally:
00416                 msg = "ok"
00417         if msg != "ok":
00418             self.fail(msg)

Here is the call graph for this function:

Definition at line 373 of file test_grammar.py.

00373 
00374     def testDelStmt(self):
00375         # 'del' exprlist
00376         abc = [1,2,3]
00377         x, y, z = abc
00378         xyz = x, y, z
00379 
00380         del abc
00381         del x, y, (z, xyz)

Definition at line 741 of file test_grammar.py.

00741 
00742     def testDictcomps(self):
00743         # dictorsetmaker: ( (test ':' test (comp_for |
00744         #                                   (',' test ':' test)* [','])) |
00745         #                   (test (comp_for | (',' test)* [','])) )
00746         nums = [1, 2, 3]
00747         self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})

Here is the call graph for this function:

Definition at line 139 of file test_grammar.py.

00139 
00140     def testEvalInput(self):
00141         # testlist ENDMARKER
00142         x = eval('1, 0 or 1')

small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt Tested below

Definition at line 360 of file test_grammar.py.

00360 
00361     def testExprStmt(self):
00362         # (exprlist '=')* exprlist
00363         1
00364         1, 2, 3
00365         x = 1
00366         x = 1, 2, 3
00367         x = y = z = 1, 2, 3
00368         x, y, z = 1, 2, 3
00369         abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
00370 
00371         check_syntax_error(self, "x + 1 = 1")
00372         check_syntax_error(self, "a + 1 = b + 2")

Here is the call graph for this function:

Definition at line 535 of file test_grammar.py.

00535 
00536     def testFor(self):
00537         # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
00538         for i in 1, 2, 3: pass
00539         for i, j, k in (): pass
00540         else: pass
00541         class Squares:
00542             def __init__(self, max):
00543                 self.max = max
00544                 self.sofar = []
00545             def __len__(self): return len(self.sofar)
00546             def __getitem__(self, i):
00547                 if not 0 <= i < self.max: raise IndexError
00548                 n = len(self.sofar)
00549                 while n <= i:
00550                     self.sofar.append(n*n)
00551                     n = n+1
00552                 return self.sofar[i]
00553         n = 0
00554         for x in Squares(10): n = n+x
00555         if n != 285:
00556             self.fail('for over growing sequence')
00557 
00558         result = []
00559         for x, in [(1,), (2,), (3,)]:
00560             result.append(x)
00561         self.assertEqual(result, [1, 2, 3])

Here is the call graph for this function:

Definition at line 143 of file test_grammar.py.

00143 
00144     def testFuncdef(self):
00145         ### [decorators] 'def' NAME parameters ['->' test] ':' suite
00146         ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
00147         ### decorators: decorator+
00148         ### parameters: '(' [typedargslist] ')'
00149         ### typedargslist: ((tfpdef ['=' test] ',')*
00150         ###                ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
00151         ###                | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
00152         ### tfpdef: NAME [':' test]
00153         ### varargslist: ((vfpdef ['=' test] ',')*
00154         ###              ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] | '**' vfpdef)
00155         ###              | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
00156         ### vfpdef: NAME
00157         def f1(): pass
00158         f1()
00159         f1(*())
00160         f1(*(), **{})
00161         def f2(one_argument): pass
00162         def f3(two, arguments): pass
00163         self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
00164         self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
00165         def a1(one_arg,): pass
00166         def a2(two, args,): pass
00167         def v0(*rest): pass
00168         def v1(a, *rest): pass
00169         def v2(a, b, *rest): pass
00170 
00171         f1()
00172         f2(1)
00173         f2(1,)
00174         f3(1, 2)
00175         f3(1, 2,)
00176         v0()
00177         v0(1)
00178         v0(1,)
00179         v0(1,2)
00180         v0(1,2,3,4,5,6,7,8,9,0)
00181         v1(1)
00182         v1(1,)
00183         v1(1,2)
00184         v1(1,2,3)
00185         v1(1,2,3,4,5,6,7,8,9,0)
00186         v2(1,2)
00187         v2(1,2,3)
00188         v2(1,2,3,4)
00189         v2(1,2,3,4,5,6,7,8,9,0)
00190 
00191         def d01(a=1): pass
00192         d01()
00193         d01(1)
00194         d01(*(1,))
00195         d01(**{'a':2})
00196         def d11(a, b=1): pass
00197         d11(1)
00198         d11(1, 2)
00199         d11(1, **{'b':2})
00200         def d21(a, b, c=1): pass
00201         d21(1, 2)
00202         d21(1, 2, 3)
00203         d21(*(1, 2, 3))
00204         d21(1, *(2, 3))
00205         d21(1, 2, *(3,))
00206         d21(1, 2, **{'c':3})
00207         def d02(a=1, b=2): pass
00208         d02()
00209         d02(1)
00210         d02(1, 2)
00211         d02(*(1, 2))
00212         d02(1, *(2,))
00213         d02(1, **{'b':2})
00214         d02(**{'a': 1, 'b': 2})
00215         def d12(a, b=1, c=2): pass
00216         d12(1)
00217         d12(1, 2)
00218         d12(1, 2, 3)
00219         def d22(a, b, c=1, d=2): pass
00220         d22(1, 2)
00221         d22(1, 2, 3)
00222         d22(1, 2, 3, 4)
00223         def d01v(a=1, *rest): pass
00224         d01v()
00225         d01v(1)
00226         d01v(1, 2)
00227         d01v(*(1, 2, 3, 4))
00228         d01v(*(1,))
00229         d01v(**{'a':2})
00230         def d11v(a, b=1, *rest): pass
00231         d11v(1)
00232         d11v(1, 2)
00233         d11v(1, 2, 3)
00234         def d21v(a, b, c=1, *rest): pass
00235         d21v(1, 2)
00236         d21v(1, 2, 3)
00237         d21v(1, 2, 3, 4)
00238         d21v(*(1, 2, 3, 4))
00239         d21v(1, 2, **{'c': 3})
00240         def d02v(a=1, b=2, *rest): pass
00241         d02v()
00242         d02v(1)
00243         d02v(1, 2)
00244         d02v(1, 2, 3)
00245         d02v(1, *(2, 3, 4))
00246         d02v(**{'a': 1, 'b': 2})
00247         def d12v(a, b=1, c=2, *rest): pass
00248         d12v(1)
00249         d12v(1, 2)
00250         d12v(1, 2, 3)
00251         d12v(1, 2, 3, 4)
00252         d12v(*(1, 2, 3, 4))
00253         d12v(1, 2, *(3, 4, 5))
00254         d12v(1, *(2,), **{'c': 3})
00255         def d22v(a, b, c=1, d=2, *rest): pass
00256         d22v(1, 2)
00257         d22v(1, 2, 3)
00258         d22v(1, 2, 3, 4)
00259         d22v(1, 2, 3, 4, 5)
00260         d22v(*(1, 2, 3, 4))
00261         d22v(1, 2, *(3, 4, 5))
00262         d22v(1, *(2, 3), **{'d': 4})
00263 
00264         # keyword argument type tests
00265         try:
00266             str('x', **{b'foo':1 })
00267         except TypeError:
00268             pass
00269         else:
00270             self.fail('Bytes should not work as keyword argument names')
00271         # keyword only argument tests
00272         def pos0key1(*, key): return key
00273         pos0key1(key=100)
00274         def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
00275         pos2key2(1, 2, k1=100)
00276         pos2key2(1, 2, k1=100, k2=200)
00277         pos2key2(1, 2, k2=100, k1=200)
00278         def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
00279         pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
00280         pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
00281 
00282         # keyword arguments after *arglist
00283         def f(*args, **kwargs):
00284             return args, kwargs
00285         self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
00286                                                     {'x':2, 'y':5}))
00287         self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
00288         self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
00289 
00290         # argument annotation tests
00291         def f(x) -> list: pass
00292         self.assertEqual(f.__annotations__, {'return': list})
00293         def f(x:int): pass
00294         self.assertEqual(f.__annotations__, {'x': int})
00295         def f(*x:str): pass
00296         self.assertEqual(f.__annotations__, {'x': str})
00297         def f(**x:float): pass
00298         self.assertEqual(f.__annotations__, {'x': float})
00299         def f(x, y:1+2): pass
00300         self.assertEqual(f.__annotations__, {'y': 3})
00301         def f(a, b:1, c:2, d): pass
00302         self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
00303         def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
00304         self.assertEqual(f.__annotations__,
00305                           {'b': 1, 'c': 2, 'e': 3, 'g': 6})
00306         def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
00307               **k:11) -> 12: pass
00308         self.assertEqual(f.__annotations__,
00309                           {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
00310                            'k': 11, 'return': 12})
00311         # Check for SF Bug #1697248 - mixing decorators and a return annotation
00312         def null(x): return x
00313         @null
00314         def f(x) -> list: pass
00315         self.assertEqual(f.__annotations__, {'return': list})
00316 
00317         # test MAKE_CLOSURE with a variety of oparg's
00318         closure = 1
00319         def f(): return closure
00320         def f(x=1): return closure
00321         def f(*, k=1): return closure
00322         def f() -> int: return closure
00323 
00324         # Check ast errors in *args and *kwargs
00325         check_syntax_error(self, "f(*g(1=2))")
00326         check_syntax_error(self, "f(**g(1=2))")

Here is the call graph for this function:

Definition at line 811 of file test_grammar.py.

00811 
00812     def testGenexps(self):
00813         # generator expression tests
00814         g = ([x for x in range(10)] for x in range(1))
00815         self.assertEqual(next(g), [x for x in range(10)])
00816         try:
00817             next(g)
00818             self.fail('should produce StopIteration exception')
00819         except StopIteration:
00820             pass
00821 
00822         a = 1
00823         try:
00824             g = (a for d in a)
00825             next(g)
00826             self.fail('should produce TypeError')
00827         except TypeError:
00828             pass
00829 
00830         self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
00831         self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
00832 
00833         a = [x for x in range(10)]
00834         b = (x for x in (y for y in a))
00835         self.assertEqual(sum(b), sum([x for x in range(10)]))
00836 
00837         self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
00838         self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
00839         self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
00840         self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
00841         self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
00842         self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
00843         self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
00844         check_syntax_error(self, "foo(x for x in range(10), 100)")
00845         check_syntax_error(self, "foo(100, x for x in range(10))")

Here is the call graph for this function:

Definition at line 476 of file test_grammar.py.

00476 
00477     def testGlobal(self):
00478         # 'global' NAME (',' NAME)*
00479         global a
00480         global a, b
00481         global one, two, three, four, five, six, seven, eight, nine, ten

compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef Tested below

Definition at line 507 of file test_grammar.py.

00507 
00508     def testIf(self):
00509         # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
00510         if 1: pass
00511         if 1: pass
00512         else: pass
00513         if 0: pass
00514         elif 0: pass
00515         if 0: pass
00516         elif 0: pass
00517         elif 0: pass
00518         elif 0: pass
00519         else: pass

Definition at line 885 of file test_grammar.py.

00885 
00886     def testIfElseExpr(self):
00887         # Test ifelse expressions in various cases
00888         def _checkeval(msg, ret):
00889             "helper to check that evaluation of expressions is done correctly"
00890             print(x)
00891             return ret
00892 
00893         # the next line is not allowed anymore
00894         #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
00895         self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
00896         self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
00897         self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
00898         self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
00899         self.assertEqual((5 and 6 if 0 else 1), 1)
00900         self.assertEqual(((5 and 6) if 0 else 1), 1)
00901         self.assertEqual((5 and (6 if 1 else 1)), 6)
00902         self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
00903         self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
00904         self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
00905         self.assertEqual((not 5 if 1 else 1), False)
00906         self.assertEqual((not 5 if 0 else 1), 1)
00907         self.assertEqual((6 + 1 if 1 else 2), 7)
00908         self.assertEqual((6 - 1 if 1 else 2), 5)
00909         self.assertEqual((6 * 2 if 1 else 4), 12)
00910         self.assertEqual((6 / 2 if 1 else 3), 3)
00911         self.assertEqual((6 < 4 if 0 else 2), 2)

Here is the call graph for this function:

Definition at line 463 of file test_grammar.py.

00463 
00464     def testImport(self):
00465         # 'import' dotted_as_names
00466         import sys
00467         import time, sys
00468         # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
00469         from time import time
00470         from time import (time)
00471         # not testable inside a function, but already done at top of the module
00472         # from sys import *
00473         from sys import path, argv
00474         from sys import (path, argv)
00475         from sys import (path, argv,)

Definition at line 327 of file test_grammar.py.

00327 
00328     def testLambdef(self):
00329         ### lambdef: 'lambda' [varargslist] ':' test
00330         l1 = lambda : 0
00331         self.assertEqual(l1(), 0)
00332         l2 = lambda : a[d] # XXX just testing the expression
00333         l3 = lambda : [2 < x for x in [-1, 3, 0]]
00334         self.assertEqual(l3(), [0, 1, 0])
00335         l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
00336         self.assertEqual(l4(), 1)
00337         l5 = lambda x, y, z=2: x + y + z
00338         self.assertEqual(l5(1, 2), 5)
00339         self.assertEqual(l5(1, 2, 3), 6)
00340         check_syntax_error(self, "lambda x: x = 2")
00341         check_syntax_error(self, "lambda (None,): None")
00342         l6 = lambda x, y, *, k=20: x+y+k
00343         self.assertEqual(l6(1,2), 1+2+20)
00344         self.assertEqual(l6(1,2,k=10), 1+2+10)
00345 

Here is the call graph for this function:

Definition at line 748 of file test_grammar.py.

00748 
00749     def testListcomps(self):
00750         # list comprehension tests
00751         nums = [1, 2, 3, 4, 5]
00752         strs = ["Apple", "Banana", "Coconut"]
00753         spcs = ["  Apple", " Banana ", "Coco  nut  "]
00754 
00755         self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco  nut'])
00756         self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
00757         self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
00758         self.assertEqual([(i, s) for i in nums for s in strs],
00759                          [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
00760                           (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
00761                           (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
00762                           (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
00763                           (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
00764         self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
00765                          [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
00766                           (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
00767                           (5, 'Banana'), (5, 'Coconut')])
00768         self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
00769                          [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
00770 
00771         def test_in_func(l):
00772             return [0 < x < 3 for x in l if x > 2]
00773 
00774         self.assertEqual(test_in_func(nums), [False, False, False])
00775 
00776         def test_nested_front():
00777             self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
00778                              [[1, 2], [3, 4], [5, 6]])
00779 
00780         test_nested_front()
00781 
00782         check_syntax_error(self, "[i, s for i in nums for s in strs]")
00783         check_syntax_error(self, "[x if y]")
00784 
00785         suppliers = [
00786           (1, "Boeing"),
00787           (2, "Ford"),
00788           (3, "Macdonalds")
00789         ]
00790 
00791         parts = [
00792           (10, "Airliner"),
00793           (20, "Engine"),
00794           (30, "Cheeseburger")
00795         ]
00796 
00797         suppart = [
00798           (1, 10), (1, 20), (2, 20), (3, 30)
00799         ]
00800 
00801         x = [
00802           (sname, pname)
00803             for (sno, sname) in suppliers
00804               for (pno, pname) in parts
00805                 for (sp_sno, sp_pno) in suppart
00806                   if sno == sp_sno and pno == sp_pno
00807         ]
00808 
00809         self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
00810                              ('Macdonalds', 'Cheeseburger')])

Here is the call graph for this function:

Definition at line 644 of file test_grammar.py.

00644 
00645     def testMultiplicativeOps(self):
00646         x = 1 * 1
00647         x = 1 / 1
00648         x = 1 % 1
00649         x = 1 / 1 * 1 % 1

Definition at line 482 of file test_grammar.py.

00482 
00483     def testNonlocal(self):
00484         # 'nonlocal' NAME (',' NAME)*
00485         x = 0
00486         y = 0
00487         def f():
00488             nonlocal x
00489             nonlocal x, y

Definition at line 382 of file test_grammar.py.

00382 
00383     def testPassStmt(self):
00384         # 'pass'
00385         pass

Definition at line 456 of file test_grammar.py.

00456 
00457     def testRaise(self):
00458         # 'raise' test [',' test]
00459         try: raise RuntimeError('just testing')
00460         except RuntimeError: pass
00461         try: raise KeyboardInterrupt
00462         except KeyboardInterrupt: pass

Definition at line 445 of file test_grammar.py.

00445 
00446     def testReturn(self):
00447         # 'return' [testlist]
00448         def g1(): return
00449         def g2(): return 1
00450         g1()
00451         x = g2()
00452         check_syntax_error(self, "class foo:return 1")

Here is the call graph for this function:

Definition at line 657 of file test_grammar.py.

00657 
00658     def testSelectors(self):
00659         ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
00660         ### subscript: expr | [expr] ':' [expr]
00661 
00662         import sys, time
00663         c = sys.path[0]
00664         x = time.time()
00665         x = sys.modules['time'].time()
00666         a = '01234'
00667         c = a[0]
00668         c = a[-1]
00669         s = a[0:5]
00670         s = a[:5]
00671         s = a[0:]
00672         s = a[:]
00673         s = a[-5:]
00674         s = a[:-1]
00675         s = a[-4:-3]
00676         # A rough test of SF bug 1333982.  http://python.org/sf/1333982
00677         # The testing here is fairly incomplete.
00678         # Test cases should include: commas with 1 and 2 colons
00679         d = {}
00680         d[1] = 1
00681         d[1,] = 2
00682         d[1,2] = 3
00683         d[1,2,3] = 4
00684         L = list(d)
00685         L.sort(key=lambda x: x if isinstance(x, tuple) else ())
00686         self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')

Here is the call graph for this function:

Definition at line 633 of file test_grammar.py.

00633 
00634     def testShiftOps(self):
00635         x = 1 << 1
00636         x = 1 >> 1
00637         x = 1 << 1 >> 1

stmt: simple_stmt | compound_stmt Tested below

Definition at line 349 of file test_grammar.py.

00349 
00350     def testSimpleStmt(self):
00351         ### simple_stmt: small_stmt (';' small_stmt)* [';']
00352         x = 1; pass; del x
00353         def foo():
00354             # verify statements that end with semi-colons
00355             x = 1; pass; del x;
00356         foo()

Definition at line 585 of file test_grammar.py.

00585 
00586     def testSuite(self):
00587         # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
00588         if 1: pass
00589         if 1:
00590             pass
00591         if 1:
00592             #
00593             #
00594             #
00595             pass
00596             pass
00597             #
00598             pass
00599             #

Definition at line 600 of file test_grammar.py.

00600 
00601     def testTest(self):
00602         ### and_test ('or' and_test)*
00603         ### and_test: not_test ('and' not_test)*
00604         ### not_test: 'not' not_test | comparison
00605         if not 1: pass
00606         if 1 and 1: pass
00607         if 1 or 1: pass
00608         if not not not 1: pass
00609         if not 1 and 1 and 1: pass
00610         if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass

Definition at line 562 of file test_grammar.py.

00562 
00563     def testTry(self):
00564         ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
00565         ###         | 'try' ':' suite 'finally' ':' suite
00566         ### except_clause: 'except' [expr ['as' expr]]
00567         try:
00568             1/0
00569         except ZeroDivisionError:
00570             pass
00571         else:
00572             pass
00573         try: 1/0
00574         except EOFError: pass
00575         except TypeError as msg: pass
00576         except RuntimeError as msg: pass
00577         except: pass
00578         else: pass
00579         try: 1/0
00580         except (EOFError, TypeError, ZeroDivisionError): pass
00581         try: 1/0
00582         except (EOFError, TypeError, ZeroDivisionError) as msg: pass
00583         try: pass
00584         finally: pass

Definition at line 650 of file test_grammar.py.

00650 
00651     def testUnaryOps(self):
00652         x = +1
00653         x = -1
00654         x = ~1
00655         x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
00656         x = -1*1/1 + 1*1 - ---1*1

Definition at line 520 of file test_grammar.py.

00520 
00521     def testWhile(self):
00522         # 'while' test ':' suite ['else' ':' suite]
00523         while 0: pass
00524         while 0: pass
00525         else: pass
00526 
00527         # Issue1920: "while 0" is optimized away,
00528         # ensure that the "else" clause is still present.
00529         x = 0
00530         while 0:
00531             x = 1
00532         else:
00533             x = 2
00534         self.assertEqual(x, 2)

Here is the call graph for this function:

Definition at line 453 of file test_grammar.py.

00453 
00454     def testYield(self):
00455         check_syntax_error(self, "class foo:yield 1")

Here is the call graph for this function:


Member Data Documentation

Definition at line 542 of file test_grammar.py.

Definition at line 543 of file test_grammar.py.


The documentation for this class was generated from the following file: