How to use test_syntax method in green

Best Python code snippet using green

test_syntax.py

Source:test_syntax.py Github

copy

Full Screen

1"""This module tests SyntaxErrors.2Here's an example of the sort of thing that is tested.3>>> def f(x):4... global x5Traceback (most recent call last):6SyntaxError: name 'x' is local and global (<doctest test.test_syntax[0]>, line 1)7The tests are all raise SyntaxErrors. They were created by checking8each C call that raises SyntaxError. There are several modules that9raise these exceptions-- ast.c, compile.c, future.c, pythonrun.c, and10symtable.c.11The parser itself outlaws a lot of invalid syntax. None of these12errors are tested here at the moment. We should add some tests; since13there are infinitely many programs with invalid syntax, we would need14to be judicious in selecting some.15The compiler generates a synthetic module name for code executed by16doctest. Since all the code comes from the same module, a suffix like17[1] is appended to the module name, As a consequence, changing the18order of tests in this module means renumbering all the errors after19it. (Maybe we should enable the ellipsis option for these tests.)20In ast.c, syntax errors are raised by calling ast_error().21Errors from set_context():22>>> obj.None = 123Traceback (most recent call last):24 File "<doctest test.test_syntax[1]>", line 125SyntaxError: cannot assign to None26>>> None = 127Traceback (most recent call last):28 File "<doctest test.test_syntax[2]>", line 129SyntaxError: cannot assign to None30It's a syntax error to assign to the empty tuple. Why isn't it an31error to assign to the empty list? It will always raise some error at32runtime.33>>> () = 134Traceback (most recent call last):35 File "<doctest test.test_syntax[3]>", line 136SyntaxError: can't assign to ()37>>> f() = 138Traceback (most recent call last):39 File "<doctest test.test_syntax[4]>", line 140SyntaxError: can't assign to function call41>>> del f()42Traceback (most recent call last):43 File "<doctest test.test_syntax[5]>", line 144SyntaxError: can't delete function call45>>> a + 1 = 246Traceback (most recent call last):47 File "<doctest test.test_syntax[6]>", line 148SyntaxError: can't assign to operator49>>> (x for x in x) = 150Traceback (most recent call last):51 File "<doctest test.test_syntax[7]>", line 152SyntaxError: can't assign to generator expression53>>> 1 = 154Traceback (most recent call last):55 File "<doctest test.test_syntax[8]>", line 156SyntaxError: can't assign to literal57>>> "abc" = 158Traceback (most recent call last):59 File "<doctest test.test_syntax[8]>", line 160SyntaxError: can't assign to literal61>>> `1` = 162Traceback (most recent call last):63 File "<doctest test.test_syntax[10]>", line 164SyntaxError: can't assign to repr65If the left-hand side of an assignment is a list or tuple, an illegal66expression inside that contain should still cause a syntax error.67This test just checks a couple of cases rather than enumerating all of68them.69>>> (a, "b", c) = (1, 2, 3)70Traceback (most recent call last):71 File "<doctest test.test_syntax[11]>", line 172SyntaxError: can't assign to literal73>>> [a, b, c + 1] = [1, 2, 3]74Traceback (most recent call last):75 File "<doctest test.test_syntax[12]>", line 176SyntaxError: can't assign to operator77>>> a if 1 else b = 178Traceback (most recent call last):79 File "<doctest test.test_syntax[13]>", line 180SyntaxError: can't assign to conditional expression81From compiler_complex_args():82>>> def f(None=1):83... pass84Traceback (most recent call last):85 File "<doctest test.test_syntax[14]>", line 186SyntaxError: cannot assign to None87From ast_for_arguments():88>>> def f(x, y=1, z):89... pass90Traceback (most recent call last):91 File "<doctest test.test_syntax[15]>", line 192SyntaxError: non-default argument follows default argument93>>> def f(x, None):94... pass95Traceback (most recent call last):96 File "<doctest test.test_syntax[16]>", line 197SyntaxError: cannot assign to None98>>> def f(*None):99... pass100Traceback (most recent call last):101 File "<doctest test.test_syntax[17]>", line 1102SyntaxError: cannot assign to None103>>> def f(**None):104... pass105Traceback (most recent call last):106 File "<doctest test.test_syntax[18]>", line 1107SyntaxError: cannot assign to None108From ast_for_funcdef():109>>> def None(x):110... pass111Traceback (most recent call last):112 File "<doctest test.test_syntax[19]>", line 1113SyntaxError: cannot assign to None114From ast_for_call():115>>> def f(it, *varargs):116... return list(it)117>>> L = range(10)118>>> f(x for x in L)119[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]120>>> f(x for x in L, 1)121Traceback (most recent call last):122 File "<doctest test.test_syntax[23]>", line 1123SyntaxError: Generator expression must be parenthesized if not sole argument124>>> f((x for x in L), 1)125[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]126>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11,127... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22,128... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33,129... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44,130... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55,131... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66,132... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77,133... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88,134... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99,135... i100, i101, i102, i103, i104, i105, i106, i107, i108,136... i109, i110, i111, i112, i113, i114, i115, i116, i117,137... i118, i119, i120, i121, i122, i123, i124, i125, i126,138... i127, i128, i129, i130, i131, i132, i133, i134, i135,139... i136, i137, i138, i139, i140, i141, i142, i143, i144,140... i145, i146, i147, i148, i149, i150, i151, i152, i153,141... i154, i155, i156, i157, i158, i159, i160, i161, i162,142... i163, i164, i165, i166, i167, i168, i169, i170, i171,143... i172, i173, i174, i175, i176, i177, i178, i179, i180,144... i181, i182, i183, i184, i185, i186, i187, i188, i189,145... i190, i191, i192, i193, i194, i195, i196, i197, i198,146... i199, i200, i201, i202, i203, i204, i205, i206, i207,147... i208, i209, i210, i211, i212, i213, i214, i215, i216,148... i217, i218, i219, i220, i221, i222, i223, i224, i225,149... i226, i227, i228, i229, i230, i231, i232, i233, i234,150... i235, i236, i237, i238, i239, i240, i241, i242, i243,151... i244, i245, i246, i247, i248, i249, i250, i251, i252,152... i253, i254, i255)153Traceback (most recent call last):154 File "<doctest test.test_syntax[25]>", line 1155SyntaxError: more than 255 arguments156The actual error cases counts positional arguments, keyword arguments,157and generator expression arguments separately. This test combines the158three.159>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11,160... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22,161... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33,162... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44,163... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55,164... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66,165... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77,166... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88,167... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99,168... i100, i101, i102, i103, i104, i105, i106, i107, i108,169... i109, i110, i111, i112, i113, i114, i115, i116, i117,170... i118, i119, i120, i121, i122, i123, i124, i125, i126,171... i127, i128, i129, i130, i131, i132, i133, i134, i135,172... i136, i137, i138, i139, i140, i141, i142, i143, i144,173... i145, i146, i147, i148, i149, i150, i151, i152, i153,174... i154, i155, i156, i157, i158, i159, i160, i161, i162,175... i163, i164, i165, i166, i167, i168, i169, i170, i171,176... i172, i173, i174, i175, i176, i177, i178, i179, i180,177... i181, i182, i183, i184, i185, i186, i187, i188, i189,178... i190, i191, i192, i193, i194, i195, i196, i197, i198,179... i199, i200, i201, i202, i203, i204, i205, i206, i207,180... i208, i209, i210, i211, i212, i213, i214, i215, i216,181... i217, i218, i219, i220, i221, i222, i223, i224, i225,182... i226, i227, i228, i229, i230, i231, i232, i233, i234,183... i235, i236, i237, i238, i239, i240, i241, i242, i243,184... (x for x in i244), i245, i246, i247, i248, i249, i250, i251,185... i252=1, i253=1, i254=1, i255=1)186Traceback (most recent call last):187 File "<doctest test.test_syntax[26]>", line 1188SyntaxError: more than 255 arguments189>>> f(lambda x: x[0] = 3)190Traceback (most recent call last):191 File "<doctest test.test_syntax[27]>", line 1192SyntaxError: lambda cannot contain assignment193The grammar accepts any test (basically, any expression) in the194keyword slot of a call site. Test a few different options.195>>> f(x()=2)196Traceback (most recent call last):197 File "<doctest test.test_syntax[28]>", line 1198SyntaxError: keyword can't be an expression199>>> f(a or b=1)200Traceback (most recent call last):201 File "<doctest test.test_syntax[29]>", line 1202SyntaxError: keyword can't be an expression203>>> f(x.y=1)204Traceback (most recent call last):205 File "<doctest test.test_syntax[30]>", line 1206SyntaxError: keyword can't be an expression207More set_context():208>>> (x for x in x) += 1209Traceback (most recent call last):210 File "<doctest test.test_syntax[31]>", line 1211SyntaxError: can't assign to generator expression212>>> None += 1213Traceback (most recent call last):214 File "<doctest test.test_syntax[32]>", line 1215SyntaxError: cannot assign to None216>>> f() += 1217Traceback (most recent call last):218 File "<doctest test.test_syntax[33]>", line 1219SyntaxError: can't assign to function call220Test continue in finally in weird combinations.221continue in for loop under finally should be ok.222 >>> def test():223 ... try:224 ... pass225 ... finally:226 ... for abc in range(10):227 ... continue228 ... print abc229 >>> test()230 9231Start simple, a continue in a finally should not be allowed.232 >>> def test():233 ... for abc in range(10):234 ... try:235 ... pass236 ... finally:237 ... continue238 Traceback (most recent call last):239 ...240 File "<doctest test.test_syntax[36]>", line 6241 SyntaxError: 'continue' not supported inside 'finally' clause242This is essentially a continue in a finally which should not be allowed.243 >>> def test():244 ... for abc in range(10):245 ... try:246 ... pass247 ... finally:248 ... try:249 ... continue250 ... except:251 ... pass252 Traceback (most recent call last):253 ...254 File "<doctest test.test_syntax[37]>", line 6255 SyntaxError: 'continue' not supported inside 'finally' clause256 >>> def foo():257 ... try:258 ... pass259 ... finally:260 ... continue261 Traceback (most recent call last):262 ...263 File "<doctest test.test_syntax[38]>", line 5264 SyntaxError: 'continue' not supported inside 'finally' clause265 >>> def foo():266 ... for a in ():267 ... try:268 ... pass269 ... finally:270 ... continue271 Traceback (most recent call last):272 ...273 File "<doctest test.test_syntax[39]>", line 6274 SyntaxError: 'continue' not supported inside 'finally' clause275 >>> def foo():276 ... for a in ():277 ... try:278 ... pass279 ... finally:280 ... try:281 ... continue282 ... finally:283 ... pass284 Traceback (most recent call last):285 ...286 File "<doctest test.test_syntax[40]>", line 7287 SyntaxError: 'continue' not supported inside 'finally' clause288 >>> def foo():289 ... for a in ():290 ... try: pass291 ... finally:292 ... try:293 ... pass294 ... except:295 ... continue296 Traceback (most recent call last):297 ...298 File "<doctest test.test_syntax[41]>", line 8299 SyntaxError: 'continue' not supported inside 'finally' clause300There is one test for a break that is not in a loop. The compiler301uses a single data structure to keep track of try-finally and loops,302so we need to be sure that a break is actually inside a loop. If it303isn't, there should be a syntax error.304 >>> try:305 ... print 1306 ... break307 ... print 2308 ... finally:309 ... print 3310 Traceback (most recent call last):311 ...312 File "<doctest test.test_syntax[42]>", line 3313 SyntaxError: 'break' outside loop314This raises a SyntaxError, it used to raise a SystemError.315Context for this change can be found on issue #27514316In 2.5 there was a missing exception and an assert was triggered in a debug317build. The number of blocks must be greater than CO_MAXBLOCKS. SF #1565514318 >>> while 1:319 ... while 2:320 ... while 3:321 ... while 4:322 ... while 5:323 ... while 6:324 ... while 8:325 ... while 9:326 ... while 10:327 ... while 11:328 ... while 12:329 ... while 13:330 ... while 14:331 ... while 15:332 ... while 16:333 ... while 17:334 ... while 18:335 ... while 19:336 ... while 20:337 ... while 21:338 ... while 22:339 ... break340 Traceback (most recent call last):341 ...342 SyntaxError: too many statically nested blocks343This tests assignment-context; there was a bug in Python 2.5 where compiling344a complex 'if' (one with 'elif') would fail to notice an invalid suite,345leading to spurious errors.346 >>> if 1:347 ... x() = 1348 ... elif 1:349 ... pass350 Traceback (most recent call last):351 ...352 File "<doctest test.test_syntax[44]>", line 2353 SyntaxError: can't assign to function call354 >>> if 1:355 ... pass356 ... elif 1:357 ... x() = 1358 Traceback (most recent call last):359 ...360 File "<doctest test.test_syntax[45]>", line 4361 SyntaxError: can't assign to function call362 >>> if 1:363 ... x() = 1364 ... elif 1:365 ... pass366 ... else:367 ... pass368 Traceback (most recent call last):369 ...370 File "<doctest test.test_syntax[46]>", line 2371 SyntaxError: can't assign to function call372 >>> if 1:373 ... pass374 ... elif 1:375 ... x() = 1376 ... else:377 ... pass378 Traceback (most recent call last):379 ...380 File "<doctest test.test_syntax[47]>", line 4381 SyntaxError: can't assign to function call382 >>> if 1:383 ... pass384 ... elif 1:385 ... pass386 ... else:387 ... x() = 1388 Traceback (most recent call last):389 ...390 File "<doctest test.test_syntax[48]>", line 6391 SyntaxError: can't assign to function call392>>> f(a=23, a=234)393Traceback (most recent call last):394 ...395 File "<doctest test.test_syntax[49]>", line 1396SyntaxError: keyword argument repeated397>>> del ()398Traceback (most recent call last):399 ...400 File "<doctest test.test_syntax[50]>", line 1401SyntaxError: can't delete ()402>>> {1, 2, 3} = 42403Traceback (most recent call last):404 ...405 File "<doctest test.test_syntax[50]>", line 1406SyntaxError: can't assign to literal407Corner-case that used to crash:408 >>> def f(*xx, **__debug__): pass409 Traceback (most recent call last):410 SyntaxError: cannot assign to __debug__411"""412import re413import unittest414import warnings415from test import test_support416class SyntaxTestCase(unittest.TestCase):417 def _check_error(self, code, errtext,418 filename="<testcase>", mode="exec", subclass=None):419 """Check that compiling code raises SyntaxError with errtext.420 errtest is a regular expression that must be present in the421 test of the exception raised. If subclass is specified it422 is the expected subclass of SyntaxError (e.g. IndentationError).423 """424 try:425 compile(code, filename, mode)426 except SyntaxError, err:427 if subclass and not isinstance(err, subclass):428 self.fail("SyntaxError is not a %s" % subclass.__name__)429 mo = re.search(errtext, str(err))430 if mo is None:431 self.fail("%s did not contain '%r'" % (err, errtext,))432 else:433 self.fail("compile() did not raise SyntaxError")434 def test_paren_arg_with_default(self):435 self._check_error("def f((x)=23): pass",436 "parenthesized arg with default")437 def test_assign_call(self):438 self._check_error("f() = 1", "assign")439 def test_assign_del(self):440 self._check_error("del f()", "delete")441 def test_global_err_then_warn(self):442 # Bug tickler: The SyntaxError raised for one global statement443 # shouldn't be clobbered by a SyntaxWarning issued for a later one.444 source = re.sub('(?m)^ *:', '', """\445 :def error(a):446 : global a # SyntaxError447 :def warning():448 : b = 1449 : global b # SyntaxWarning450 :""")451 warnings.filterwarnings(action='ignore', category=SyntaxWarning)452 self._check_error(source, "global")453 warnings.filters.pop(0)454 def test_break_outside_loop(self):455 self._check_error("break", "outside loop")456 def test_delete_deref(self):457 source = re.sub('(?m)^ *:', '', """\458 :def foo(x):459 : def bar():460 : print x461 : del x462 :""")463 self._check_error(source, "nested scope")464 def test_unexpected_indent(self):465 self._check_error("foo()\n bar()\n", "unexpected indent",466 subclass=IndentationError)467 def test_no_indent(self):468 self._check_error("if 1:\nfoo()", "expected an indented block",469 subclass=IndentationError)470 def test_bad_outdent(self):471 self._check_error("if 1:\n foo()\n bar()",472 "unindent does not match .* level",473 subclass=IndentationError)474 def test_kwargs_last(self):475 self._check_error("int(base=10, '2')", "non-keyword arg")476def test_main():477 test_support.run_unittest(SyntaxTestCase)478 from test import test_syntax479 with test_support.check_py3k_warnings(("backquote not supported",480 SyntaxWarning)):481 test_support.run_doctest(test_syntax, verbosity=True)482if __name__ == "__main__":...

Full Screen

Full Screen

syntaxerror.py

Source:syntaxerror.py Github

copy

Full Screen

...3 exec4except NameError:5 print("SKIP")6 raise SystemExit7def test_syntax(code):8 try:9 exec(code)10 print("no SyntaxError")11 except IndentationError:12 print("IndentationError")13 except SyntaxError:14 print("SyntaxError")15# non-newline after line-continuation character (lexer error)16test_syntax("a \\a\n")17# dedent mismatch (lexer error)18test_syntax("def f():\n a\n a\n")19# unclosed string (lexer error)20test_syntax("'abc")21# invalid (lexer error)22test_syntax("!")23test_syntax("$")24test_syntax("`")25# bad indentation (lexer error)26test_syntax(" a\n")27# malformed integer literal (parser error)28test_syntax("123z")29# input doesn't match the grammar (parser error)30test_syntax('1 or 2 or')31test_syntax('{1:')32# can't assign to literals33test_syntax("1 = 2")34test_syntax("'' = 1")35test_syntax("{} = 1")36# can't assign to comprehension37test_syntax("(i for i in a) = 1")38# can't assign to function39test_syntax("f() = 1")40# can't assign to power41test_syntax("f**2 = 1")42# can't assign to power of composite43test_syntax("f[0]**2 = 1")44# can't have *x on RHS45test_syntax("x = *x")46# can't have multiple *x on LHS47test_syntax("*a, *b = c")48# can't do augmented assignment to tuple49test_syntax("a, b += c")50test_syntax("(a, b) += c")51# can't do augmented assignment to list52test_syntax("[a, b] += c")53# non-default argument can't follow default argument54test_syntax("def f(a=1, b): pass")55# can't delete these things56test_syntax("del f()")57test_syntax("del f[0]**2")58test_syntax("del (a for a in a)")59# must be in a "loop"60test_syntax("break")61test_syntax("continue")62# must be in a function63test_syntax("yield")64test_syntax("nonlocal a")65test_syntax("await 1")66# error on uPy, warning on CPy67#test_syntax("def f():\n a = 1\n global a")68# default except must be last69test_syntax("try:\n a\nexcept:\n pass\nexcept:\n pass")70# LHS of keywords must be id's71test_syntax("f(1=2)")72# non-keyword after keyword73test_syntax("f(a=1, 2)")74# doesn't error on uPy but should75#test_syntax("f(1, i for i in i)")76# all elements of dict/set must be pairs or singles77test_syntax("{1:2, 3}")78test_syntax("{1, 2:3}")79# can't mix non-bytes with bytes when concatenating80test_syntax("'abc' b'def'")81# can't reuse same name for argument82test_syntax("def f(a, a): pass")83# nonlocal must exist in outer function/class scope84test_syntax("def f():\n def g():\n nonlocal a")85# param can't be redefined as global86test_syntax('def f(x):\n global x')87# param can't be redefined as nonlocal88test_syntax('def f(x):\n nonlocal x')89# can define variable to be both nonlocal and global90test_syntax('def f():\n nonlocal x\n global x')91# can't have multiple *'s92test_syntax('def f(x, *a, *):\n pass')93test_syntax('lambda x, *a, *: 1')94# **kw must be last95test_syntax('def f(x, *a, **kw, r):\n pass')...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run green automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful