home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / TEST_GRAMMAR.PY < prev    next >
Encoding:
Python Source  |  2000-10-11  |  14.0 KB  |  650 lines

  1. # Python test set -- part 1, grammar.
  2. # This just tests whether the parser accepts them all.
  3.  
  4. from test_support import *
  5.  
  6. print '1. Parser'
  7.  
  8. print '1.1 Tokens'
  9.  
  10. print '1.1.1 Backslashes'
  11.  
  12. # Backslash means line continuation:
  13. x = 1 \
  14. + 1
  15. if x <> 2: raise TestFailed, 'backslash for line continuation'
  16.  
  17. # Backslash does not means continuation in comments :\
  18. x = 0
  19. if x <> 0: raise TestFailed, 'backslash ending comment'
  20.  
  21. print '1.1.2 Numeric literals'
  22.  
  23. print '1.1.2.1 Plain integers'
  24. if 0xff <> 255: raise TestFailed, 'hex int'
  25. if 0377 <> 255: raise TestFailed, 'octal int'
  26. if  2147483647   != 017777777777: raise TestFailed, 'large positive int'
  27. try:
  28.     from sys import maxint
  29. except ImportError:
  30.     maxint = 2147483647
  31. if maxint == 2147483647:
  32.     if -2147483647-1 != 020000000000: raise TestFailed, 'max negative int'
  33.     # XXX -2147483648
  34.     if 037777777777 != -1: raise TestFailed, 'oct -1'
  35.     if 0xffffffff != -1: raise TestFailed, 'hex -1'
  36.     for s in '2147483648', '040000000000', '0x100000000':
  37.         try:
  38.             x = eval(s)
  39.         except OverflowError:
  40.             continue
  41. ##        raise TestFailed, \
  42.         print \
  43.               'No OverflowError on huge integer literal ' + `s`
  44. elif eval('maxint == 9223372036854775807'):
  45.     if eval('-9223372036854775807-1 != 01000000000000000000000'):
  46.         raise TestFailed, 'max negative int'
  47.     if eval('01777777777777777777777') != -1: raise TestFailed, 'oct -1'
  48.     if eval('0xffffffffffffffff') != -1: raise TestFailed, 'hex -1'
  49.     for s in '9223372036854775808', '02000000000000000000000', \
  50.          '0x10000000000000000':
  51.         try:
  52.             x = eval(s)
  53.         except OverflowError:
  54.             continue
  55.         raise TestFailed, \
  56.               'No OverflowError on huge integer literal ' + `s`
  57. else:
  58.     print 'Weird maxint value', maxint
  59.  
  60. print '1.1.2.2 Long integers'
  61. x = 0L
  62. x = 0l
  63. x = 0xffffffffffffffffL
  64. x = 0xffffffffffffffffl
  65. x = 077777777777777777L
  66. x = 077777777777777777l
  67. x = 123456789012345678901234567890L
  68. x = 123456789012345678901234567890l
  69.  
  70. print '1.1.2.3 Floating point'
  71. x = 3.14
  72. x = 314.
  73. x = 0.314
  74. # XXX x = 000.314
  75. x = .314
  76. x = 3e14
  77. x = 3E14
  78. x = 3e-14
  79. x = 3e+14
  80. x = 3.e14
  81. x = .3e14
  82. x = 3.1e4
  83.  
  84. print '1.1.3 String literals'
  85.  
  86. ##def assert(s):
  87. ##    if not s: raise TestFailed, 'see traceback'
  88.  
  89. x = ''; y = ""; assert(len(x) == 0 and x == y)
  90. x = '\''; y = "'"; assert(len(x) == 1 and x == y and ord(x) == 39)
  91. x = '"'; y = "\""; assert(len(x) == 1 and x == y and ord(x) == 34)
  92. x = "doesn't \"shrink\" does it"
  93. y = 'doesn\'t "shrink" does it'
  94. assert(len(x) == 24 and x == y)
  95. x = "does \"shrink\" doesn't it"
  96. y = 'does "shrink" doesn\'t it'
  97. assert(len(x) == 24 and x == y)
  98. x = """
  99. The "quick"
  100. brown fox
  101. jumps over
  102. the 'lazy' dog.
  103. """
  104. y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
  105. assert(x == y)
  106. y = '''
  107. The "quick"
  108. brown fox
  109. jumps over
  110. the 'lazy' dog.
  111. '''; assert(x == y)
  112. y = "\n\
  113. The \"quick\"\n\
  114. brown fox\n\
  115. jumps over\n\
  116. the 'lazy' dog.\n\
  117. "; assert(x == y)
  118. y = '\n\
  119. The \"quick\"\n\
  120. brown fox\n\
  121. jumps over\n\
  122. the \'lazy\' dog.\n\
  123. '; assert(x == y)
  124.  
  125.  
  126. print '1.2 Grammar'
  127.  
  128. print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE
  129. # XXX can't test in a script -- this rule is only used when interactive
  130.  
  131. print 'file_input' # (NEWLINE | stmt)* ENDMARKER
  132. # Being tested as this very moment this very module
  133.  
  134. print 'expr_input' # testlist NEWLINE
  135. # XXX Hard to test -- used only in calls to input()
  136.  
  137. print 'eval_input' # testlist ENDMARKER
  138. x = eval('1, 0 or 1')
  139.  
  140. print 'funcdef'
  141. ### 'def' NAME parameters ':' suite
  142. ### parameters: '(' [varargslist] ')'
  143. ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
  144. ###            | ('**'|'*' '*') NAME)
  145. ###            | fpdef ['=' test] (',' fpdef ['=' test])* [',']  
  146. ### fpdef: NAME | '(' fplist ')'
  147. ### fplist: fpdef (',' fpdef)* [',']
  148. ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
  149. ### argument: [test '='] test    # Really [keyword '='] test
  150. def f1(): pass
  151. f1()
  152. f1(*())
  153. f1(*(), **{})
  154. def f2(one_argument): pass
  155. def f3(two, arguments): pass
  156. def f4(two, (compound, (argument, list))): pass
  157. def a1(one_arg,): pass
  158. def a2(two, args,): pass
  159. def v0(*rest): pass
  160. def v1(a, *rest): pass
  161. def v2(a, b, *rest): pass
  162. def v3(a, (b, c), *rest): pass
  163. def d01(a=1): pass
  164. d01()
  165. d01(1)
  166. d01(*(1,))
  167. d01(**{'a':2})
  168. def d11(a, b=1): pass
  169. d11(1)
  170. d11(1, 2)
  171. d11(1, **{'b':2})
  172. def d21(a, b, c=1): pass
  173. d21(1, 2)
  174. d21(1, 2, 3)
  175. d21(*(1, 2, 3))
  176. d21(1, *(2, 3))
  177. d21(1, 2, *(3,))
  178. d21(1, 2, **{'c':3})
  179. def d02(a=1, b=2): pass
  180. d02()
  181. d02(1)
  182. d02(1, 2)
  183. d02(*(1, 2))
  184. d02(1, *(2,))
  185. d02(1, **{'b':2})
  186. d02(**{'a': 1, 'b': 2})
  187. def d12(a, b=1, c=2): pass
  188. d12(1)
  189. d12(1, 2)
  190. d12(1, 2, 3)
  191. def d22(a, b, c=1, d=2): pass
  192. d22(1, 2)
  193. d22(1, 2, 3)
  194. d22(1, 2, 3, 4)
  195. def d01v(a=1, *rest): pass
  196. d01v()
  197. d01v(1)
  198. d01v(1, 2)
  199. d01v(*(1, 2, 3, 4))
  200. d01v(*(1,))
  201. d01v(**{'a':2})
  202. def d11v(a, b=1, *rest): pass
  203. d11v(1)
  204. d11v(1, 2)
  205. d11v(1, 2, 3)
  206. def d21v(a, b, c=1, *rest): pass
  207. d21v(1, 2)
  208. d21v(1, 2, 3)
  209. d21v(1, 2, 3, 4)
  210. d21v(*(1, 2, 3, 4))
  211. d21v(1, 2, **{'c': 3})
  212. def d02v(a=1, b=2, *rest): pass
  213. d02v()
  214. d02v(1)
  215. d02v(1, 2)
  216. d02v(1, 2, 3)
  217. d02v(1, *(2, 3, 4))
  218. d02v(**{'a': 1, 'b': 2})
  219. def d12v(a, b=1, c=2, *rest): pass
  220. d12v(1)
  221. d12v(1, 2)
  222. d12v(1, 2, 3)
  223. d12v(1, 2, 3, 4)
  224. d12v(*(1, 2, 3, 4))
  225. d12v(1, 2, *(3, 4, 5))
  226. d12v(1, *(2,), **{'c': 3})
  227. def d22v(a, b, c=1, d=2, *rest): pass
  228. d22v(1, 2)
  229. d22v(1, 2, 3)
  230. d22v(1, 2, 3, 4)
  231. d22v(1, 2, 3, 4, 5)
  232. d22v(*(1, 2, 3, 4))
  233. d22v(1, 2, *(3, 4, 5))
  234. d22v(1, *(2, 3), **{'d': 4})
  235.  
  236. ### stmt: simple_stmt | compound_stmt
  237. # Tested below
  238.  
  239. ### simple_stmt: small_stmt (';' small_stmt)* [';']
  240. print 'simple_stmt'
  241. x = 1; pass; del x
  242.  
  243. ### small_stmt: expr_stmt | print_stmt  | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
  244. # Tested below
  245.  
  246. print 'expr_stmt' # (exprlist '=')* exprlist
  247. 1
  248. 1, 2, 3
  249. x = 1
  250. x = 1, 2, 3
  251. x = y = z = 1, 2, 3
  252. x, y, z = 1, 2, 3
  253. abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
  254. # NB these variables are deleted below
  255.  
  256. print 'print_stmt' # 'print' (test ',')* [test]
  257. print 1, 2, 3
  258. print 1, 2, 3,
  259. print
  260. print 0 or 1, 0 or 1,
  261. print 0 or 1
  262.  
  263. print 'extended print_stmt' # 'print' '>>' test ','
  264. import sys
  265. print >> sys.stdout, 1, 2, 3
  266. print >> sys.stdout, 1, 2, 3,
  267. print >> sys.stdout
  268. print >> sys.stdout, 0 or 1, 0 or 1,
  269. print >> sys.stdout, 0 or 1
  270.  
  271. # test printing to an instance
  272. class Gulp:
  273.     def write(self, msg): pass
  274.  
  275. gulp = Gulp()
  276. print >> gulp, 1, 2, 3
  277. print >> gulp, 1, 2, 3,
  278. print >> gulp
  279. print >> gulp, 0 or 1, 0 or 1,
  280. print >> gulp, 0 or 1
  281.  
  282. # test print >> None
  283. def driver():
  284.     oldstdout = sys.stdout
  285.     sys.stdout = Gulp()
  286.     try:
  287.         tellme(Gulp())
  288.         tellme()
  289.     finally:
  290.         sys.stdout = oldstdout
  291.  
  292. # we should see this once
  293. def tellme(file=sys.stdout):
  294.     print >> file, 'hello world'
  295.  
  296. driver()
  297.  
  298. # we should not see this at all
  299. def tellme(file=None):
  300.     print >> file, 'goodbye universe'
  301.  
  302. driver()
  303.  
  304. # syntax errors
  305. def check_syntax(statement):
  306.     try:
  307.         compile(statement, '<string>', 'exec')
  308.     except SyntaxError:
  309.         pass
  310.     else:
  311.         print 'Missing SyntaxError: "%s"' % statement
  312. check_syntax('print ,')
  313. check_syntax('print >> x,')
  314.  
  315. print 'del_stmt' # 'del' exprlist
  316. del abc
  317. del x, y, (z, xyz)
  318.  
  319. print 'pass_stmt' # 'pass'
  320. pass
  321.  
  322. print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt
  323. # Tested below
  324.  
  325. print 'break_stmt' # 'break'
  326. while 1: break
  327.  
  328. print 'continue_stmt' # 'continue'
  329. i = 1
  330. while i: i = 0; continue
  331.  
  332. print 'return_stmt' # 'return' [testlist]
  333. def g1(): return
  334. def g2(): return 1
  335. g1()
  336. x = g2()
  337.  
  338. print 'raise_stmt' # 'raise' test [',' test]
  339. try: raise RuntimeError, 'just testing'
  340. except RuntimeError: pass
  341. try: raise KeyboardInterrupt
  342. except KeyboardInterrupt: pass
  343.  
  344. print 'import_stmt' # 'import' NAME (',' NAME)* | 'from' NAME 'import' ('*' | NAME (',' NAME)*)
  345. import sys
  346. import time, sys
  347. from time import time
  348. from sys import *
  349. from sys import path, argv
  350.  
  351. print 'global_stmt' # 'global' NAME (',' NAME)*
  352. def f():
  353.     global a
  354.     global a, b
  355.     global one, two, three, four, five, six, seven, eight, nine, ten
  356.  
  357. print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
  358. def f():
  359.     z = None
  360.     del z
  361.     exec 'z=1+1\n'
  362.     if z <> 2: raise TestFailed, 'exec \'z=1+1\'\\n'
  363.     del z
  364.     exec 'z=1+1'
  365.     if z <> 2: raise TestFailed, 'exec \'z=1+1\''
  366.     z = None
  367.     del z
  368.     exec u'z=1+1\n'
  369.     if z <> 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
  370.     del z
  371.     exec u'z=1+1'
  372.     if z <> 2: raise TestFailed, 'exec u\'z=1+1\''
  373. f()
  374. g = {}
  375. exec 'z = 1' in g
  376. if g.has_key('__builtins__'): del g['__builtins__']
  377. if g <> {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'
  378. g = {}
  379. l = {}
  380. exec 'global a; a = 1; b = 2' in g, l
  381. if g.has_key('__builtins__'): del g['__builtins__']
  382. if l.has_key('__builtins__'): del l['__builtins__']
  383. if (g, l) <> ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g, l'
  384.  
  385.  
  386. ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  387. # Tested below
  388.  
  389. print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  390. if 1: pass
  391. if 1: pass
  392. else: pass
  393. if 0: pass
  394. elif 0: pass
  395. if 0: pass
  396. elif 0: pass
  397. elif 0: pass
  398. elif 0: pass
  399. else: pass
  400.  
  401. print 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
  402. while 0: pass
  403. while 0: pass
  404. else: pass
  405.  
  406. print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
  407. for i in 1, 2, 3: pass
  408. for i, j, k in (): pass
  409. else: pass
  410. class Squares:
  411.     def __init__(self, max):
  412.         self.max = max
  413.         self.sofar = []
  414.     def __len__(self): return len(self.sofar)
  415.     def __getitem__(self, i):
  416.         if not 0 <= i < self.max: raise IndexError
  417.         n = len(self.sofar)
  418.         while n <= i:
  419.             self.sofar.append(n*n)
  420.             n = n+1
  421.         return self.sofar[i]
  422. n = 0
  423. for x in Squares(10): n = n+x
  424. if n != 285: raise TestFailed, 'for over growing sequence'
  425.  
  426. print 'try_stmt'
  427. ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  428. ###         | 'try' ':' suite 'finally' ':' suite
  429. ### except_clause: 'except' [expr [',' expr]]
  430. try:
  431.     1/0
  432. except ZeroDivisionError:
  433.     pass
  434. else:
  435.     pass
  436. try: 1/0
  437. except EOFError: pass
  438. except TypeError, msg: pass
  439. except RuntimeError, msg: pass
  440. except: pass
  441. else: pass
  442. try: 1/0
  443. except (EOFError, TypeError, ZeroDivisionError): pass
  444. try: 1/0
  445. except (EOFError, TypeError, ZeroDivisionError), msg: pass
  446. try: pass
  447. finally: pass
  448.  
  449. print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
  450. if 1: pass
  451. if 1:
  452.     pass
  453. if 1:
  454.     #
  455.     #
  456.     #
  457.     pass
  458.     pass
  459.     #
  460.     pass
  461.     #
  462.  
  463. print 'test'
  464. ### and_test ('or' and_test)*
  465. ### and_test: not_test ('and' not_test)*
  466. ### not_test: 'not' not_test | comparison
  467. if not 1: pass
  468. if 1 and 1: pass
  469. if 1 or 1: pass
  470. if not not not 1: pass
  471. if not 1 and 1 and 1: pass
  472. if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
  473.  
  474. print 'comparison'
  475. ### comparison: expr (comp_op expr)*
  476. ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  477. if 1: pass
  478. x = (1 == 1)
  479. if 1 == 1: pass
  480. if 1 != 1: pass
  481. if 1 <> 1: pass
  482. if 1 < 1: pass
  483. if 1 > 1: pass
  484. if 1 <= 1: pass
  485. if 1 >= 1: pass
  486. if 1 is 1: pass
  487. if 1 is not 1: pass
  488. if 1 in (): pass
  489. if 1 not in (): pass
  490. if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
  491.  
  492. print 'binary mask ops'
  493. x = 1 & 1
  494. x = 1 ^ 1
  495. x = 1 | 1
  496.  
  497. print 'shift ops'
  498. x = 1 << 1
  499. x = 1 >> 1
  500. x = 1 << 1 >> 1
  501.  
  502. print 'additive ops'
  503. x = 1
  504. x = 1 + 1
  505. x = 1 - 1 - 1
  506. x = 1 - 1 + 1 - 1 + 1
  507.  
  508. print 'multiplicative ops'
  509. x = 1 * 1
  510. x = 1 / 1
  511. x = 1 % 1
  512. x = 1 / 1 * 1 % 1
  513.  
  514. print 'unary ops'
  515. x = +1
  516. x = -1
  517. x = ~1
  518. x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
  519. x = -1*1/1 + 1*1 - ---1*1
  520.  
  521. print 'selectors'
  522. ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
  523. ### subscript: expr | [expr] ':' [expr]
  524. f1()
  525. f2(1)
  526. f2(1,)
  527. f3(1, 2)
  528. f3(1, 2,)
  529. f4(1, (2, (3, 4)))
  530. v0()
  531. v0(1)
  532. v0(1,)
  533. v0(1,2)
  534. v0(1,2,3,4,5,6,7,8,9,0)
  535. v1(1)
  536. v1(1,)
  537. v1(1,2)
  538. v1(1,2,3)
  539. v1(1,2,3,4,5,6,7,8,9,0)
  540. v2(1,2)
  541. v2(1,2,3)
  542. v2(1,2,3,4)
  543. v2(1,2,3,4,5,6,7,8,9,0)
  544. v3(1,(2,3))
  545. v3(1,(2,3),4)
  546. v3(1,(2,3),4,5,6,7,8,9,0)
  547. print
  548. import sys, time
  549. c = sys.path[0]
  550. x = time.time()
  551. x = sys.modules['time'].time()
  552. a = '01234'
  553. c = a[0]
  554. c = a[-1]
  555. s = a[0:5]
  556. s = a[:5]
  557. s = a[0:]
  558. s = a[:]
  559. s = a[-5:]
  560. s = a[:-1]
  561. s = a[-4:-3]
  562.  
  563. print 'atoms'
  564. ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
  565. ### dictmaker: test ':' test (',' test ':' test)* [',']
  566.  
  567. x = (1)
  568. x = (1 or 2 or 3)
  569. x = (1 or 2 or 3, 2, 3)
  570.  
  571. x = []
  572. x = [1]
  573. x = [1 or 2 or 3]
  574. x = [1 or 2 or 3, 2, 3]
  575. x = []
  576.  
  577. x = {}
  578. x = {'one': 1}
  579. x = {'one': 1,}
  580. x = {'one' or 'two': 1 or 2}
  581. x = {'one': 1, 'two': 2}
  582. x = {'one': 1, 'two': 2,}
  583. x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
  584.  
  585. x = `x`
  586. x = `1 or 2 or 3`
  587. x = x
  588. x = 'x'
  589. x = 123
  590.  
  591. ### exprlist: expr (',' expr)* [',']
  592. ### testlist: test (',' test)* [',']
  593. # These have been exercised enough above
  594.  
  595. print 'classdef' # 'class' NAME ['(' testlist ')'] ':' suite
  596. class B: pass
  597. class C1(B): pass
  598. class C2(B): pass
  599. class D(C1, C2, B): pass
  600. class C:
  601.     def meth1(self): pass
  602.     def meth2(self, arg): pass
  603.     def meth3(self, a1, a2): pass
  604.  
  605. # list comprehension tests
  606. nums = [1, 2, 3, 4, 5]
  607. strs = ["Apple", "Banana", "Coconut"]
  608. spcs = ["  Apple", " Banana ", "Coco  nut  "]
  609.  
  610. print [s.strip() for s in spcs]
  611. print [3 * x for x in nums]
  612. print [x for x in nums if x > 2]
  613. print [(i, s) for i in nums for s in strs]
  614. print [(i, s) for i in nums for s in [f for f in strs if "n" in f]]
  615. try:
  616.     eval("[i, s for i in nums for s in strs]")
  617.     print "FAIL: should have raised a SyntaxError!"
  618. except SyntaxError:
  619.     print "good: got a SyntaxError as expected"
  620.  
  621. try:
  622.     eval("[x if y]")
  623.     print "FAIL: should have raised a SyntaxError!"
  624. except SyntaxError:
  625.         print "good: got a SyntaxError as expected"
  626.  
  627. suppliers = [
  628.   (1, "Boeing"),
  629.   (2, "Ford"),
  630.   (3, "Macdonalds")
  631. ]
  632.  
  633. parts = [
  634.   (10, "Airliner"),
  635.   (20, "Engine"),
  636.   (30, "Cheeseburger")
  637. ]
  638.  
  639. suppart = [
  640.   (1, 10), (1, 20), (2, 20), (3, 30)
  641. ]
  642.  
  643. print [
  644.   (sname, pname)
  645.     for (sno, sname) in suppliers
  646.       for (pno, pname) in parts
  647.         for (sp_sno, sp_pno) in suppart
  648.           if sno == sp_sno and pno == sp_pno
  649. ]
  650.