Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes
py2_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 | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt Tested below
def testPrintStmt
def testDelStmt
def testPassStmt
def testBreakStmt
def testContinueStmt
def test_break_continue_loop
def testReturn
def testYield
def testRaise
def testImport
def testGlobal
def testExec
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 testListcomps
def testGenexps
def testComprehensionSpecials
def test_with_statement
def testIfElseExpr

Public Attributes

 max
 sofar

Detailed Description

Definition at line 124 of file py2_test_grammar.py.


Member Function Documentation

Definition at line 455 of file py2_test_grammar.py.

00455 
00456     def test_break_continue_loop(self):
00457         # This test warrants an explanation. It is a test specifically for SF bugs
00458         # #463359 and #462937. The bug is that a 'break' statement executed or
00459         # exception raised inside a try/except inside a loop, *after* a continue
00460         # statement has been executed in that loop, will cause the wrong number of
00461         # arguments to be popped off the stack and the instruction pointer reset to
00462         # a very small number (usually 0.) Because of this, the following test
00463         # *must* written as a function, and the tracking vars *must* be function
00464         # arguments with default values. Otherwise, the test will loop and loop.
00465 
00466         def test_inner(extra_burning_oil = 1, count=0):
00467             big_hippo = 2
00468             while big_hippo:
00469                 count += 1
00470                 try:
00471                     if extra_burning_oil and big_hippo == 1:
00472                         extra_burning_oil -= 1
00473                         break
00474                     big_hippo -= 1
00475                     continue
00476                 except:
00477                     raise
00478             if count > 2 or big_hippo <> 1:
00479                 self.fail("continue then break in try/except in loop broken!")
00480         test_inner()

Here is the call graph for this function:

Definition at line 923 of file py2_test_grammar.py.

00923 
00924     def test_with_statement(self):
00925         class manager(object):
00926             def __enter__(self):
00927                 return (1, 2)
00928             def __exit__(self, *args):
00929                 pass
00930 
00931         with manager():
00932             pass
00933         with manager() as x:
00934             pass
00935         with manager() as (x, y):
00936             pass
00937         with manager(), manager():
00938             pass
00939         with manager() as x, manager() as y:
00940             pass
00941         with manager() as x, manager():
00942             pass

Here is the call graph for this function:

Definition at line 701 of file py2_test_grammar.py.

00701 
00702     def testAdditiveOps(self):
00703         x = 1
00704         x = 1 + 1
00705         x = 1 - 1 - 1
00706         x = 1 - 1 + 1 - 1 + 1

Definition at line 552 of file py2_test_grammar.py.

00552 
00553     def testAssert(self):
00554         # assert_stmt: 'assert' test [',' test]
00555         assert 1
00556         assert 1, 1
00557         assert lambda x:x
00558         assert 1, lambda x:x+1
00559         try:
00560             assert 0, "msg"
00561         except AssertionError, e:
00562             self.assertEquals(e.args[0], "msg")
00563         else:
00564             if __debug__:
00565                 self.fail("AssertionError not raised by assert 0")

Here is the call graph for this function:

Definition at line 750 of file py2_test_grammar.py.

00750 
00751     def testAtoms(self):
00752         ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
00753         ### dictmaker: test ':' test (',' test ':' test)* [',']
00754 
00755         x = (1)
00756         x = (1 or 2 or 3)
00757         x = (1 or 2 or 3, 2, 3)
00758 
00759         x = []
00760         x = [1]
00761         x = [1 or 2 or 3]
00762         x = [1 or 2 or 3, 2, 3]
00763         x = []
00764 
00765         x = {}
00766         x = {'one': 1}
00767         x = {'one': 1,}
00768         x = {'one' or 'two': 1 or 2}
00769         x = {'one': 1, 'two': 2}
00770         x = {'one': 1, 'two': 2,}
00771         x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
00772 
00773         x = `x`
00774         x = `1 or 2 or 3`
00775         self.assertEqual(`1,2`, '(1, 2)')
00776 
00777         x = x
00778         x = 'x'
00779         x = 123

Here is the call graph for this function:

Definition at line 691 of file py2_test_grammar.py.

00691 
00692     def testBinaryMaskOps(self):
00693         x = 1 & 1
00694         x = 1 ^ 1
00695         x = 1 | 1

Definition at line 425 of file py2_test_grammar.py.

00425 
00426     def testBreakStmt(self):
00427         # 'break'
00428         while 1: break

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

Definition at line 784 of file py2_test_grammar.py.

00784 
00785     def testClassdef(self):
00786         # 'class' NAME ['(' [testlist] ')'] ':' suite
00787         class B: pass
00788         class B2(): pass
00789         class C1(B): pass
00790         class C2(B): pass
00791         class D(C1, C2, B): pass
00792         class C:
00793             def meth1(self): pass
00794             def meth2(self, arg): pass
00795             def meth3(self, a1, a2): pass
00796         # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
00797         # decorators: decorator+
00798         # decorated: decorators (classdef | funcdef)
00799         def class_decorator(x):
00800             x.decorated = True
00801             return x
00802         @class_decorator
00803         class G:
00804             pass
00805         self.assertEqual(G.decorated, True)

Definition at line 673 of file py2_test_grammar.py.

00673 
00674     def testComparison(self):
00675         ### comparison: expr (comp_op expr)*
00676         ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
00677         if 1: pass
00678         x = (1 == 1)
00679         if 1 == 1: pass
00680         if 1 != 1: pass
00681         if 1 <> 1: pass
00682         if 1 < 1: pass
00683         if 1 > 1: pass
00684         if 1 <= 1: pass
00685         if 1 >= 1: pass
00686         if 1 is 1: pass
00687         if 1 is not 1: pass
00688         if 1 in (): pass
00689         if 1 not in (): pass
00690         if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass

Definition at line 904 of file py2_test_grammar.py.

00904 
00905     def testComprehensionSpecials(self):
00906         # test for outmost iterable precomputation
00907         x = 10; g = (i for i in range(x)); x = 5
00908         self.assertEqual(len(list(g)), 10)
00909 
00910         # This should hold, since we're only precomputing outmost iterable.
00911         x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
00912         x = 5; t = True;
00913         self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
00914 
00915         # Grammar allows multiple adjacent 'if's in listcomps and genexps,
00916         # even though it's silly. Make sure it works (ifelse broke this.)
00917         self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
00918         self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
00919 
00920         # verify unpacking single element tuples in listcomp/genexp.
00921         self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
00922         self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])

Here is the call graph for this function:

Definition at line 429 of file py2_test_grammar.py.

00429 
00430     def testContinueStmt(self):
00431         # 'continue'
00432         i = 1
00433         while i: i = 0; continue
00434 
00435         msg = ""
00436         while not msg:
00437             msg = "ok"
00438             try:
00439                 continue
00440                 msg = "continue failed to continue inside try"
00441             except:
00442                 msg = "continue inside try called except block"
00443         if msg != "ok":
00444             self.fail(msg)
00445 
00446         msg = ""
00447         while not msg:
00448             msg = "finally block not called"
00449             try:
00450                 continue
00451             finally:
00452                 msg = "ok"
00453         if msg != "ok":
00454             self.fail(msg)

Here is the call graph for this function:

Definition at line 409 of file py2_test_grammar.py.

00409 
00410     def testDelStmt(self):
00411         # 'del' exprlist
00412         abc = [1,2,3]
00413         x, y, z = abc
00414         xyz = x, y, z
00415 
00416         del abc
00417         del x, y, (z, xyz)

Definition at line 135 of file py2_test_grammar.py.

00135 
00136     def testEvalInput(self):
00137         # testlist ENDMARKER
00138         x = eval('1, 0 or 1')

Definition at line 518 of file py2_test_grammar.py.

00518 
00519     def testExec(self):
00520         # 'exec' expr ['in' expr [',' expr]]
00521         z = None
00522         del z
00523         exec 'z=1+1\n'
00524         if z != 2: self.fail('exec \'z=1+1\'\\n')
00525         del z
00526         exec 'z=1+1'
00527         if z != 2: self.fail('exec \'z=1+1\'')
00528         z = None
00529         del z
00530         import types
00531         if hasattr(types, "UnicodeType"):
00532             exec r"""if 1:
00533             exec u'z=1+1\n'
00534             if z != 2: self.fail('exec u\'z=1+1\'\\n')
00535             del z
00536             exec u'z=1+1'
00537             if z != 2: self.fail('exec u\'z=1+1\'')"""
00538         g = {}
00539         exec 'z = 1' in g
00540         if g.has_key('__builtins__'): del g['__builtins__']
00541         if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
00542         g = {}
00543         l = {}
00544 
00545         import warnings
00546         warnings.filterwarnings("ignore", "global statement", module="<string>")
00547         exec 'global a; a = 1; b = 2' in g, l
00548         if g.has_key('__builtins__'): del g['__builtins__']
00549         if l.has_key('__builtins__'): del l['__builtins__']
00550         if (g, l) != ({'a':1}, {'b':2}):
00551             self.fail('exec ... in g (%s), l (%s)' %(g,l))

Here is the call graph for this function:

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

Definition at line 326 of file py2_test_grammar.py.

00326 
00327     def testExprStmt(self):
00328         # (exprlist '=')* exprlist
00329         1
00330         1, 2, 3
00331         x = 1
00332         x = 1, 2, 3
00333         x = y = z = 1, 2, 3
00334         x, y, z = 1, 2, 3
00335         abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
00336 
00337         check_syntax_error(self, "x + 1 = 1")
00338         check_syntax_error(self, "a + 1 = b + 2")

Here is the call graph for this function:

Definition at line 597 of file py2_test_grammar.py.

00597 
00598     def testFor(self):
00599         # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
00600         for i in 1, 2, 3: pass
00601         for i, j, k in (): pass
00602         else: pass
00603         class Squares:
00604             def __init__(self, max):
00605                 self.max = max
00606                 self.sofar = []
00607             def __len__(self): return len(self.sofar)
00608             def __getitem__(self, i):
00609                 if not 0 <= i < self.max: raise IndexError
00610                 n = len(self.sofar)
00611                 while n <= i:
00612                     self.sofar.append(n*n)
00613                     n = n+1
00614                 return self.sofar[i]
00615         n = 0
00616         for x in Squares(10): n = n+x
00617         if n != 285:
00618             self.fail('for over growing sequence')
00619 
00620         result = []
00621         for x, in [(1,), (2,), (3,)]:
00622             result.append(x)
00623         self.assertEqual(result, [1, 2, 3])

Here is the call graph for this function:

Definition at line 139 of file py2_test_grammar.py.

00139 
00140     def testFuncdef(self):
00141         ### 'def' NAME parameters ':' suite
00142         ### parameters: '(' [varargslist] ')'
00143         ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
00144         ###            | ('**'|'*' '*') NAME)
00145         ###            | fpdef ['=' test] (',' fpdef ['=' test])* [',']
00146         ### fpdef: NAME | '(' fplist ')'
00147         ### fplist: fpdef (',' fpdef)* [',']
00148         ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
00149         ### argument: [test '='] test   # Really [keyword '='] test
00150         def f1(): pass
00151         f1()
00152         f1(*())
00153         f1(*(), **{})
00154         def f2(one_argument): pass
00155         def f3(two, arguments): pass
00156         def f4(two, (compound, (argument, list))): pass
00157         def f5((compound, first), two): pass
00158         self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
00159         self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
00160         if sys.platform.startswith('java'):
00161             self.assertEquals(f4.func_code.co_varnames,
00162                    ('two', '(compound, (argument, list))', 'compound', 'argument',
00163                                 'list',))
00164             self.assertEquals(f5.func_code.co_varnames,
00165                    ('(compound, first)', 'two', 'compound', 'first'))
00166         else:
00167             self.assertEquals(f4.func_code.co_varnames,
00168                   ('two', '.1', 'compound', 'argument',  'list'))
00169             self.assertEquals(f5.func_code.co_varnames,
00170                   ('.0', 'two', 'compound', 'first'))
00171         def a1(one_arg,): pass
00172         def a2(two, args,): pass
00173         def v0(*rest): pass
00174         def v1(a, *rest): pass
00175         def v2(a, b, *rest): pass
00176         def v3(a, (b, c), *rest): return a, b, c, rest
00177 
00178         f1()
00179         f2(1)
00180         f2(1,)
00181         f3(1, 2)
00182         f3(1, 2,)
00183         f4(1, (2, (3, 4)))
00184         v0()
00185         v0(1)
00186         v0(1,)
00187         v0(1,2)
00188         v0(1,2,3,4,5,6,7,8,9,0)
00189         v1(1)
00190         v1(1,)
00191         v1(1,2)
00192         v1(1,2,3)
00193         v1(1,2,3,4,5,6,7,8,9,0)
00194         v2(1,2)
00195         v2(1,2,3)
00196         v2(1,2,3,4)
00197         v2(1,2,3,4,5,6,7,8,9,0)
00198         v3(1,(2,3))
00199         v3(1,(2,3),4)
00200         v3(1,(2,3),4,5,6,7,8,9,0)
00201 
00202         # ceval unpacks the formal arguments into the first argcount names;
00203         # thus, the names nested inside tuples must appear after these names.
00204         if sys.platform.startswith('java'):
00205             self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
00206         else:
00207             self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
00208         self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
00209         def d01(a=1): pass
00210         d01()
00211         d01(1)
00212         d01(*(1,))
00213         d01(**{'a':2})
00214         def d11(a, b=1): pass
00215         d11(1)
00216         d11(1, 2)
00217         d11(1, **{'b':2})
00218         def d21(a, b, c=1): pass
00219         d21(1, 2)
00220         d21(1, 2, 3)
00221         d21(*(1, 2, 3))
00222         d21(1, *(2, 3))
00223         d21(1, 2, *(3,))
00224         d21(1, 2, **{'c':3})
00225         def d02(a=1, b=2): pass
00226         d02()
00227         d02(1)
00228         d02(1, 2)
00229         d02(*(1, 2))
00230         d02(1, *(2,))
00231         d02(1, **{'b':2})
00232         d02(**{'a': 1, 'b': 2})
00233         def d12(a, b=1, c=2): pass
00234         d12(1)
00235         d12(1, 2)
00236         d12(1, 2, 3)
00237         def d22(a, b, c=1, d=2): pass
00238         d22(1, 2)
00239         d22(1, 2, 3)
00240         d22(1, 2, 3, 4)
00241         def d01v(a=1, *rest): pass
00242         d01v()
00243         d01v(1)
00244         d01v(1, 2)
00245         d01v(*(1, 2, 3, 4))
00246         d01v(*(1,))
00247         d01v(**{'a':2})
00248         def d11v(a, b=1, *rest): pass
00249         d11v(1)
00250         d11v(1, 2)
00251         d11v(1, 2, 3)
00252         def d21v(a, b, c=1, *rest): pass
00253         d21v(1, 2)
00254         d21v(1, 2, 3)
00255         d21v(1, 2, 3, 4)
00256         d21v(*(1, 2, 3, 4))
00257         d21v(1, 2, **{'c': 3})
00258         def d02v(a=1, b=2, *rest): pass
00259         d02v()
00260         d02v(1)
00261         d02v(1, 2)
00262         d02v(1, 2, 3)
00263         d02v(1, *(2, 3, 4))
00264         d02v(**{'a': 1, 'b': 2})
00265         def d12v(a, b=1, c=2, *rest): pass
00266         d12v(1)
00267         d12v(1, 2)
00268         d12v(1, 2, 3)
00269         d12v(1, 2, 3, 4)
00270         d12v(*(1, 2, 3, 4))
00271         d12v(1, 2, *(3, 4, 5))
00272         d12v(1, *(2,), **{'c': 3})
00273         def d22v(a, b, c=1, d=2, *rest): pass
00274         d22v(1, 2)
00275         d22v(1, 2, 3)
00276         d22v(1, 2, 3, 4)
00277         d22v(1, 2, 3, 4, 5)
00278         d22v(*(1, 2, 3, 4))
00279         d22v(1, 2, *(3, 4, 5))
00280         d22v(1, *(2, 3), **{'d': 4})
00281         def d31v((x)): pass
00282         d31v(1)
00283         def d32v((x,)): pass
00284         d32v((1,))
00285 
00286         # keyword arguments after *arglist
00287         def f(*args, **kwargs):
00288             return args, kwargs
00289         self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
00290                                                     {'x':2, 'y':5}))
00291         self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
00292         self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
00293 
00294         # Check ast errors in *args and *kwargs
00295         check_syntax_error(self, "f(*g(1=2))")
00296         check_syntax_error(self, "f(**g(1=2))")

Here is the call graph for this function:

Definition at line 869 of file py2_test_grammar.py.

00869 
00870     def testGenexps(self):
00871         # generator expression tests
00872         g = ([x for x in range(10)] for x in range(1))
00873         self.assertEqual(g.next(), [x for x in range(10)])
00874         try:
00875             g.next()
00876             self.fail('should produce StopIteration exception')
00877         except StopIteration:
00878             pass
00879 
00880         a = 1
00881         try:
00882             g = (a for d in a)
00883             g.next()
00884             self.fail('should produce TypeError')
00885         except TypeError:
00886             pass
00887 
00888         self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
00889         self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
00890 
00891         a = [x for x in range(10)]
00892         b = (x for x in (y for y in a))
00893         self.assertEqual(sum(b), sum([x for x in range(10)]))
00894 
00895         self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
00896         self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
00897         self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
00898         self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
00899         self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
00900         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)]))
00901         self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
00902         check_syntax_error(self, "foo(x for x in range(10), 100)")
00903         check_syntax_error(self, "foo(100, x for x in range(10))")

Here is the call graph for this function:

Definition at line 512 of file py2_test_grammar.py.

00512 
00513     def testGlobal(self):
00514         # 'global' NAME (',' NAME)*
00515         global a
00516         global a, b
00517         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 569 of file py2_test_grammar.py.

00569 
00570     def testIf(self):
00571         # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
00572         if 1: pass
00573         if 1: pass
00574         else: pass
00575         if 0: pass
00576         elif 0: pass
00577         if 0: pass
00578         elif 0: pass
00579         elif 0: pass
00580         elif 0: pass
00581         else: pass

Definition at line 943 of file py2_test_grammar.py.

00943 
00944     def testIfElseExpr(self):
00945         # Test ifelse expressions in various cases
00946         def _checkeval(msg, ret):
00947             "helper to check that evaluation of expressions is done correctly"
00948             print x
00949             return ret
00950 
00951         self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
00952         self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
00953         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])
00954         self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
00955         self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
00956         self.assertEqual((5 and 6 if 0 else 1), 1)
00957         self.assertEqual(((5 and 6) if 0 else 1), 1)
00958         self.assertEqual((5 and (6 if 1 else 1)), 6)
00959         self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
00960         self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
00961         self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
00962         self.assertEqual((not 5 if 1 else 1), False)
00963         self.assertEqual((not 5 if 0 else 1), 1)
00964         self.assertEqual((6 + 1 if 1 else 2), 7)
00965         self.assertEqual((6 - 1 if 1 else 2), 5)
00966         self.assertEqual((6 * 2 if 1 else 4), 12)
00967         self.assertEqual((6 / 2 if 1 else 3), 3)
00968         self.assertEqual((6 < 4 if 0 else 2), 2)
00969 

Here is the call graph for this function:

Definition at line 499 of file py2_test_grammar.py.

00499 
00500     def testImport(self):
00501         # 'import' dotted_as_names
00502         import sys
00503         import time, sys
00504         # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
00505         from time import time
00506         from time import (time)
00507         # not testable inside a function, but already done at top of the module
00508         # from sys import *
00509         from sys import path, argv
00510         from sys import (path, argv)
00511         from sys import (path, argv,)

Definition at line 297 of file py2_test_grammar.py.

00297 
00298     def testLambdef(self):
00299         ### lambdef: 'lambda' [varargslist] ':' test
00300         l1 = lambda : 0
00301         self.assertEquals(l1(), 0)
00302         l2 = lambda : a[d] # XXX just testing the expression
00303         l3 = lambda : [2 < x for x in [-1, 3, 0L]]
00304         self.assertEquals(l3(), [0, 1, 0])
00305         l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
00306         self.assertEquals(l4(), 1)
00307         l5 = lambda x, y, z=2: x + y + z
00308         self.assertEquals(l5(1, 2), 5)
00309         self.assertEquals(l5(1, 2, 3), 6)
00310         check_syntax_error(self, "lambda x: x = 2")
00311         check_syntax_error(self, "lambda (None,): None")

Here is the call graph for this function:

Definition at line 806 of file py2_test_grammar.py.

00806 
00807     def testListcomps(self):
00808         # list comprehension tests
00809         nums = [1, 2, 3, 4, 5]
00810         strs = ["Apple", "Banana", "Coconut"]
00811         spcs = ["  Apple", " Banana ", "Coco  nut  "]
00812 
00813         self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco  nut'])
00814         self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
00815         self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
00816         self.assertEqual([(i, s) for i in nums for s in strs],
00817                          [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
00818                           (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
00819                           (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
00820                           (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
00821                           (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
00822         self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
00823                          [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
00824                           (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
00825                           (5, 'Banana'), (5, 'Coconut')])
00826         self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
00827                          [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
00828 
00829         def test_in_func(l):
00830             return [None < x < 3 for x in l if x > 2]
00831 
00832         self.assertEqual(test_in_func(nums), [False, False, False])
00833 
00834         def test_nested_front():
00835             self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
00836                              [[1, 2], [3, 4], [5, 6]])
00837 
00838         test_nested_front()
00839 
00840         check_syntax_error(self, "[i, s for i in nums for s in strs]")
00841         check_syntax_error(self, "[x if y]")
00842 
00843         suppliers = [
00844           (1, "Boeing"),
00845           (2, "Ford"),
00846           (3, "Macdonalds")
00847         ]
00848 
00849         parts = [
00850           (10, "Airliner"),
00851           (20, "Engine"),
00852           (30, "Cheeseburger")
00853         ]
00854 
00855         suppart = [
00856           (1, 10), (1, 20), (2, 20), (3, 30)
00857         ]
00858 
00859         x = [
00860           (sname, pname)
00861             for (sno, sname) in suppliers
00862               for (pno, pname) in parts
00863                 for (sp_sno, sp_pno) in suppart
00864                   if sno == sp_sno and pno == sp_pno
00865         ]
00866 
00867         self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
00868                              ('Macdonalds', 'Cheeseburger')])

Here is the call graph for this function:

Definition at line 707 of file py2_test_grammar.py.

00707 
00708     def testMultiplicativeOps(self):
00709         x = 1 * 1
00710         x = 1 / 1
00711         x = 1 % 1
00712         x = 1 / 1 * 1 % 1

Definition at line 418 of file py2_test_grammar.py.

00418 
00419     def testPassStmt(self):
00420         # 'pass'
00421         pass

Definition at line 339 of file py2_test_grammar.py.

00339 
00340     def testPrintStmt(self):
00341         # 'print' (test ',')* [test]
00342         import StringIO
00343 
00344         # Can't test printing to real stdout without comparing output
00345         # which is not available in unittest.
00346         save_stdout = sys.stdout
00347         sys.stdout = StringIO.StringIO()
00348 
00349         print 1, 2, 3
00350         print 1, 2, 3,
00351         print
00352         print 0 or 1, 0 or 1,
00353         print 0 or 1
00354 
00355         # 'print' '>>' test ','
00356         print >> sys.stdout, 1, 2, 3
00357         print >> sys.stdout, 1, 2, 3,
00358         print >> sys.stdout
00359         print >> sys.stdout, 0 or 1, 0 or 1,
00360         print >> sys.stdout, 0 or 1
00361 
00362         # test printing to an instance
00363         class Gulp:
00364             def write(self, msg): pass
00365 
00366         gulp = Gulp()
00367         print >> gulp, 1, 2, 3
00368         print >> gulp, 1, 2, 3,
00369         print >> gulp
00370         print >> gulp, 0 or 1, 0 or 1,
00371         print >> gulp, 0 or 1
00372 
00373         # test print >> None
00374         def driver():
00375             oldstdout = sys.stdout
00376             sys.stdout = Gulp()
00377             try:
00378                 tellme(Gulp())
00379                 tellme()
00380             finally:
00381                 sys.stdout = oldstdout
00382 
00383         # we should see this once
00384         def tellme(file=sys.stdout):
00385             print >> file, 'hello world'
00386 
00387         driver()
00388 
00389         # we should not see this at all
00390         def tellme(file=None):
00391             print >> file, 'goodbye universe'
00392 
00393         driver()
00394 
00395         self.assertEqual(sys.stdout.getvalue(), '''\
00396 1 2 3
00397 1 2 3
00398 1 1 1
00399 1 2 3
00400 1 2 3
00401 1 1 1
00402 hello world
00403 ''')
00404         sys.stdout = save_stdout
00405 
00406         # syntax errors
00407         check_syntax_error(self, 'print ,')
00408         check_syntax_error(self, 'print >> x,')

Here is the call graph for this function:

Definition at line 492 of file py2_test_grammar.py.

00492 
00493     def testRaise(self):
00494         # 'raise' test [',' test]
00495         try: raise RuntimeError, 'just testing'
00496         except RuntimeError: pass
00497         try: raise KeyboardInterrupt
00498         except KeyboardInterrupt: pass

Definition at line 481 of file py2_test_grammar.py.

00481 
00482     def testReturn(self):
00483         # 'return' [testlist]
00484         def g1(): return
00485         def g2(): return 1
00486         g1()
00487         x = g2()
00488         check_syntax_error(self, "class foo:return 1")

Here is the call graph for this function:

Definition at line 720 of file py2_test_grammar.py.

00720 
00721     def testSelectors(self):
00722         ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
00723         ### subscript: expr | [expr] ':' [expr]
00724 
00725         import sys, time
00726         c = sys.path[0]
00727         x = time.time()
00728         x = sys.modules['time'].time()
00729         a = '01234'
00730         c = a[0]
00731         c = a[-1]
00732         s = a[0:5]
00733         s = a[:5]
00734         s = a[0:]
00735         s = a[:]
00736         s = a[-5:]
00737         s = a[:-1]
00738         s = a[-4:-3]
00739         # A rough test of SF bug 1333982.  http://python.org/sf/1333982
00740         # The testing here is fairly incomplete.
00741         # Test cases should include: commas with 1 and 2 colons
00742         d = {}
00743         d[1] = 1
00744         d[1,] = 2
00745         d[1,2] = 3
00746         d[1,2,3] = 4
00747         L = list(d)
00748         L.sort()
00749         self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')

Definition at line 696 of file py2_test_grammar.py.

00696 
00697     def testShiftOps(self):
00698         x = 1 << 1
00699         x = 1 >> 1
00700         x = 1 << 1 >> 1

stmt: simple_stmt | compound_stmt Tested below

Definition at line 315 of file py2_test_grammar.py.

00315 
00316     def testSimpleStmt(self):
00317         ### simple_stmt: small_stmt (';' small_stmt)* [';']
00318         x = 1; pass; del x
00319         def foo():
00320             # verify statements that end with semi-colons
00321             x = 1; pass; del x;
00322         foo()

Definition at line 647 of file py2_test_grammar.py.

00647 
00648     def testSuite(self):
00649         # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
00650         if 1: pass
00651         if 1:
00652             pass
00653         if 1:
00654             #
00655             #
00656             #
00657             pass
00658             pass
00659             #
00660             pass
00661             #

Definition at line 662 of file py2_test_grammar.py.

00662 
00663     def testTest(self):
00664         ### and_test ('or' and_test)*
00665         ### and_test: not_test ('and' not_test)*
00666         ### not_test: 'not' not_test | comparison
00667         if not 1: pass
00668         if 1 and 1: pass
00669         if 1 or 1: pass
00670         if not not not 1: pass
00671         if not 1 and 1 and 1: pass
00672         if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass

Definition at line 624 of file py2_test_grammar.py.

00624 
00625     def testTry(self):
00626         ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
00627         ###         | 'try' ':' suite 'finally' ':' suite
00628         ### except_clause: 'except' [expr [('as' | ',') expr]]
00629         try:
00630             1/0
00631         except ZeroDivisionError:
00632             pass
00633         else:
00634             pass
00635         try: 1/0
00636         except EOFError: pass
00637         except TypeError as msg: pass
00638         except RuntimeError, msg: pass
00639         except: pass
00640         else: pass
00641         try: 1/0
00642         except (EOFError, TypeError, ZeroDivisionError): pass
00643         try: 1/0
00644         except (EOFError, TypeError, ZeroDivisionError), msg: pass
00645         try: pass
00646         finally: pass

Definition at line 713 of file py2_test_grammar.py.

00713 
00714     def testUnaryOps(self):
00715         x = +1
00716         x = -1
00717         x = ~1
00718         x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
00719         x = -1*1/1 + 1*1 - ---1*1

Definition at line 582 of file py2_test_grammar.py.

00582 
00583     def testWhile(self):
00584         # 'while' test ':' suite ['else' ':' suite]
00585         while 0: pass
00586         while 0: pass
00587         else: pass
00588 
00589         # Issue1920: "while 0" is optimized away,
00590         # ensure that the "else" clause is still present.
00591         x = 0
00592         while 0:
00593             x = 1
00594         else:
00595             x = 2
00596         self.assertEquals(x, 2)

Definition at line 489 of file py2_test_grammar.py.

00489 
00490     def testYield(self):
00491         check_syntax_error(self, "class foo:yield 1")

Here is the call graph for this function:


Member Data Documentation

Definition at line 604 of file py2_test_grammar.py.

Definition at line 605 of file py2_test_grammar.py.


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