| 1 |
|
| 2 |
import random |
| 3 |
import string |
| 4 |
import sys |
| 5 |
import pytest |
| 6 |
import functools |
| 7 |
import textwrap |
| 8 |
from pypy.interpreter.baseobjspace import W_Root |
| 9 |
from pypy.interpreter.pyparser import pyparse |
| 10 |
from pypy.interpreter.pyparser.error import SyntaxError |
| 11 |
from pypy.interpreter.error import OperationError |
| 12 |
from pypy.interpreter.astcompiler import ast, consts |
| 13 |
|
| 14 |
|
| 15 |
class TestAstBuilding: |
| 16 |
|
| 17 |
def setup_class(cls): |
| 18 |
cls.parser = pyparse.PegParser(cls.space) |
| 19 |
|
| 20 |
def setup_method(self, method): |
| 21 |
self.info = None |
| 22 |
|
| 23 |
def get_ast(self, source, p_mode=None, flags=None, with_async_hacks=False): |
| 24 |
if p_mode is None: |
| 25 |
p_mode = "exec" |
| 26 |
if flags is None: |
| 27 |
flags = consts.CO_FUTURE_WITH_STATEMENT |
| 28 |
if with_async_hacks: |
| 29 |
flags |= consts.PyCF_ASYNC_HACKS |
| 30 |
info = pyparse.CompileInfo("<test>", p_mode, flags) |
| 31 |
self.info = info |
| 32 |
ast_node = self.parser.parse_source(source, info) |
| 33 |
ast_node.to_object(self.space) |
| 34 |
return ast_node |
| 35 |
|
| 36 |
def get_first_expr(self, source, p_mode=None, flags=None): |
| 37 |
mod = self.get_ast(source, p_mode, flags) |
| 38 |
assert len(mod.body) == 1 |
| 39 |
expr = mod.body[0] |
| 40 |
assert isinstance(expr, ast.Expr) |
| 41 |
return expr.value |
| 42 |
|
| 43 |
def get_first_stmt(self, source, p_mode=None, flags=None): |
| 44 |
mod = self.get_ast(source, p_mode, flags) |
| 45 |
assert len(mod.body) == 1 |
| 46 |
return mod.body[0] |
| 47 |
|
| 48 |
def test_top_level(self): |
| 49 |
mod = self.get_ast("hi = 32") |
| 50 |
assert isinstance(mod, ast.Module) |
| 51 |
body = mod.body |
| 52 |
assert len(body) == 1 |
| 53 |
|
| 54 |
mod = self.get_ast("hi", p_mode="eval") |
| 55 |
assert isinstance(mod, ast.Expression) |
| 56 |
assert isinstance(mod.body, ast.expr) |
| 57 |
|
| 58 |
mod = self.get_ast("x = 23", p_mode="single") |
| 59 |
assert isinstance(mod, ast.Interactive) |
| 60 |
assert len(mod.body) == 1 |
| 61 |
mod = self.get_ast("x = 23; y = 23; b = 23", p_mode="single") |
| 62 |
assert isinstance(mod, ast.Interactive) |
| 63 |
assert len(mod.body) == 3 |
| 64 |
for stmt in mod.body: |
| 65 |
assert isinstance(stmt, ast.Assign) |
| 66 |
assert mod.body[-1].targets[0].id == "b" |
| 67 |
|
| 68 |
mod = self.get_ast("x = 23; y = 23; b = 23") |
| 69 |
assert isinstance(mod, ast.Module) |
| 70 |
assert len(mod.body) == 3 |
| 71 |
for stmt in mod.body: |
| 72 |
assert isinstance(stmt, ast.Assign) |
| 73 |
|
| 74 |
def test_constant_kind_bug(self): |
| 75 |
d = self.get_first_expr("None") |
| 76 |
|
| 77 |
def test_del(self): |
| 78 |
d = self.get_first_stmt("del x") |
| 79 |
assert isinstance(d, ast.Delete) |
| 80 |
assert len(d.targets) == 1 |
| 81 |
assert isinstance(d.targets[0], ast.Name) |
| 82 |
assert d.targets[0].ctx == ast.Del |
| 83 |
d = self.get_first_stmt("del x, y") |
| 84 |
assert len(d.targets) == 2 |
| 85 |
assert d.targets[0].ctx == ast.Del |
| 86 |
assert d.targets[1].ctx == ast.Del |
| 87 |
d = self.get_first_stmt("del x.y") |
| 88 |
assert len(d.targets) == 1 |
| 89 |
attr = d.targets[0] |
| 90 |
assert isinstance(attr, ast.Attribute) |
| 91 |
assert attr.ctx == ast.Del |
| 92 |
d = self.get_first_stmt("del x[:]") |
| 93 |
assert len(d.targets) == 1 |
| 94 |
sub = d.targets[0] |
| 95 |
assert isinstance(sub, ast.Subscript) |
| 96 |
assert sub.ctx == ast.Del |
| 97 |
|
| 98 |
def test_break(self): |
| 99 |
br = self.get_first_stmt("while True: break").body[0] |
| 100 |
assert isinstance(br, ast.Break) |
| 101 |
|
| 102 |
def test_continue(self): |
| 103 |
cont = self.get_first_stmt("while True: continue").body[0] |
| 104 |
assert isinstance(cont, ast.Continue) |
| 105 |
|
| 106 |
def test_return(self): |
| 107 |
ret = self.get_first_stmt("def f(): return").body[0] |
| 108 |
assert isinstance(ret, ast.Return) |
| 109 |
assert ret.value is None |
| 110 |
ret = self.get_first_stmt("def f(): return x").body[0] |
| 111 |
assert isinstance(ret.value, ast.Name) |
| 112 |
|
| 113 |
def test_raise(self): |
| 114 |
ra = self.get_first_stmt("raise") |
| 115 |
assert ra.exc is None |
| 116 |
assert ra.cause is None |
| 117 |
ra = self.get_first_stmt("raise x") |
| 118 |
assert isinstance(ra.exc, ast.Name) |
| 119 |
assert ra.cause is None |
| 120 |
ra = self.get_first_stmt("raise x from 3") |
| 121 |
assert isinstance(ra.exc, ast.Name) |
| 122 |
assert isinstance(ra.cause, ast.Constant) |
| 123 |
|
| 124 |
def test_import(self): |
| 125 |
im = self.get_first_stmt("import x") |
| 126 |
assert isinstance(im, ast.Import) |
| 127 |
assert len(im.names) == 1 |
| 128 |
alias = im.names[0] |
| 129 |
assert isinstance(alias, ast.alias) |
| 130 |
assert alias.name == "x" |
| 131 |
assert alias.asname is None |
| 132 |
im = self.get_first_stmt("import x.y") |
| 133 |
assert len(im.names) == 1 |
| 134 |
alias = im.names[0] |
| 135 |
assert alias.name == "x.y" |
| 136 |
assert alias.asname is None |
| 137 |
im = self.get_first_stmt("import x as y") |
| 138 |
assert len(im.names) == 1 |
| 139 |
alias = im.names[0] |
| 140 |
assert alias.name == "x" |
| 141 |
assert alias.asname == "y" |
| 142 |
im = self.get_first_stmt("import x, y as w") |
| 143 |
assert len(im.names) == 2 |
| 144 |
a1, a2 = im.names |
| 145 |
assert a1.name == "x" |
| 146 |
assert a1.asname is None |
| 147 |
assert a2.name == "y" |
| 148 |
assert a2.asname == "w" |
| 149 |
with pytest.raises(SyntaxError) as excinfo: |
| 150 |
self.get_ast("import x a b") |
| 151 |
assert excinfo.value.text == "import x a b\n" |
| 152 |
|
| 153 |
def test_from_import(self): |
| 154 |
im = self.get_first_stmt("from x import y") |
| 155 |
assert isinstance(im, ast.ImportFrom) |
| 156 |
assert im.module == "x" |
| 157 |
assert im.level == 0 |
| 158 |
assert len(im.names) == 1 |
| 159 |
a = im.names[0] |
| 160 |
assert isinstance(a, ast.alias) |
| 161 |
assert a.name == "y" |
| 162 |
assert a.asname is None |
| 163 |
im = self.get_first_stmt("from . import y") |
| 164 |
assert im.level == 1 |
| 165 |
assert im.module is None |
| 166 |
im = self.get_first_stmt("from ... import y") |
| 167 |
assert im.level == 3 |
| 168 |
assert im.module is None |
| 169 |
im = self.get_first_stmt("from .x import y") |
| 170 |
assert im.level == 1 |
| 171 |
assert im.module == "x" |
| 172 |
im = self.get_first_stmt("from ..x.y import m") |
| 173 |
assert im.level == 2 |
| 174 |
assert im.module == "x.y" |
| 175 |
im = self.get_first_stmt("from x import *") |
| 176 |
assert len(im.names) == 1 |
| 177 |
a = im.names[0] |
| 178 |
assert a.name == "*" |
| 179 |
assert a.asname is None |
| 180 |
for input in ("from x import x, y", "from x import (x, y)"): |
| 181 |
im = self.get_first_stmt(input) |
| 182 |
assert len(im.names) == 2 |
| 183 |
a1, a2 = im.names |
| 184 |
assert a1.name == "x" |
| 185 |
assert a1.asname is None |
| 186 |
assert a2.name == "y" |
| 187 |
assert a2.asname is None |
| 188 |
for input in ("from x import a as b, w", "from x import (a as b, w)"): |
| 189 |
im = self.get_first_stmt(input) |
| 190 |
assert len(im.names) == 2 |
| 191 |
a1, a2 = im.names |
| 192 |
assert a1.name == "a" |
| 193 |
assert a1.asname == "b" |
| 194 |
assert a2.name == "w" |
| 195 |
assert a2.asname is None |
| 196 |
|
| 197 |
input = "from x import y a b" |
| 198 |
with pytest.raises(SyntaxError) as excinfo: |
| 199 |
self.get_ast(input) |
| 200 |
assert excinfo.value.text == input + "\n" |
| 201 |
|
| 202 |
input = "from x import a, b," |
| 203 |
with pytest.raises(SyntaxError) as excinfo: |
| 204 |
self.get_ast(input) |
| 205 |
assert excinfo.value.msg == "trailing comma not allowed without surrounding " \ |
| 206 |
"parentheses" |
| 207 |
assert excinfo.value.text == input + "\n" |
| 208 |
|
| 209 |
def test_global(self): |
| 210 |
glob = self.get_first_stmt("global x") |
| 211 |
assert isinstance(glob, ast.Global) |
| 212 |
assert glob.names == ["x"] |
| 213 |
glob = self.get_first_stmt("global x, y") |
| 214 |
assert glob.names == ["x", "y"] |
| 215 |
|
| 216 |
def test_nonlocal(self): |
| 217 |
nonloc = self.get_first_stmt("nonlocal x") |
| 218 |
assert isinstance(nonloc, ast.Nonlocal) |
| 219 |
assert nonloc.names == ["x"] |
| 220 |
nonloc = self.get_first_stmt("nonlocal x, y") |
| 221 |
assert nonloc.names == ["x", "y"] |
| 222 |
|
| 223 |
def test_assert(self): |
| 224 |
asrt = self.get_first_stmt("assert x") |
| 225 |
assert isinstance(asrt, ast.Assert) |
| 226 |
assert isinstance(asrt.test, ast.Name) |
| 227 |
assert asrt.msg is None |
| 228 |
asrt = self.get_first_stmt("assert x, 'hi'") |
| 229 |
assert isinstance(asrt.test, ast.Name) |
| 230 |
assert isinstance(asrt.msg, ast.Constant) |
| 231 |
|
| 232 |
def test_suite(self): |
| 233 |
suite = self.get_first_stmt("while x: n;").body |
| 234 |
assert len(suite) == 1 |
| 235 |
assert isinstance(suite[0].value, ast.Name) |
| 236 |
suite = self.get_first_stmt("while x: n").body |
| 237 |
assert len(suite) == 1 |
| 238 |
suite = self.get_first_stmt("while x: \n n;").body |
| 239 |
assert len(suite) == 1 |
| 240 |
suite = self.get_first_stmt("while x: n;").body |
| 241 |
assert len(suite) == 1 |
| 242 |
suite = self.get_first_stmt("while x:\n n; f;").body |
| 243 |
assert len(suite) == 2 |
| 244 |
|
| 245 |
def test_if(self): |
| 246 |
if_ = self.get_first_stmt("if x: 4") |
| 247 |
assert isinstance(if_, ast.If) |
| 248 |
assert isinstance(if_.test, ast.Name) |
| 249 |
assert if_.test.ctx == ast.Load |
| 250 |
assert len(if_.body) == 1 |
| 251 |
assert isinstance(if_.body[0].value, ast.Constant) |
| 252 |
assert if_.orelse is None |
| 253 |
if_ = self.get_first_stmt("if x: 4\nelse: 'hi'") |
| 254 |
assert isinstance(if_.test, ast.Name) |
| 255 |
assert len(if_.body) == 1 |
| 256 |
assert isinstance(if_.body[0].value, ast.Constant) |
| 257 |
assert len(if_.orelse) == 1 |
| 258 |
assert isinstance(if_.orelse[0].value, ast.Constant) |
| 259 |
if_ = self.get_first_stmt("if x: 3\nelif 'hi': pass") |
| 260 |
assert isinstance(if_.test, ast.Name) |
| 261 |
assert len(if_.orelse) == 1 |
| 262 |
sub_if = if_.orelse[0] |
| 263 |
assert isinstance(sub_if, ast.If) |
| 264 |
assert isinstance(sub_if.test, ast.Constant) |
| 265 |
assert sub_if.orelse is None |
| 266 |
if_ = self.get_first_stmt("if x: pass\nelif 'hi': 3\nelse: ()") |
| 267 |
assert isinstance(if_.test, ast.Name) |
| 268 |
assert len(if_.body) == 1 |
| 269 |
assert isinstance(if_.body[0], ast.Pass) |
| 270 |
assert len(if_.orelse) == 1 |
| 271 |
sub_if = if_.orelse[0] |
| 272 |
assert isinstance(sub_if, ast.If) |
| 273 |
assert isinstance(sub_if.test, ast.Constant) |
| 274 |
assert len(sub_if.body) == 1 |
| 275 |
assert isinstance(sub_if.body[0].value, ast.Constant) |
| 276 |
assert len(sub_if.orelse) == 1 |
| 277 |
assert isinstance(sub_if.orelse[0].value, ast.Tuple) |
| 278 |
|
| 279 |
def test_elif_pos_bug(self): |
| 280 |
if_ = self.get_first_stmt("if x: 3\nelif \\\n 'hi': pass") |
| 281 |
assert isinstance(if_.test, ast.Name) |
| 282 |
assert len(if_.orelse) == 1 |
| 283 |
sub_if = if_.orelse[0] |
| 284 |
assert sub_if.lineno == 2 |
| 285 |
assert sub_if.col_offset == 0 |
| 286 |
if_ = self.get_first_stmt("if x: 3\nelif \\\n 'hi': pass\nelse: pass") |
| 287 |
assert isinstance(if_.test, ast.Name) |
| 288 |
assert len(if_.orelse) == 1 |
| 289 |
sub_if = if_.orelse[0] |
| 290 |
assert sub_if.lineno == 2 |
| 291 |
assert sub_if.col_offset == 0 |
| 292 |
|
| 293 |
def test_while(self): |
| 294 |
wh = self.get_first_stmt("while x: pass") |
| 295 |
assert isinstance(wh, ast.While) |
| 296 |
assert isinstance(wh.test, ast.Name) |
| 297 |
assert wh.test.ctx == ast.Load |
| 298 |
assert len(wh.body) == 1 |
| 299 |
assert isinstance(wh.body[0], ast.Pass) |
| 300 |
assert wh.orelse is None |
| 301 |
wh = self.get_first_stmt("while x: pass\nelse: 4") |
| 302 |
assert isinstance(wh.test, ast.Name) |
| 303 |
assert len(wh.body) == 1 |
| 304 |
assert isinstance(wh.body[0], ast.Pass) |
| 305 |
assert len(wh.orelse) == 1 |
| 306 |
assert isinstance(wh.orelse[0].value, ast.Constant) |
| 307 |
|
| 308 |
def test_for(self): |
| 309 |
fr = self.get_first_stmt("for x in y: pass") |
| 310 |
assert isinstance(fr, ast.For) |
| 311 |
assert isinstance(fr.target, ast.Name) |
| 312 |
assert fr.target.ctx == ast.Store |
| 313 |
assert isinstance(fr.iter, ast.Name) |
| 314 |
assert fr.iter.ctx == ast.Load |
| 315 |
assert len(fr.body) == 1 |
| 316 |
assert isinstance(fr.body[0], ast.Pass) |
| 317 |
assert fr.orelse is None |
| 318 |
fr = self.get_first_stmt("for x, in y: pass") |
| 319 |
tup = fr.target |
| 320 |
assert isinstance(tup, ast.Tuple) |
| 321 |
assert tup.ctx == ast.Store |
| 322 |
assert len(tup.elts) == 1 |
| 323 |
assert isinstance(tup.elts[0], ast.Name) |
| 324 |
assert tup.elts[0].ctx == ast.Store |
| 325 |
fr = self.get_first_stmt("for x, y in g: pass") |
| 326 |
tup = fr.target |
| 327 |
assert isinstance(tup, ast.Tuple) |
| 328 |
assert tup.ctx == ast.Store |
| 329 |
assert len(tup.elts) == 2 |
| 330 |
for elt in tup.elts: |
| 331 |
assert isinstance(elt, ast.Name) |
| 332 |
assert elt.ctx == ast.Store |
| 333 |
fr = self.get_first_stmt("for x in g: pass\nelse: 4") |
| 334 |
assert len(fr.body) == 1 |
| 335 |
assert isinstance(fr.body[0], ast.Pass) |
| 336 |
assert len(fr.orelse) == 1 |
| 337 |
assert isinstance(fr.orelse[0].value, ast.Constant) |
| 338 |
|
| 339 |
def test_try(self): |
| 340 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 341 |
"finally: pass") |
| 342 |
assert isinstance(tr, ast.Try) |
| 343 |
assert len(tr.body) == 1 |
| 344 |
assert isinstance(tr.body[0].value, ast.Name) |
| 345 |
assert len(tr.finalbody) == 1 |
| 346 |
assert isinstance(tr.finalbody[0], ast.Pass) |
| 347 |
assert tr.orelse is None |
| 348 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 349 |
"except: pass") |
| 350 |
assert isinstance(tr, ast.Try) |
| 351 |
assert len(tr.body) == 1 |
| 352 |
assert isinstance(tr.body[0].value, ast.Name) |
| 353 |
assert len(tr.handlers) == 1 |
| 354 |
handler = tr.handlers[0] |
| 355 |
assert isinstance(handler, ast.excepthandler) |
| 356 |
assert handler.type is None |
| 357 |
assert handler.name is None |
| 358 |
assert len(handler.body) == 1 |
| 359 |
assert isinstance(handler.body[0], ast.Pass) |
| 360 |
assert tr.orelse is None |
| 361 |
assert tr.finalbody is None |
| 362 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 363 |
"except Exception: pass") |
| 364 |
assert len(tr.handlers) == 1 |
| 365 |
handler = tr.handlers[0] |
| 366 |
assert isinstance(handler.type, ast.Name) |
| 367 |
assert handler.type.ctx == ast.Load |
| 368 |
assert handler.name is None |
| 369 |
assert len(handler.body) == 1 |
| 370 |
assert tr.orelse is None |
| 371 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 372 |
"except Exception as e: pass") |
| 373 |
assert len(tr.handlers) == 1 |
| 374 |
handler = tr.handlers[0] |
| 375 |
assert isinstance(handler.type, ast.Name) |
| 376 |
assert handler.type.id == "Exception" |
| 377 |
assert handler.name == "e" |
| 378 |
assert len(handler.body) == 1 |
| 379 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 380 |
"except: pass" + "\n" + |
| 381 |
"else: 4") |
| 382 |
assert len(tr.body) == 1 |
| 383 |
assert isinstance(tr.body[0].value, ast.Name) |
| 384 |
assert len(tr.handlers) == 1 |
| 385 |
assert isinstance(tr.handlers[0].body[0], ast.Pass) |
| 386 |
assert len(tr.orelse) == 1 |
| 387 |
assert isinstance(tr.orelse[0].value, ast.Constant) |
| 388 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 389 |
"except Exc as a: 5" + "\n" + |
| 390 |
"except F: pass") |
| 391 |
assert len(tr.handlers) == 2 |
| 392 |
h1, h2 = tr.handlers |
| 393 |
assert isinstance(h1.type, ast.Name) |
| 394 |
assert h1.name == "a" |
| 395 |
assert isinstance(h1.body[0].value, ast.Constant) |
| 396 |
assert isinstance(h2.type, ast.Name) |
| 397 |
assert h2.name is None |
| 398 |
assert isinstance(h2.body[0], ast.Pass) |
| 399 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 400 |
"except Exc as a: 5" + "\n" + |
| 401 |
"except F: pass") |
| 402 |
assert len(tr.handlers) == 2 |
| 403 |
h1, h2 = tr.handlers |
| 404 |
assert isinstance(h1.type, ast.Name) |
| 405 |
assert h1.name == "a" |
| 406 |
assert isinstance(h1.body[0].value, ast.Constant) |
| 407 |
assert isinstance(h2.type, ast.Name) |
| 408 |
assert h2.name is None |
| 409 |
assert isinstance(h2.body[0], ast.Pass) |
| 410 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 411 |
"except: 4" + "\n" + |
| 412 |
"finally: pass") |
| 413 |
assert isinstance(tr, ast.Try) |
| 414 |
assert len(tr.finalbody) == 1 |
| 415 |
assert isinstance(tr.finalbody[0], ast.Pass) |
| 416 |
assert len(tr.handlers) == 1 |
| 417 |
assert len(tr.handlers[0].body) == 1 |
| 418 |
assert isinstance(tr.handlers[0].body[0].value, ast.Constant) |
| 419 |
assert len(tr.body) == 1 |
| 420 |
assert isinstance(tr.body[0].value, ast.Name) |
| 421 |
tr = self.get_first_stmt("try: x" + "\n" + |
| 422 |
"except: 4" + "\n" + |
| 423 |
"else: 'hi'" + "\n" + |
| 424 |
"finally: pass") |
| 425 |
assert isinstance(tr, ast.Try) |
| 426 |
assert len(tr.finalbody) == 1 |
| 427 |
assert isinstance(tr.finalbody[0], ast.Pass) |
| 428 |
assert len(tr.body) == 1 |
| 429 |
assert len(tr.orelse) == 1 |
| 430 |
assert isinstance(tr.orelse[0].value, ast.Constant) |
| 431 |
assert len(tr.body) == 1 |
| 432 |
assert isinstance(tr.body[0].value, ast.Name) |
| 433 |
assert len(tr.handlers) == 1 |
| 434 |
|
| 435 |
def test_with(self): |
| 436 |
wi = self.get_first_stmt("with x: pass") |
| 437 |
assert isinstance(wi, ast.With) |
| 438 |
assert len(wi.items) == 1 |
| 439 |
assert isinstance(wi.items[0], ast.withitem) |
| 440 |
assert isinstance(wi.items[0].context_expr, ast.Name) |
| 441 |
assert wi.items[0].optional_vars is None |
| 442 |
assert len(wi.body) == 1 |
| 443 |
wi = self.get_first_stmt("with x as y: pass") |
| 444 |
assert isinstance(wi.items[0].context_expr, ast.Name) |
| 445 |
assert len(wi.body) == 1 |
| 446 |
assert isinstance(wi.items[0].optional_vars, ast.Name) |
| 447 |
assert wi.items[0].optional_vars.ctx == ast.Store |
| 448 |
wi = self.get_first_stmt("with x as (y,): pass") |
| 449 |
assert isinstance(wi.items[0].optional_vars, ast.Tuple) |
| 450 |
assert len(wi.items[0].optional_vars.elts) == 1 |
| 451 |
assert wi.items[0].optional_vars.ctx == ast.Store |
| 452 |
assert wi.items[0].optional_vars.elts[0].ctx == ast.Store |
| 453 |
input = "with x hi y: pass" |
| 454 |
with pytest.raises(SyntaxError) as excinfo: |
| 455 |
self.get_ast(input) |
| 456 |
wi = self.get_first_stmt("with x as y, b: pass") |
| 457 |
assert isinstance(wi, ast.With) |
| 458 |
assert len(wi.items) == 2 |
| 459 |
assert isinstance(wi.items[0].context_expr, ast.Name) |
| 460 |
assert wi.items[0].context_expr.id == "x" |
| 461 |
assert isinstance(wi.items[0].optional_vars, ast.Name) |
| 462 |
assert wi.items[0].optional_vars.id == "y" |
| 463 |
assert isinstance(wi.items[1].context_expr, ast.Name) |
| 464 |
assert wi.items[1].context_expr.id == "b" |
| 465 |
assert wi.items[1].optional_vars is None |
| 466 |
assert len(wi.body) == 1 |
| 467 |
assert isinstance(wi.body[0], ast.Pass) |
| 468 |
|
| 469 |
def test_class(self): |
| 470 |
for input in ("class X: pass", "class X(): pass"): |
| 471 |
cls = self.get_first_stmt(input) |
| 472 |
assert isinstance(cls, ast.ClassDef) |
| 473 |
assert cls.name == "X" |
| 474 |
assert len(cls.body) == 1 |
| 475 |
assert isinstance(cls.body[0], ast.Pass) |
| 476 |
assert cls.bases is None |
| 477 |
assert cls.decorator_list is None |
| 478 |
for input in ("class X(Y): pass", "class X(Y,): pass"): |
| 479 |
cls = self.get_first_stmt(input) |
| 480 |
assert len(cls.bases) == 1 |
| 481 |
base = cls.bases[0] |
| 482 |
assert isinstance(base, ast.Name) |
| 483 |
assert base.ctx == ast.Load |
| 484 |
assert base.id == "Y" |
| 485 |
assert cls.decorator_list is None |
| 486 |
cls = self.get_first_stmt("class X(Y, Z): pass") |
| 487 |
assert len(cls.bases) == 2 |
| 488 |
for b in cls.bases: |
| 489 |
assert isinstance(b, ast.Name) |
| 490 |
assert b.ctx == ast.Load |
| 491 |
|
| 492 |
with pytest.raises(SyntaxError) as info: |
| 493 |
self.get_ast("class A(x for x in T): pass") |
| 494 |
|
| 495 |
def test_function(self): |
| 496 |
func = self.get_first_stmt("def f(): pass") |
| 497 |
assert isinstance(func, ast.FunctionDef) |
| 498 |
assert func.name == "f" |
| 499 |
assert len(func.body) == 1 |
| 500 |
assert isinstance(func.body[0], ast.Pass) |
| 501 |
assert func.decorator_list is None |
| 502 |
args = func.args |
| 503 |
assert isinstance(args, ast.arguments) |
| 504 |
assert args.args is None |
| 505 |
assert args.defaults is None |
| 506 |
assert args.kwarg is None |
| 507 |
assert args.vararg is None |
| 508 |
assert func.returns is None |
| 509 |
args = self.get_first_stmt("def f(a, b): pass").args |
| 510 |
assert len(args.args) == 2 |
| 511 |
a1, a2 = args.args |
| 512 |
assert isinstance(a1, ast.arg) |
| 513 |
assert a1.arg == "a" |
| 514 |
assert isinstance(a2, ast.arg) |
| 515 |
assert a2.arg == "b" |
| 516 |
assert args.vararg is None |
| 517 |
assert args.kwarg is None |
| 518 |
args = self.get_first_stmt("def f(a=b): pass").args |
| 519 |
assert len(args.args) == 1 |
| 520 |
arg = args.args[0] |
| 521 |
assert isinstance(arg, ast.arg) |
| 522 |
assert arg.arg == "a" |
| 523 |
assert len(args.defaults) == 1 |
| 524 |
default = args.defaults[0] |
| 525 |
assert isinstance(default, ast.Name) |
| 526 |
assert default.id == "b" |
| 527 |
assert default.ctx == ast.Load |
| 528 |
args = self.get_first_stmt("def f(*a): pass").args |
| 529 |
assert not args.args |
| 530 |
assert not args.defaults |
| 531 |
assert args.kwarg is None |
| 532 |
assert args.vararg.arg == "a" |
| 533 |
args = self.get_first_stmt("def f(**a): pass").args |
| 534 |
assert not args.args |
| 535 |
assert not args.defaults |
| 536 |
assert args.vararg is None |
| 537 |
assert args.kwarg.arg == "a" |
| 538 |
args = self.get_first_stmt("def f(a, b, c=d, *e, **f): pass").args |
| 539 |
assert len(args.args) == 3 |
| 540 |
for arg in args.args: |
| 541 |
assert isinstance(arg, ast.arg) |
| 542 |
assert len(args.defaults) == 1 |
| 543 |
assert isinstance(args.defaults[0], ast.Name) |
| 544 |
assert args.defaults[0].ctx == ast.Load |
| 545 |
assert args.vararg.arg == "e" |
| 546 |
assert args.kwarg.arg == "f" |
| 547 |
input = "def f(a=b, c): pass" |
| 548 |
with pytest.raises(SyntaxError) as excinfo: |
| 549 |
self.get_ast(input) |
| 550 |
assert excinfo.value.msg == "non-default argument follows default argument" |
| 551 |
input = "def f((x)=23): pass" |
| 552 |
with pytest.raises(SyntaxError) as excinfo: |
| 553 |
self.get_ast(input) |
| 554 |
assert excinfo.value.msg == "Function parameters cannot be parenthesized" |
| 555 |
|
| 556 |
def test_kwonly_arguments(self): |
| 557 |
fn = self.get_first_stmt("def f(a, b, c, *, kwarg): pass") |
| 558 |
assert isinstance(fn, ast.FunctionDef) |
| 559 |
assert len(fn.args.kwonlyargs) == 1 |
| 560 |
assert isinstance(fn.args.kwonlyargs[0], ast.arg) |
| 561 |
assert fn.args.kwonlyargs[0].arg == "kwarg" |
| 562 |
assert fn.args.kw_defaults == [None] |
| 563 |
fn = self.get_first_stmt("def f(a, b, c, *args, kwarg): pass") |
| 564 |
assert isinstance(fn, ast.FunctionDef) |
| 565 |
assert len(fn.args.kwonlyargs) == 1 |
| 566 |
assert isinstance(fn.args.kwonlyargs[0], ast.arg) |
| 567 |
assert fn.args.kwonlyargs[0].arg == "kwarg" |
| 568 |
assert fn.args.kw_defaults == [None] |
| 569 |
fn = self.get_first_stmt("def f(a, b, c, *, kwarg=2): pass") |
| 570 |
assert isinstance(fn, ast.FunctionDef) |
| 571 |
assert len(fn.args.kwonlyargs) == 1 |
| 572 |
assert isinstance(fn.args.kwonlyargs[0], ast.arg) |
| 573 |
assert fn.args.kwonlyargs[0].arg == "kwarg" |
| 574 |
assert len(fn.args.kw_defaults) == 1 |
| 575 |
assert isinstance(fn.args.kw_defaults[0], ast.Constant) |
| 576 |
input = "def f(p1, *, **k1): pass" |
| 577 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 578 |
assert exc.msg == "named arguments must follow bare *" |
| 579 |
input = "def foo(a,*b=3,c):" |
| 580 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 581 |
assert exc.msg == "var-positional argument cannot have default value" |
| 582 |
input = "lambda a,*b=3,c: 12" |
| 583 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 584 |
assert exc.msg == "var-positional argument cannot have default value" |
| 585 |
input = "lambda *b,*d: 12" |
| 586 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 587 |
assert exc.msg == "* argument may appear only once" |
| 588 |
|
| 589 |
def test_posonly_arguments(self): |
| 590 |
fn = self.get_first_stmt("def f(a, b, c, /, arg): pass") |
| 591 |
assert isinstance(fn, ast.FunctionDef) |
| 592 |
assert len(fn.args.posonlyargs) == 3 |
| 593 |
assert len(fn.args.args) == 1 |
| 594 |
assert isinstance(fn.args.args[0], ast.arg) |
| 595 |
assert fn.args.args[0].arg == "arg" |
| 596 |
|
| 597 |
def test_function_annotation(self): |
| 598 |
func = self.get_first_stmt("def f() -> X: pass") |
| 599 |
assert isinstance(func.returns, ast.Name) |
| 600 |
assert func.returns.id == "X" |
| 601 |
assert func.returns.ctx == ast.Load |
| 602 |
for stmt in "def f(x : 42): pass", "def f(x : 42=a): pass": |
| 603 |
func = self.get_first_stmt(stmt) |
| 604 |
assert isinstance(func.args.args[0].annotation, ast.Constant) |
| 605 |
assert isinstance(func.args.defaults[0], ast.Name) |
| 606 |
func = self.get_first_stmt("def f(*x : 42): pass") |
| 607 |
assert isinstance(func.args.vararg.annotation, ast.Constant) |
| 608 |
func = self.get_first_stmt("def f(**kw : 42): pass") |
| 609 |
assert isinstance(func.args.kwarg.annotation, ast.Constant) |
| 610 |
func = self.get_first_stmt("def f(*, kw : 42=a): pass") |
| 611 |
assert isinstance(func.args.kwonlyargs[0].annotation, ast.Constant) |
| 612 |
|
| 613 |
def test_lots_of_kwonly_arguments(self): |
| 614 |
fundef = "def f(" |
| 615 |
for i in range(255): |
| 616 |
fundef += "i%d, "%i |
| 617 |
fundef += "*, key=100):\n pass\n" |
| 618 |
self.get_first_stmt(fundef) |
| 619 |
|
| 620 |
fundef2 = "def foo(i,*," |
| 621 |
for i in range(255): |
| 622 |
fundef2 += "i%d, "%i |
| 623 |
fundef2 += "lastarg):\n pass\n" |
| 624 |
self.get_first_stmt(fundef2) |
| 625 |
|
| 626 |
fundef3 = "def f(i,*," |
| 627 |
for i in range(253): |
| 628 |
fundef3 += "i%d, "%i |
| 629 |
fundef3 += "lastarg):\n pass\n" |
| 630 |
self.get_first_stmt(fundef3) |
| 631 |
|
| 632 |
def test_decorators(self): |
| 633 |
to_examine = (("def f(): pass", ast.FunctionDef), |
| 634 |
("class x: pass", ast.ClassDef)) |
| 635 |
for stmt, node in to_examine: |
| 636 |
definition = self.get_first_stmt("@dec\n%s" % (stmt,)) |
| 637 |
assert isinstance(definition, node) |
| 638 |
assert len(definition.decorator_list) == 1 |
| 639 |
dec = definition.decorator_list[0] |
| 640 |
assert isinstance(dec, ast.Name) |
| 641 |
assert dec.id == "dec" |
| 642 |
assert dec.ctx == ast.Load |
| 643 |
definition = self.get_first_stmt("@mod.hi.dec\n%s" % (stmt,)) |
| 644 |
assert len(definition.decorator_list) == 1 |
| 645 |
dec = definition.decorator_list[0] |
| 646 |
assert isinstance(dec, ast.Attribute) |
| 647 |
assert dec.ctx == ast.Load |
| 648 |
assert dec.attr == "dec" |
| 649 |
assert isinstance(dec.value, ast.Attribute) |
| 650 |
assert dec.value.attr == "hi" |
| 651 |
assert isinstance(dec.value.value, ast.Name) |
| 652 |
assert dec.value.value.id == "mod" |
| 653 |
definition = self.get_first_stmt("@dec\n@dec2\n%s" % (stmt,)) |
| 654 |
assert len(definition.decorator_list) == 2 |
| 655 |
for dec in definition.decorator_list: |
| 656 |
assert isinstance(dec, ast.Name) |
| 657 |
assert dec.ctx == ast.Load |
| 658 |
assert definition.decorator_list[0].id == "dec" |
| 659 |
assert definition.decorator_list[1].id == "dec2" |
| 660 |
definition = self.get_first_stmt("@dec()\n%s" % (stmt,)) |
| 661 |
assert len(definition.decorator_list) == 1 |
| 662 |
dec = definition.decorator_list[0] |
| 663 |
assert isinstance(dec, ast.Call) |
| 664 |
assert isinstance(dec.func, ast.Name) |
| 665 |
assert dec.func.id == "dec" |
| 666 |
assert dec.args is None |
| 667 |
assert dec.keywords is None |
| 668 |
definition = self.get_first_stmt("@dec(a, b)\n%s" % (stmt,)) |
| 669 |
assert len(definition.decorator_list) == 1 |
| 670 |
dec = definition.decorator_list[0] |
| 671 |
assert isinstance(dec, ast.Call) |
| 672 |
assert dec.func.id == "dec" |
| 673 |
assert len(dec.args) == 2 |
| 674 |
assert dec.keywords is None |
| 675 |
|
| 676 |
def test_annassign(self): |
| 677 |
simple = self.get_first_stmt('a: int') |
| 678 |
assert isinstance(simple, ast.AnnAssign) |
| 679 |
assert isinstance(simple.target, ast.Name) |
| 680 |
assert simple.target.ctx == ast.Store |
| 681 |
assert isinstance(simple.annotation, ast.Name) |
| 682 |
assert simple.value == None |
| 683 |
assert simple.simple == 1 |
| 684 |
|
| 685 |
with_value = self.get_first_stmt('x: str = "test"') |
| 686 |
assert isinstance(with_value, ast.AnnAssign) |
| 687 |
assert isinstance(with_value.value, ast.Constant) |
| 688 |
assert self.space.eq_w(with_value.value.value, self.space.wrap("test")) |
| 689 |
|
| 690 |
not_simple = self.get_first_stmt('(a): int') |
| 691 |
assert isinstance(not_simple, ast.AnnAssign) |
| 692 |
assert isinstance(not_simple.target, ast.Name) |
| 693 |
assert not_simple.target.ctx == ast.Store |
| 694 |
assert not_simple.simple == 0 |
| 695 |
|
| 696 |
attrs = self.get_first_stmt('a.b.c: int') |
| 697 |
assert isinstance(attrs, ast.AnnAssign) |
| 698 |
assert isinstance(attrs.target, ast.Attribute) |
| 699 |
|
| 700 |
subscript = self.get_first_stmt('a[0:2]: int') |
| 701 |
assert isinstance(subscript, ast.AnnAssign) |
| 702 |
assert isinstance(subscript.target, ast.Subscript) |
| 703 |
|
| 704 |
exc_tuple = pytest.raises(SyntaxError, self.get_ast, 'a, b: int').value |
| 705 |
assert exc_tuple.msg == "only single target (not tuple) can be annotated" |
| 706 |
|
| 707 |
exc_list = pytest.raises(SyntaxError, self.get_ast, '[]: int').value |
| 708 |
assert exc_list.msg == "only single target (not list) can be annotated" |
| 709 |
|
| 710 |
exc_bad_target = pytest.raises(SyntaxError, self.get_ast, '{}: int').value |
| 711 |
assert exc_bad_target.msg == "illegal target for annotation" |
| 712 |
|
| 713 |
|
| 714 |
def test_augassign(self): |
| 715 |
aug_assigns = ( |
| 716 |
("+=", ast.Add), |
| 717 |
("-=", ast.Sub), |
| 718 |
("/=", ast.Div), |
| 719 |
("//=", ast.FloorDiv), |
| 720 |
("%=", ast.Mod), |
| 721 |
("@=", ast.MatMult), |
| 722 |
("<<=", ast.LShift), |
| 723 |
(">>=", ast.RShift), |
| 724 |
("&=", ast.BitAnd), |
| 725 |
("|=", ast.BitOr), |
| 726 |
("^=", ast.BitXor), |
| 727 |
("*=", ast.Mult), |
| 728 |
("**=", ast.Pow) |
| 729 |
) |
| 730 |
for op, ast_type in aug_assigns: |
| 731 |
input = "x %s 4" % (op,) |
| 732 |
assign = self.get_first_stmt(input) |
| 733 |
assert isinstance(assign, ast.AugAssign) |
| 734 |
assert assign.op is ast_type |
| 735 |
assert isinstance(assign.target, ast.Name) |
| 736 |
assert assign.target.ctx == ast.Store |
| 737 |
assert isinstance(assign.value, ast.Constant) |
| 738 |
|
| 739 |
def test_assign(self): |
| 740 |
assign = self.get_first_stmt("hi = 32") |
| 741 |
assert isinstance(assign, ast.Assign) |
| 742 |
assert len(assign.targets) == 1 |
| 743 |
name = assign.targets[0] |
| 744 |
assert isinstance(name, ast.Name) |
| 745 |
assert name.ctx == ast.Store |
| 746 |
value = assign.value |
| 747 |
assert self.space.eq_w(value.value, self.space.wrap(32)) |
| 748 |
assign = self.get_first_stmt("hi, = something") |
| 749 |
assert len(assign.targets) == 1 |
| 750 |
tup = assign.targets[0] |
| 751 |
assert isinstance(tup, ast.Tuple) |
| 752 |
assert tup.ctx == ast.Store |
| 753 |
assert len(tup.elts) == 1 |
| 754 |
assert isinstance(tup.elts[0], ast.Name) |
| 755 |
assert tup.elts[0].ctx == ast.Store |
| 756 |
|
| 757 |
def test_assign_starred(self): |
| 758 |
assign = self.get_first_stmt("*a, b = x") |
| 759 |
assert isinstance(assign, ast.Assign) |
| 760 |
assert len(assign.targets) == 1 |
| 761 |
names = assign.targets[0] |
| 762 |
assert len(names.elts) == 2 |
| 763 |
assert isinstance(names.elts[0], ast.Starred) |
| 764 |
assert isinstance(names.elts[1], ast.Name) |
| 765 |
assert isinstance(names.elts[0].value, ast.Name) |
| 766 |
assert names.elts[0].value.id == "a" |
| 767 |
|
| 768 |
def test_name(self): |
| 769 |
name = self.get_first_expr("hi") |
| 770 |
assert isinstance(name, ast.Name) |
| 771 |
assert name.ctx == ast.Load |
| 772 |
|
| 773 |
def test_tuple(self): |
| 774 |
tup = self.get_first_expr("()") |
| 775 |
assert isinstance(tup, ast.Tuple) |
| 776 |
assert tup.elts is None |
| 777 |
assert tup.ctx == ast.Load |
| 778 |
tup = self.get_first_expr("(3,)") |
| 779 |
assert len(tup.elts) == 1 |
| 780 |
assert self.space.eq_w(tup.elts[0].value, self.space.wrap(3)) |
| 781 |
tup = self.get_first_expr("2, 3, 4") |
| 782 |
assert len(tup.elts) == 3 |
| 783 |
|
| 784 |
def test_list(self): |
| 785 |
seq = self.get_first_expr("[]") |
| 786 |
assert isinstance(seq, ast.List) |
| 787 |
assert seq.elts is None |
| 788 |
assert seq.ctx == ast.Load |
| 789 |
seq = self.get_first_expr("[3,]") |
| 790 |
assert len(seq.elts) == 1 |
| 791 |
assert self.space.eq_w(seq.elts[0].value, self.space.wrap(3)) |
| 792 |
seq = self.get_first_expr("[3]") |
| 793 |
assert len(seq.elts) == 1 |
| 794 |
seq = self.get_first_expr("[1, 2, 3, 4, 5]") |
| 795 |
assert len(seq.elts) == 5 |
| 796 |
nums = range(1, 6) |
| 797 |
assert [self.space.int_w(n.value) for n in seq.elts] == nums |
| 798 |
|
| 799 |
def test_dict(self): |
| 800 |
d = self.get_first_expr("{}") |
| 801 |
assert isinstance(d, ast.Dict) |
| 802 |
assert d.keys is None |
| 803 |
assert d.values is None |
| 804 |
d = self.get_first_expr("{4 : x, y : 7}") |
| 805 |
assert len(d.keys) == len(d.values) == 2 |
| 806 |
key1, key2 = d.keys |
| 807 |
assert isinstance(key1, ast.Constant) |
| 808 |
assert isinstance(key2, ast.Name) |
| 809 |
assert key2.ctx == ast.Load |
| 810 |
v1, v2 = d.values |
| 811 |
assert isinstance(v1, ast.Name) |
| 812 |
assert v1.ctx == ast.Load |
| 813 |
assert isinstance(v2, ast.Constant) |
| 814 |
|
| 815 |
def test_set(self): |
| 816 |
s = self.get_first_expr("{1}") |
| 817 |
assert isinstance(s, ast.Set) |
| 818 |
assert len(s.elts) == 1 |
| 819 |
assert isinstance(s.elts[0], ast.Constant) |
| 820 |
assert self.space.eq_w(s.elts[0].value, self.space.wrap(1)) |
| 821 |
s = self.get_first_expr("{0, 1, 2, 3, 4, 5}") |
| 822 |
assert isinstance(s, ast.Set) |
| 823 |
assert len(s.elts) == 6 |
| 824 |
for i, elt in enumerate(s.elts): |
| 825 |
assert isinstance(elt, ast.Constant) |
| 826 |
assert self.space.eq_w(elt.value, self.space.wrap(i)) |
| 827 |
|
| 828 |
def test_set_unpack(self): |
| 829 |
s = self.get_first_expr("{*{1}}") |
| 830 |
assert isinstance(s, ast.Set) |
| 831 |
assert len(s.elts) == 1 |
| 832 |
sta0 = s.elts[0] |
| 833 |
assert isinstance(sta0, ast.Starred) |
| 834 |
s0 = sta0.value |
| 835 |
assert isinstance(s0, ast.Set) |
| 836 |
assert len(s0.elts) == 1 |
| 837 |
assert isinstance(s0.elts[0], ast.Constant) |
| 838 |
assert self.space.eq_w(s0.elts[0].value, self.space.wrap(1)) |
| 839 |
s = self.get_first_expr("{*{0, 1, 2, 3, 4, 5}}") |
| 840 |
assert isinstance(s, ast.Set) |
| 841 |
assert len(s.elts) == 1 |
| 842 |
sta0 = s.elts[0] |
| 843 |
assert isinstance(sta0, ast.Starred) |
| 844 |
s0 = sta0.value |
| 845 |
assert isinstance(s0, ast.Set) |
| 846 |
assert len(s0.elts) == 6 |
| 847 |
for i, elt in enumerate(s0.elts): |
| 848 |
assert isinstance(elt, ast.Constant) |
| 849 |
assert self.space.eq_w(elt.value, self.space.wrap(i)) |
| 850 |
|
| 851 |
def test_set_context(self): |
| 852 |
tup = self.get_ast("(a, b) = c").body[0].targets[0] |
| 853 |
assert all(elt.ctx == ast.Store for elt in tup.elts) |
| 854 |
seq = self.get_ast("[a, b] = c").body[0].targets[0] |
| 855 |
assert all(elt.ctx == ast.Store for elt in seq.elts) |
| 856 |
invalid_stores = ( |
| 857 |
("(lambda x: x)", "lambda"), |
| 858 |
("f()", "function call"), |
| 859 |
("~x", "expression"), |
| 860 |
("+x", "expression"), |
| 861 |
("-x", "expression"), |
| 862 |
("(x or y)", "expression"), |
| 863 |
("(x and y)", "expression"), |
| 864 |
("(not g)", "expression"), |
| 865 |
("(x for y in g)", "generator expression"), |
| 866 |
("(yield x)", "yield expression"), |
| 867 |
("[x for y in g]", "list comprehension"), |
| 868 |
("{x for x in z}", "set comprehension"), |
| 869 |
("{x : x for x in z}", "dict comprehension"), |
| 870 |
("'str'", "literal"), |
| 871 |
("b'bytes'", "literal"), |
| 872 |
("23", "literal"), |
| 873 |
("{}", "dict literal"), |
| 874 |
("{1, 2, 3}", "set display"), |
| 875 |
("(x > 4)", "comparison"), |
| 876 |
("(x if y else a)", "conditional expression"), |
| 877 |
("...", "ellipsis"), |
| 878 |
) |
| 879 |
test_contexts = ( |
| 880 |
("assign to", "%s = 23"), |
| 881 |
("delete", "del %s") |
| 882 |
) |
| 883 |
for ctx_type, template in test_contexts: |
| 884 |
for expr, type_str in invalid_stores: |
| 885 |
input = template % (expr,) |
| 886 |
with pytest.raises(SyntaxError) as excinfo: |
| 887 |
self.get_ast(input) |
| 888 |
assert excinfo.value.msg.startswith("cannot %s %s" % (ctx_type, type_str)) |
| 889 |
|
| 890 |
def test_assignment_to_forbidden_names(self): |
| 891 |
space = self.space |
| 892 |
invalid = ( |
| 893 |
"%s = x", |
| 894 |
"%s, x = y", |
| 895 |
"[%s, x] = y", |
| 896 |
"[%s, x] = y", |
| 897 |
"*%s, x = y", |
| 898 |
"[*%s, x] = y", |
| 899 |
"def %s(): pass", |
| 900 |
"class %s(): pass", |
| 901 |
"def f(%s): pass", |
| 902 |
"def f(%s=x): pass", |
| 903 |
"def f(*%s): pass", |
| 904 |
"def f(**%s): pass", |
| 905 |
"f(%s=x)", |
| 906 |
"with x as %s: pass", |
| 907 |
"import %s", |
| 908 |
"import x as %s", |
| 909 |
"from x import %s", |
| 910 |
"from x import y as %s", |
| 911 |
"for %s in x: pass", |
| 912 |
"x.%s = y", |
| 913 |
"x.%s += y", |
| 914 |
"%s += 1", |
| 915 |
"(%s := 1)", |
| 916 |
) |
| 917 |
for name in "__debug__",: |
| 918 |
for template in invalid: |
| 919 |
input = template % (name,) |
| 920 |
ast = self.get_ast(input) |
| 921 |
ec = space.getexecutioncontext() |
| 922 |
with pytest.raises(OperationError) as excinfo: |
| 923 |
ec.compiler.compile_ast(ast, "", "exec") |
| 924 |
excinfo.value.normalize_exception(space) |
| 925 |
w_value = excinfo.value.get_w_value(space) |
| 926 |
msg = space.text_w(space.repr(w_value)) |
| 927 |
assert ("cannot assign to %s" % (name,)) in msg |
| 928 |
|
| 929 |
assert space.int_w(w_value.w_end_lineno) == space.int_w(w_value.w_lineno) == 1 |
| 930 |
offset = space.int_w(w_value.w_offset) |
| 931 |
assert offset >= 1 |
| 932 |
assert offset < space.int_w(w_value.w_end_offset) |
| 933 |
|
| 934 |
def test_delete_forbidden_name(self): |
| 935 |
invalid = ( |
| 936 |
"del %s", |
| 937 |
"del %s, a", |
| 938 |
"del [%s, a]", |
| 939 |
"del a.%s", |
| 940 |
) |
| 941 |
for name in "__debug__",: |
| 942 |
for template in invalid: |
| 943 |
input = template % (name,) |
| 944 |
ast = self.get_ast(input) |
| 945 |
ec = self.space.getexecutioncontext() |
| 946 |
with pytest.raises(OperationError) as excinfo: |
| 947 |
ec.compiler.compile_ast(ast, "", "exec") |
| 948 |
msg = self.space.text_w(self.space.repr(excinfo.value.get_w_value(self.space))) |
| 949 |
assert ("cannot delete %s" % (name,)) in msg |
| 950 |
|
| 951 |
def test_cannot_delete_messages(self): |
| 952 |
invalid = [ |
| 953 |
("del (1, x)", "cannot delete literal"), |
| 954 |
("del [x, z, a, {1, 2}]", "cannot delete set display"), |
| 955 |
("del [a, (b, *c)]", "cannot delete starred"), |
| 956 |
("del (a := 5)", "cannot delete named expression"), |
| 957 |
] |
| 958 |
for wrong, msg in invalid: |
| 959 |
with pytest.raises(SyntaxError) as excinfo: |
| 960 |
self.get_ast(wrong) |
| 961 |
assert msg in excinfo.value.msg |
| 962 |
|
| 963 |
def test_cannot_assign_messages(self): |
| 964 |
invalid = [ |
| 965 |
("(1, x) = 5", "cannot assign to literal", 2, 3), |
| 966 |
("[x, z, a, {1, 2}] = 12", "cannot assign to set display", 11, 17), |
| 967 |
("for (1, x) in []: pass", "cannot assign to literal"), |
| 968 |
("with foo as (1, 2): pass", "cannot assign to literal"), |
| 969 |
("(a, *True, c) = (1, 2, 3)", "cannot assign to True"), |
| 970 |
("for (x, *(y, z.d())) in b: pass", "cannot assign to function call", 14, 19), |
| 971 |
("1 + 2 = 3", "cannot assign to expression", 1, 6), |
| 972 |
("while a.x = 3:", "cannot assign to attribute", 7, 10), |
| 973 |
("while a[0] = 3:", "cannot assign to subscript", 7, 11), |
| 974 |
] |
| 975 |
for entry in invalid: |
| 976 |
wrong = entry[0] |
| 977 |
msg = entry[1] |
| 978 |
pos = entry[2:] |
| 979 |
with pytest.raises(SyntaxError) as excinfo: |
| 980 |
self.get_ast(wrong) |
| 981 |
assert msg in excinfo.value.msg |
| 982 |
if pos: |
| 983 |
assert excinfo.value.offset == pos[0] |
| 984 |
assert excinfo.value.end_offset == pos[1] |
| 985 |
|
| 986 |
def test_cannot_assign_augmented(self): |
| 987 |
with pytest.raises(SyntaxError) as excinfo: |
| 988 |
self.get_ast("a, b += 1, 2") |
| 989 |
assert "'tuple' is an illegal expression for augmented assignment" in excinfo.value.msg |
| 990 |
|
| 991 |
|
| 992 |
def test_cannot_assign_bug(self): |
| 993 |
with pytest.raises(SyntaxError) as excinfo: |
| 994 |
self.get_ast("for [ ]") |
| 995 |
assert excinfo.value.msg.startswith('invalid syntax') |
| 996 |
assert excinfo.value.offset == 8 |
| 997 |
with pytest.raises(SyntaxError) as excinfo: |
| 998 |
self.get_ast("for [ ] b 1.0") |
| 999 |
assert excinfo.value.msg.startswith('invalid syntax') |
| 1000 |
assert excinfo.value.offset in (5, 9) |
| 1001 |
with pytest.raises(SyntaxError) as excinfo: |
| 1002 |
self.get_ast("for ( ) b 1.0") |
| 1003 |
assert excinfo.value.msg.startswith('invalid syntax') |
| 1004 |
assert excinfo.value.offset in (5, 9) |
| 1005 |
|
| 1006 |
def test_assign_bug(self): |
| 1007 |
self.get_ast("direct = (__debug__ and optimize == 0)") |
| 1008 |
|
| 1009 |
def test_lambda(self): |
| 1010 |
lam = self.get_first_expr("lambda x: expr") |
| 1011 |
assert isinstance(lam, ast.Lambda) |
| 1012 |
args = lam.args |
| 1013 |
assert isinstance(args, ast.arguments) |
| 1014 |
assert args.vararg is None |
| 1015 |
assert args.kwarg is None |
| 1016 |
assert not args.defaults |
| 1017 |
assert len(args.args) == 1 |
| 1018 |
assert isinstance(args.args[0], ast.arg) |
| 1019 |
assert isinstance(lam.body, ast.Name) |
| 1020 |
lam = self.get_first_expr("lambda: True") |
| 1021 |
args = lam.args |
| 1022 |
assert not args.args |
| 1023 |
lam = self.get_first_expr("lambda x=x: y") |
| 1024 |
assert len(lam.args.args) == 1 |
| 1025 |
assert len(lam.args.defaults) == 1 |
| 1026 |
assert isinstance(lam.args.defaults[0], ast.Name) |
| 1027 |
input = "f(lambda x: x[0] = y)" |
| 1028 |
with pytest.raises(SyntaxError) as excinfo: |
| 1029 |
self.get_ast(input) |
| 1030 |
assert excinfo.value.msg == 'expression cannot contain assignment, perhaps you meant "=="?' |
| 1031 |
|
| 1032 |
def test_ifexp(self): |
| 1033 |
ifexp = self.get_first_expr("x if y else g") |
| 1034 |
assert isinstance(ifexp, ast.IfExp) |
| 1035 |
assert isinstance(ifexp.test, ast.Name) |
| 1036 |
assert ifexp.test.ctx == ast.Load |
| 1037 |
assert isinstance(ifexp.body, ast.Name) |
| 1038 |
assert ifexp.body.ctx == ast.Load |
| 1039 |
assert isinstance(ifexp.orelse, ast.Name) |
| 1040 |
assert ifexp.orelse.ctx == ast.Load |
| 1041 |
|
| 1042 |
def test_boolop(self): |
| 1043 |
for ast_type, op in ((ast.And, "and"), (ast.Or, "or")): |
| 1044 |
bo = self.get_first_expr("x %s a" % (op,)) |
| 1045 |
assert isinstance(bo, ast.BoolOp) |
| 1046 |
assert bo.op == ast_type |
| 1047 |
assert len(bo.values) == 2 |
| 1048 |
assert isinstance(bo.values[0], ast.Name) |
| 1049 |
assert isinstance(bo.values[1], ast.Name) |
| 1050 |
bo = self.get_first_expr("x %s a %s b" % (op, op)) |
| 1051 |
assert bo.op == ast_type |
| 1052 |
assert len(bo.values) == 3 |
| 1053 |
|
| 1054 |
def test_not(self): |
| 1055 |
n = self.get_first_expr("not x") |
| 1056 |
assert isinstance(n, ast.UnaryOp) |
| 1057 |
assert n.op == ast.Not |
| 1058 |
assert isinstance(n.operand, ast.Name) |
| 1059 |
assert n.operand.ctx == ast.Load |
| 1060 |
|
| 1061 |
def test_comparison(self): |
| 1062 |
compares = ( |
| 1063 |
(">", ast.Gt), |
| 1064 |
(">=", ast.GtE), |
| 1065 |
("<", ast.Lt), |
| 1066 |
("<=", ast.LtE), |
| 1067 |
("==", ast.Eq), |
| 1068 |
("!=", ast.NotEq), |
| 1069 |
("in", ast.In), |
| 1070 |
("is", ast.Is), |
| 1071 |
("is not", ast.IsNot), |
| 1072 |
("not in", ast.NotIn) |
| 1073 |
) |
| 1074 |
for op, ast_type in compares: |
| 1075 |
comp = self.get_first_expr("x %s y" % (op,)) |
| 1076 |
assert isinstance(comp, ast.Compare) |
| 1077 |
assert isinstance(comp.left, ast.Name) |
| 1078 |
assert comp.left.ctx == ast.Load |
| 1079 |
assert len(comp.ops) == 1 |
| 1080 |
assert comp.ops[0] == ast_type |
| 1081 |
assert len(comp.comparators) == 1 |
| 1082 |
assert isinstance(comp.comparators[0], ast.Name) |
| 1083 |
assert comp.comparators[0].ctx == ast.Load |
| 1084 |
|
| 1085 |
for j in range(10): |
| 1086 |
vars = string.ascii_letters[:random.randint(3, 7)] |
| 1087 |
ops = [random.choice(compares) for i in range(len(vars) - 1)] |
| 1088 |
input = vars[0] |
| 1089 |
for i, (op, _) in enumerate(ops): |
| 1090 |
input += " %s %s" % (op, vars[i + 1]) |
| 1091 |
comp = self.get_first_expr(input) |
| 1092 |
assert comp.ops == [tup[1] for tup in ops] |
| 1093 |
names = comp.left.id + "".join(n.id for n in comp.comparators) |
| 1094 |
assert names == vars |
| 1095 |
|
| 1096 |
def test_flufl(self): |
| 1097 |
source = "x <> y" |
| 1098 |
pytest.raises(SyntaxError, self.get_ast, source) |
| 1099 |
comp = self.get_first_expr(source, |
| 1100 |
flags=consts.CO_FUTURE_BARRY_AS_BDFL) |
| 1101 |
assert isinstance(comp, ast.Compare) |
| 1102 |
assert isinstance(comp.left, ast.Name) |
| 1103 |
assert comp.left.ctx == ast.Load |
| 1104 |
assert len(comp.ops) == 1 |
| 1105 |
assert comp.ops[0] == ast.NotEq |
| 1106 |
assert len(comp.comparators) == 1 |
| 1107 |
assert isinstance(comp.comparators[0], ast.Name) |
| 1108 |
assert comp.comparators[0].ctx == ast.Load |
| 1109 |
|
| 1110 |
def test_binop(self): |
| 1111 |
binops = ( |
| 1112 |
("|", ast.BitOr), |
| 1113 |
("&", ast.BitAnd), |
| 1114 |
("^", ast.BitXor), |
| 1115 |
("<<", ast.LShift), |
| 1116 |
(">>", ast.RShift), |
| 1117 |
("+", ast.Add), |
| 1118 |
("-", ast.Sub), |
| 1119 |
("/", ast.Div), |
| 1120 |
("*", ast.Mult), |
| 1121 |
("//", ast.FloorDiv), |
| 1122 |
("%", ast.Mod), |
| 1123 |
("@", ast.MatMult) |
| 1124 |
) |
| 1125 |
for op, ast_type in binops: |
| 1126 |
bin = self.get_first_expr("a %s b" % (op,)) |
| 1127 |
assert isinstance(bin, ast.BinOp) |
| 1128 |
assert bin.op == ast_type |
| 1129 |
assert isinstance(bin.left, ast.Name) |
| 1130 |
assert isinstance(bin.right, ast.Name) |
| 1131 |
assert bin.left.ctx == ast.Load |
| 1132 |
assert bin.right.ctx == ast.Load |
| 1133 |
bin = self.get_first_expr("a %s b %s c" % (op, op)) |
| 1134 |
assert isinstance(bin.left, ast.BinOp) |
| 1135 |
assert bin.left.op == ast_type |
| 1136 |
assert isinstance(bin.right, ast.Name) |
| 1137 |
|
| 1138 |
def test_yield(self): |
| 1139 |
expr = self.get_first_expr("yield") |
| 1140 |
assert isinstance(expr, ast.Yield) |
| 1141 |
assert expr.value is None |
| 1142 |
expr = self.get_first_expr("yield x") |
| 1143 |
assert isinstance(expr.value, ast.Name) |
| 1144 |
assign = self.get_first_stmt("x = yield x") |
| 1145 |
assert isinstance(assign, ast.Assign) |
| 1146 |
assert isinstance(assign.value, ast.Yield) |
| 1147 |
|
| 1148 |
def test_yield_from(self): |
| 1149 |
expr = self.get_first_expr("yield from x") |
| 1150 |
assert isinstance(expr, ast.YieldFrom) |
| 1151 |
assert isinstance(expr.value, ast.Name) |
| 1152 |
|
| 1153 |
def test_unaryop(self): |
| 1154 |
unary_ops = ( |
| 1155 |
("+", ast.UAdd), |
| 1156 |
("-", ast.USub), |
| 1157 |
("~", ast.Invert) |
| 1158 |
) |
| 1159 |
for op, ast_type in unary_ops: |
| 1160 |
unary = self.get_first_expr("%sx" % (op,)) |
| 1161 |
assert isinstance(unary, ast.UnaryOp) |
| 1162 |
assert unary.op == ast_type |
| 1163 |
assert isinstance(unary.operand, ast.Name) |
| 1164 |
assert unary.operand.ctx == ast.Load |
| 1165 |
|
| 1166 |
def test_power(self): |
| 1167 |
power = self.get_first_expr("x**5") |
| 1168 |
assert isinstance(power, ast.BinOp) |
| 1169 |
assert power.op == ast.Pow |
| 1170 |
assert isinstance(power.left , ast.Name) |
| 1171 |
assert power.left.ctx == ast.Load |
| 1172 |
assert isinstance(power.right, ast.Constant) |
| 1173 |
|
| 1174 |
def test_call(self): |
| 1175 |
call = self.get_first_expr("f()") |
| 1176 |
assert isinstance(call, ast.Call) |
| 1177 |
assert call.args is None |
| 1178 |
assert call.keywords is None |
| 1179 |
assert isinstance(call.func, ast.Name) |
| 1180 |
assert call.func.ctx == ast.Load |
| 1181 |
call = self.get_first_expr("f(2, 3)") |
| 1182 |
assert len(call.args) == 2 |
| 1183 |
assert isinstance(call.args[0], ast.Constant) |
| 1184 |
assert isinstance(call.args[1], ast.Constant) |
| 1185 |
assert call.keywords is None |
| 1186 |
call = self.get_first_expr("f(a=3)") |
| 1187 |
assert call.args is None |
| 1188 |
assert len(call.keywords) == 1 |
| 1189 |
keyword = call.keywords[0] |
| 1190 |
assert isinstance(keyword, ast.keyword) |
| 1191 |
assert keyword.arg == "a" |
| 1192 |
assert isinstance(keyword.value, ast.Constant) |
| 1193 |
call = self.get_first_expr("f(*a, **b)") |
| 1194 |
assert isinstance(call.args[0], ast.Starred) |
| 1195 |
assert isinstance(call.keywords[0], ast.keyword) |
| 1196 |
assert call.args[0].value.id == "a" |
| 1197 |
assert call.args[0].ctx == ast.Load |
| 1198 |
assert call.keywords[0].value.id == "b" |
| 1199 |
call = self.get_first_expr("f(a, b, x=4, *m, **f)") |
| 1200 |
assert len(call.args) == 3 |
| 1201 |
assert isinstance(call.args[0], ast.Name) |
| 1202 |
assert isinstance(call.args[1], ast.Name) |
| 1203 |
assert isinstance(call.args[2], ast.Starred) |
| 1204 |
assert len(call.keywords) == 2 |
| 1205 |
assert call.keywords[0].arg == "x" |
| 1206 |
assert call.args[2].value.id == "m" |
| 1207 |
assert call.keywords[1].value.id == "f" |
| 1208 |
call = self.get_first_expr("f(x for x in y)") |
| 1209 |
assert len(call.args) == 1 |
| 1210 |
assert isinstance(call.args[0], ast.GeneratorExp) |
| 1211 |
input = "f(x for x in y, 1)" |
| 1212 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 1213 |
assert exc.msg == "Generator expression must be parenthesized" |
| 1214 |
|
| 1215 |
input = "f(x for x in y, )" |
| 1216 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 1217 |
assert exc.msg == "Generator expression must be parenthesized" |
| 1218 |
|
| 1219 |
many_args = ", ".join("x%i" % i for i in range(256)) |
| 1220 |
input = "f(%s)" % (many_args,) |
| 1221 |
self.get_ast(input) |
| 1222 |
exc = pytest.raises(SyntaxError, self.get_ast, "f((a+b)=c)").value |
| 1223 |
assert exc.msg == 'expression cannot contain assignment, perhaps you meant "=="?' |
| 1224 |
exc = pytest.raises(SyntaxError, self.get_ast, "deff f(a=1, a=2): pass").value |
| 1225 |
assert 'invalid syntax' in exc.msg |
| 1226 |
with pytest.raises(SyntaxError) as excinfo: |
| 1227 |
self.get_ast("f((x)=1)") |
| 1228 |
assert excinfo.value.msg == 'expression cannot contain assignment, perhaps you meant "=="?' |
| 1229 |
with pytest.raises(SyntaxError) as excinfo: |
| 1230 |
self.get_ast("f(True=1)") |
| 1231 |
assert excinfo.value.msg == 'cannot assign to True' |
| 1232 |
assert excinfo.value.offset == 3 |
| 1233 |
|
| 1234 |
|
| 1235 |
def test_attribute(self): |
| 1236 |
attr = self.get_first_expr("x.y") |
| 1237 |
assert isinstance(attr, ast.Attribute) |
| 1238 |
assert isinstance(attr.value, ast.Name) |
| 1239 |
assert attr.value.ctx == ast.Load |
| 1240 |
assert attr.attr == "y" |
| 1241 |
assert attr.ctx == ast.Load |
| 1242 |
assign = self.get_first_stmt("x.y = 54") |
| 1243 |
assert isinstance(assign, ast.Assign) |
| 1244 |
assert len(assign.targets) == 1 |
| 1245 |
attr = assign.targets[0] |
| 1246 |
assert isinstance(attr, ast.Attribute) |
| 1247 |
assert attr.value.ctx == ast.Load |
| 1248 |
assert attr.ctx == ast.Store |
| 1249 |
|
| 1250 |
def test_subscript_and_slices(self): |
| 1251 |
sub = self.get_first_expr("x[y]") |
| 1252 |
assert isinstance(sub, ast.Subscript) |
| 1253 |
assert isinstance(sub.value, ast.Name) |
| 1254 |
assert sub.value.ctx == ast.Load |
| 1255 |
assert sub.ctx == ast.Load |
| 1256 |
assert isinstance(sub.slice, ast.Name) |
| 1257 |
slc = self.get_first_expr("x[:]").slice |
| 1258 |
assert slc.upper is None |
| 1259 |
assert slc.lower is None |
| 1260 |
assert slc.step is None |
| 1261 |
slc = self.get_first_expr("x[::]").slice |
| 1262 |
assert slc.upper is None |
| 1263 |
assert slc.lower is None |
| 1264 |
assert slc.step is None |
| 1265 |
slc = self.get_first_expr("x[1:]").slice |
| 1266 |
assert isinstance(slc.lower, ast.Constant) |
| 1267 |
assert slc.upper is None |
| 1268 |
assert slc.step is None |
| 1269 |
slc = self.get_first_expr("x[1::]").slice |
| 1270 |
assert isinstance(slc.lower, ast.Constant) |
| 1271 |
assert slc.upper is None |
| 1272 |
assert slc.step is None |
| 1273 |
slc = self.get_first_expr("x[:2]").slice |
| 1274 |
assert slc.lower is None |
| 1275 |
assert isinstance(slc.upper, ast.Constant) |
| 1276 |
assert slc.step is None |
| 1277 |
slc = self.get_first_expr("x[:2:]").slice |
| 1278 |
assert slc.lower is None |
| 1279 |
assert isinstance(slc.upper, ast.Constant) |
| 1280 |
assert slc.step is None |
| 1281 |
slc = self.get_first_expr("x[2:2]").slice |
| 1282 |
assert isinstance(slc.lower, ast.Constant) |
| 1283 |
assert isinstance(slc.upper, ast.Constant) |
| 1284 |
assert slc.step is None |
| 1285 |
slc = self.get_first_expr("x[2:2:]").slice |
| 1286 |
assert isinstance(slc.lower, ast.Constant) |
| 1287 |
assert isinstance(slc.upper, ast.Constant) |
| 1288 |
assert slc.step is None |
| 1289 |
slc = self.get_first_expr("x[::2]").slice |
| 1290 |
assert slc.lower is None |
| 1291 |
assert slc.upper is None |
| 1292 |
assert isinstance(slc.step, ast.Constant) |
| 1293 |
slc = self.get_first_expr("x[2::2]").slice |
| 1294 |
assert isinstance(slc.lower, ast.Constant) |
| 1295 |
assert slc.upper is None |
| 1296 |
assert isinstance(slc.step, ast.Constant) |
| 1297 |
slc = self.get_first_expr("x[:2:2]").slice |
| 1298 |
assert slc.lower is None |
| 1299 |
assert isinstance(slc.upper, ast.Constant) |
| 1300 |
assert isinstance(slc.step, ast.Constant) |
| 1301 |
slc = self.get_first_expr("x[1:2:3]").slice |
| 1302 |
for field in (slc.lower, slc.upper, slc.step): |
| 1303 |
assert isinstance(field, ast.Constant) |
| 1304 |
sub = self.get_first_expr("x[1,2,3]") |
| 1305 |
slc = sub.slice |
| 1306 |
assert isinstance(slc, ast.Tuple) |
| 1307 |
assert len(slc.elts) == 3 |
| 1308 |
assert slc.ctx == ast.Load |
| 1309 |
slc = self.get_first_expr("x[1,3:4]").slice |
| 1310 |
assert isinstance(slc, ast.Tuple) |
| 1311 |
assert len(slc.elts) == 2 |
| 1312 |
complex_slc = slc.elts[1] |
| 1313 |
assert isinstance(complex_slc, ast.Slice) |
| 1314 |
assert isinstance(complex_slc.lower, ast.Constant) |
| 1315 |
assert isinstance(complex_slc.upper, ast.Constant) |
| 1316 |
assert complex_slc.step is None |
| 1317 |
|
| 1318 |
def test_ellipsis(self): |
| 1319 |
e = self.get_first_expr("...") |
| 1320 |
assert isinstance(e, ast.Constant) |
| 1321 |
assert self.space.is_w(e.value, self.space.w_Ellipsis) |
| 1322 |
|
| 1323 |
sub = self.get_first_expr("x[...]") |
| 1324 |
assert isinstance(sub.slice, ast.Constant) |
| 1325 |
assert self.space.is_w(sub.slice.value, self.space.w_Ellipsis) |
| 1326 |
|
| 1327 |
def test_string(self): |
| 1328 |
space = self.space |
| 1329 |
s = self.get_first_expr("'hi'") |
| 1330 |
assert isinstance(s, ast.Constant) |
| 1331 |
assert space.eq_w(s.value, space.wrap("hi")) |
| 1332 |
s = self.get_first_expr("'hi' ' implicitly' ' extra'") |
| 1333 |
assert isinstance(s, ast.Constant) |
| 1334 |
assert space.eq_w(s.value, space.wrap("hi implicitly extra")) |
| 1335 |
s = self.get_first_expr("b'hi' b' implicitly' b' extra'") |
| 1336 |
assert isinstance(s, ast.Constant) |
| 1337 |
assert space.eq_w(s.value, space.newbytes("hi implicitly extra")) |
| 1338 |
excinfo = pytest.raises(SyntaxError, self.get_first_expr, "b'hello' 'world'") |
| 1339 |
assert excinfo.value.offset == 1 |
| 1340 |
excinfo = pytest.raises(SyntaxError, self.get_first_expr, "'foo' b'hello' 'world'") |
| 1341 |
assert excinfo.value.offset == 7 |
| 1342 |
sentence = u"Die Männer ärgern sich!" |
| 1343 |
source = u"# coding: utf-7\nstuff = '%s'" % (sentence,) |
| 1344 |
s = self.get_first_stmt(source.encode("utf-7")) |
| 1345 |
assert self.info.encoding == "utf-7" |
| 1346 |
assert isinstance(s.value, ast.Constant) |
| 1347 |
assert space.eq_w(s.value.value, space.wrap(sentence)) |
| 1348 |
|
| 1349 |
def test_string_pep3120(self): |
| 1350 |
space = self.space |
| 1351 |
japan = u'日本' |
| 1352 |
source = u"foo = '%s'" % japan |
| 1353 |
s = self.get_first_stmt(source.encode("utf-8")) |
| 1354 |
assert self.info.encoding == "utf-8" |
| 1355 |
assert isinstance(s.value, ast.Constant) |
| 1356 |
assert space.eq_w(s.value.value, space.wrap(japan)) |
| 1357 |
|
| 1358 |
def test_name_pep3131(self): |
| 1359 |
assign = self.get_first_stmt("日本 = 32") |
| 1360 |
assert isinstance(assign, ast.Assign) |
| 1361 |
name = assign.targets[0] |
| 1362 |
assert isinstance(name, ast.Name) |
| 1363 |
assert name.id == u"日本".encode('utf-8') |
| 1364 |
|
| 1365 |
def test_function_pep3131(self): |
| 1366 |
fn = self.get_first_stmt("def µ(µ='foo'): pass") |
| 1367 |
assert isinstance(fn, ast.FunctionDef) |
| 1368 |
C |
| 1369 |
expected = u'\u03bc'.encode('utf-8') |
| 1370 |
assert fn.name == expected |
| 1371 |
assert fn.args.args[0].arg == expected |
| 1372 |
|
| 1373 |
def test_import_pep3131(self): |
| 1374 |
im = self.get_first_stmt("from packageµ import modµ as µ") |
| 1375 |
assert isinstance(im, ast.ImportFrom) |
| 1376 |
expected = u'\u03bc'.encode('utf-8') |
| 1377 |
assert im.module == 'package' + expected |
| 1378 |
alias = im.names[0] |
| 1379 |
assert alias.name == 'mod' + expected |
| 1380 |
assert alias.asname == expected |
| 1381 |
|
| 1382 |
def test_issue3574(self): |
| 1383 |
space = self.space |
| 1384 |
source = u'# coding: Latin-1\nu = "Ç"\n' |
| 1385 |
info = pyparse.CompileInfo("<test>", "exec") |
| 1386 |
s = self.get_first_stmt(source.encode("Latin-1")).value |
| 1387 |
assert self.info.encoding == "iso-8859-1" |
| 1388 |
assert isinstance(s, ast.Constant) |
| 1389 |
assert space.eq_w(s.value, space.wrap(u'Ç')) |
| 1390 |
|
| 1391 |
def test_string_bug(self): |
| 1392 |
space = self.space |
| 1393 |
source = '# -*- encoding: utf8 -*-\nstuff = "x \xc3\xa9 \\n"\n' |
| 1394 |
s = self.get_first_stmt(source).value |
| 1395 |
assert self.info.encoding == "utf8" |
| 1396 |
assert isinstance(s, ast.Constant) |
| 1397 |
assert space.eq_w(s.value, space.wrap(u'x \xe9 \n')) |
| 1398 |
|
| 1399 |
def test_number(self): |
| 1400 |
def get_num(s): |
| 1401 |
node = self.get_first_expr(s) |
| 1402 |
assert isinstance(node, ast.Constant) |
| 1403 |
value = node.value |
| 1404 |
assert isinstance(value, W_Root) |
| 1405 |
return value |
| 1406 |
space = self.space |
| 1407 |
assert space.eq_w(get_num("32"), space.wrap(32)) |
| 1408 |
assert space.eq_w(get_num("32.5"), space.wrap(32.5)) |
| 1409 |
assert space.eq_w(get_num("2"), space.wrap(2)) |
| 1410 |
assert space.eq_w(get_num("13j"), space.wrap(13j)) |
| 1411 |
assert space.eq_w(get_num("13J"), space.wrap(13J)) |
| 1412 |
assert space.eq_w(get_num("0o53"), space.wrap(053)) |
| 1413 |
assert space.eq_w(get_num("0o0053"), space.wrap(053)) |
| 1414 |
for num in ("0x53", "0X53", "0x0000053", "0X00053"): |
| 1415 |
assert space.eq_w(get_num(num), space.wrap(0x53)) |
| 1416 |
assert space.eq_w(get_num("0Xb0d2"), space.wrap(0xb0d2)) |
| 1417 |
assert space.eq_w(get_num("0X53"), space.wrap(0x53)) |
| 1418 |
assert space.eq_w(get_num("0"), space.wrap(0)) |
| 1419 |
assert space.eq_w(get_num("00000"), space.wrap(0)) |
| 1420 |
for num in ("0o53", "0O53", "0o0000053", "0O00053"): |
| 1421 |
assert space.eq_w(get_num(num), space.wrap(053)) |
| 1422 |
for num in ("0b00101", "0B00101", "0b101", "0B101"): |
| 1423 |
assert space.eq_w(get_num(num), space.wrap(5)) |
| 1424 |
|
| 1425 |
pytest.raises(SyntaxError, self.get_ast, "0x") |
| 1426 |
pytest.raises(SyntaxError, self.get_ast, "0b") |
| 1427 |
pytest.raises(SyntaxError, self.get_ast, "0o") |
| 1428 |
pytest.raises(SyntaxError, self.get_ast, "32L") |
| 1429 |
pytest.raises(SyntaxError, self.get_ast, "32l") |
| 1430 |
pytest.raises(SyntaxError, self.get_ast, "0L") |
| 1431 |
pytest.raises(SyntaxError, self.get_ast, "-0xAAAAAAL") |
| 1432 |
pytest.raises(SyntaxError, self.get_ast, "053") |
| 1433 |
pytest.raises(SyntaxError, self.get_ast, "00053") |
| 1434 |
|
| 1435 |
def check_comprehension(self, brackets, ast_type): |
| 1436 |
def brack(s): |
| 1437 |
return brackets % s |
| 1438 |
gen = self.get_first_expr(brack("x for x in y")) |
| 1439 |
assert isinstance(gen, ast_type) |
| 1440 |
assert isinstance(gen.elt, ast.Name) |
| 1441 |
assert gen.elt.ctx == ast.Load |
| 1442 |
assert len(gen.generators) == 1 |
| 1443 |
comp = gen.generators[0] |
| 1444 |
assert isinstance(comp, ast.comprehension) |
| 1445 |
assert comp.ifs is None |
| 1446 |
assert isinstance(comp.target, ast.Name) |
| 1447 |
assert isinstance(comp.iter, ast.Name) |
| 1448 |
assert comp.target.ctx == ast.Store |
| 1449 |
gen = self.get_first_expr(brack("x for x in y if w")) |
| 1450 |
comp = gen.generators[0] |
| 1451 |
assert len(comp.ifs) == 1 |
| 1452 |
test = comp.ifs[0] |
| 1453 |
assert isinstance(test, ast.Name) |
| 1454 |
gen = self.get_first_expr(brack("x for x, in y if w")) |
| 1455 |
tup = gen.generators[0].target |
| 1456 |
assert isinstance(tup, ast.Tuple) |
| 1457 |
assert len(tup.elts) == 1 |
| 1458 |
assert tup.ctx == ast.Store |
| 1459 |
gen = self.get_first_expr(brack("a for w in x for m in p if g")) |
| 1460 |
gens = gen.generators |
| 1461 |
assert len(gens) == 2 |
| 1462 |
comp1, comp2 = gens |
| 1463 |
assert comp1.ifs is None |
| 1464 |
assert len(comp2.ifs) == 1 |
| 1465 |
assert isinstance(comp2.ifs[0], ast.Name) |
| 1466 |
gen = self.get_first_expr(brack("x for x in y if m if g")) |
| 1467 |
comps = gen.generators |
| 1468 |
assert len(comps) == 1 |
| 1469 |
assert len(comps[0].ifs) == 2 |
| 1470 |
if1, if2 = comps[0].ifs |
| 1471 |
assert isinstance(if1, ast.Name) |
| 1472 |
assert isinstance(if2, ast.Name) |
| 1473 |
gen = self.get_first_expr(brack("x for x in y or z")) |
| 1474 |
comp = gen.generators[0] |
| 1475 |
assert isinstance(comp.iter, ast.BoolOp) |
| 1476 |
assert len(comp.iter.values) == 2 |
| 1477 |
assert isinstance(comp.iter.values[0], ast.Name) |
| 1478 |
assert isinstance(comp.iter.values[1], ast.Name) |
| 1479 |
|
| 1480 |
def test_genexp(self): |
| 1481 |
self.check_comprehension("(%s)", ast.GeneratorExp) |
| 1482 |
|
| 1483 |
def test_listcomp(self): |
| 1484 |
self.check_comprehension("[%s]", ast.ListComp) |
| 1485 |
|
| 1486 |
def test_setcomp(self): |
| 1487 |
self.check_comprehension("{%s}", ast.SetComp) |
| 1488 |
|
| 1489 |
def test_dictcomp(self): |
| 1490 |
gen = self.get_first_expr("{x : z for x in y}") |
| 1491 |
assert isinstance(gen, ast.DictComp) |
| 1492 |
assert isinstance(gen.key, ast.Name) |
| 1493 |
assert gen.key.ctx == ast.Load |
| 1494 |
assert isinstance(gen.value, ast.Name) |
| 1495 |
assert gen.value.ctx == ast.Load |
| 1496 |
assert len(gen.generators) == 1 |
| 1497 |
comp = gen.generators[0] |
| 1498 |
assert isinstance(comp, ast.comprehension) |
| 1499 |
assert comp.ifs is None |
| 1500 |
assert isinstance(comp.target, ast.Name) |
| 1501 |
assert isinstance(comp.iter, ast.Name) |
| 1502 |
assert comp.target.ctx == ast.Store |
| 1503 |
gen = self.get_first_expr("{x : z for x in y if w}") |
| 1504 |
comp = gen.generators[0] |
| 1505 |
assert len(comp.ifs) == 1 |
| 1506 |
test = comp.ifs[0] |
| 1507 |
assert isinstance(test, ast.Name) |
| 1508 |
gen = self.get_first_expr("{x : z for x, in y if w}") |
| 1509 |
tup = gen.generators[0].target |
| 1510 |
assert isinstance(tup, ast.Tuple) |
| 1511 |
assert len(tup.elts) == 1 |
| 1512 |
assert tup.ctx == ast.Store |
| 1513 |
gen = self.get_first_expr("{a : b for w in x for m in p if g}") |
| 1514 |
gens = gen.generators |
| 1515 |
assert len(gens) == 2 |
| 1516 |
comp1, comp2 = gens |
| 1517 |
assert comp1.ifs is None |
| 1518 |
assert len(comp2.ifs) == 1 |
| 1519 |
assert isinstance(comp2.ifs[0], ast.Name) |
| 1520 |
gen = self.get_first_expr("{x : z for x in y if m if g}") |
| 1521 |
comps = gen.generators |
| 1522 |
assert len(comps) == 1 |
| 1523 |
assert len(comps[0].ifs) == 2 |
| 1524 |
if1, if2 = comps[0].ifs |
| 1525 |
assert isinstance(if1, ast.Name) |
| 1526 |
assert isinstance(if2, ast.Name) |
| 1527 |
|
| 1528 |
def test_cpython_issue12983(self): |
| 1529 |
pytest.raises(SyntaxError, self.get_ast, r"""b'\x'""") |
| 1530 |
pytest.raises(SyntaxError, self.get_ast, r"""b'\x0'""") |
| 1531 |
|
| 1532 |
def test_matmul(self): |
| 1533 |
mod = self.get_ast("a @ b") |
| 1534 |
assert isinstance(mod, ast.Module) |
| 1535 |
body = mod.body |
| 1536 |
assert len(body) == 1 |
| 1537 |
expr = body[0].value |
| 1538 |
assert expr.op == ast.MatMult |
| 1539 |
assert isinstance(expr.left, ast.Name) |
| 1540 |
assert isinstance(expr.right, ast.Name) |
| 1541 |
|
| 1542 |
|
| 1543 |
@pytest.mark.parametrize('with_async_hacks', [False, True]) |
| 1544 |
def test_asyncFunctionDef(self, with_async_hacks): |
| 1545 |
mod = self.get_ast("async def f():\n await something()", with_async_hacks=with_async_hacks) |
| 1546 |
assert isinstance(mod, ast.Module) |
| 1547 |
assert len(mod.body) == 1 |
| 1548 |
asyncdef = mod.body[0] |
| 1549 |
assert isinstance(asyncdef, ast.AsyncFunctionDef) |
| 1550 |
assert asyncdef.name == 'f' |
| 1551 |
assert asyncdef.args.args == None |
| 1552 |
assert len(asyncdef.body) == 1 |
| 1553 |
expr = asyncdef.body[0] |
| 1554 |
assert isinstance(expr, ast.Expr) |
| 1555 |
exprvalue = expr.value |
| 1556 |
assert isinstance(exprvalue, ast.Await) |
| 1557 |
awaitvalue = exprvalue.value |
| 1558 |
assert isinstance(awaitvalue, ast.Call) |
| 1559 |
func = awaitvalue.func |
| 1560 |
assert isinstance(func, ast.Name) |
| 1561 |
assert func.id == 'something' |
| 1562 |
assert func.ctx == ast.Load |
| 1563 |
|
| 1564 |
@pytest.mark.parametrize('with_async_hacks', [False, True]) |
| 1565 |
def test_asyncFor(self, with_async_hacks): |
| 1566 |
mod = self.get_ast("async def f():\n async for e in i: 1\n else: 2", with_async_hacks=with_async_hacks) |
| 1567 |
assert isinstance(mod, ast.Module) |
| 1568 |
assert len(mod.body) == 1 |
| 1569 |
asyncdef = mod.body[0] |
| 1570 |
assert isinstance(asyncdef, ast.AsyncFunctionDef) |
| 1571 |
assert asyncdef.name == 'f' |
| 1572 |
assert asyncdef.args.args == None |
| 1573 |
assert len(asyncdef.body) == 1 |
| 1574 |
asyncfor = asyncdef.body[0] |
| 1575 |
assert isinstance(asyncfor, ast.AsyncFor) |
| 1576 |
assert isinstance(asyncfor.target, ast.Name) |
| 1577 |
assert isinstance(asyncfor.iter, ast.Name) |
| 1578 |
assert len(asyncfor.body) == 1 |
| 1579 |
assert isinstance(asyncfor.body[0], ast.Expr) |
| 1580 |
assert isinstance(asyncfor.body[0].value, ast.Constant) |
| 1581 |
assert len(asyncfor.orelse) == 1 |
| 1582 |
assert isinstance(asyncfor.orelse[0], ast.Expr) |
| 1583 |
assert isinstance(asyncfor.orelse[0].value, ast.Constant) |
| 1584 |
|
| 1585 |
@pytest.mark.parametrize('with_async_hacks', [False, True]) |
| 1586 |
def test_asyncWith(self, with_async_hacks): |
| 1587 |
mod = self.get_ast("async def f():\n async with a as b: 1", with_async_hacks=with_async_hacks) |
| 1588 |
assert isinstance(mod, ast.Module) |
| 1589 |
assert len(mod.body) == 1 |
| 1590 |
asyncdef = mod.body[0] |
| 1591 |
assert isinstance(asyncdef, ast.AsyncFunctionDef) |
| 1592 |
assert asyncdef.name == 'f' |
| 1593 |
assert asyncdef.args.args == None |
| 1594 |
assert len(asyncdef.body) == 1 |
| 1595 |
asyncwith = asyncdef.body[0] |
| 1596 |
assert isinstance(asyncwith, ast.AsyncWith) |
| 1597 |
assert len(asyncwith.items) == 1 |
| 1598 |
asyncitem = asyncwith.items[0] |
| 1599 |
assert isinstance(asyncitem, ast.withitem) |
| 1600 |
assert isinstance(asyncitem.context_expr, ast.Name) |
| 1601 |
assert isinstance(asyncitem.optional_vars, ast.Name) |
| 1602 |
assert len(asyncwith.body) == 1 |
| 1603 |
assert isinstance(asyncwith.body[0], ast.Expr) |
| 1604 |
assert isinstance(asyncwith.body[0].value, ast.Constant) |
| 1605 |
|
| 1606 |
@pytest.mark.parametrize('with_async_hacks', [False, True]) |
| 1607 |
def test_asyncYield(self, with_async_hacks): |
| 1608 |
mod = self.get_ast("async def f():\n yield 5", with_async_hacks=with_async_hacks) |
| 1609 |
assert isinstance(mod, ast.Module) |
| 1610 |
assert len(mod.body) == 1 |
| 1611 |
asyncdef = mod.body[0] |
| 1612 |
assert isinstance(asyncdef, ast.AsyncFunctionDef) |
| 1613 |
assert asyncdef.name == 'f' |
| 1614 |
assert asyncdef.args.args == None |
| 1615 |
assert len(asyncdef.body) == 1 |
| 1616 |
expr = asyncdef.body[0] |
| 1617 |
assert isinstance(expr, ast.Expr) |
| 1618 |
assert isinstance(expr.value, ast.Yield) |
| 1619 |
assert isinstance(expr.value.value, ast.Constant) |
| 1620 |
|
| 1621 |
@pytest.mark.parametrize('with_async_hacks', [False, True]) |
| 1622 |
def test_asyncComp(self, with_async_hacks): |
| 1623 |
mod = self.get_ast("async def f():\n [i async for b in c]", with_async_hacks=with_async_hacks) |
| 1624 |
asyncdef = mod.body[0] |
| 1625 |
expr = asyncdef.body[0] |
| 1626 |
comp = expr.value.generators[0] |
| 1627 |
assert comp.target.id == 'b' |
| 1628 |
assert comp.iter.id == 'c' |
| 1629 |
assert comp.is_async is True |
| 1630 |
|
| 1631 |
def test_without_async_hacks(self): |
| 1632 |
with pytest.raises(SyntaxError): |
| 1633 |
self.get_ast("await = 1", with_async_hacks=False) |
| 1634 |
|
| 1635 |
mod = self.get_ast("await x()", with_async_hacks=False) |
| 1636 |
assert isinstance(mod.body[0].value, ast.Await) |
| 1637 |
|
| 1638 |
mod = self.get_ast("async for x in y: pass", with_async_hacks=False) |
| 1639 |
assert isinstance(mod.body[0], ast.AsyncFor) |
| 1640 |
|
| 1641 |
def test_with_async_hacks(self): |
| 1642 |
mod = self.get_ast("await = 1", with_async_hacks=True) |
| 1643 |
assert isinstance(mod.body[0], ast.Assign) |
| 1644 |
assert isinstance(mod.body[0].targets[0], ast.Name) |
| 1645 |
assert mod.body[0].targets[0].id == "await" |
| 1646 |
|
| 1647 |
with pytest.raises(SyntaxError): |
| 1648 |
self.get_ast("await x()", with_async_hacks=True) |
| 1649 |
|
| 1650 |
with pytest.raises(SyntaxError): |
| 1651 |
self.get_ast("await x()", with_async_hacks=True) |
| 1652 |
|
| 1653 |
def test_decode_error_in_string_literal(self): |
| 1654 |
input = "u'\\x'" |
| 1655 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 1656 |
assert exc.msg == ("(unicode error) 'unicodeescape' codec can't decode" |
| 1657 |
" bytes in position 0-1: truncated \\xXX escape") |
| 1658 |
input = "u'\\x1'" |
| 1659 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 1660 |
assert exc.msg == ("(unicode error) 'unicodeescape' codec can't decode" |
| 1661 |
" bytes in position 0-2: truncated \\xXX escape") |
| 1662 |
|
| 1663 |
def test_decode_error_in_string_literal_correct_line(self): |
| 1664 |
input = "u'a' u'b'\\\n u'c' u'\\x'" |
| 1665 |
exc = pytest.raises(SyntaxError, self.get_ast, input).value |
| 1666 |
assert exc.msg == ("(unicode error) 'unicodeescape' codec can't decode" |
| 1667 |
" bytes in position 0-1: truncated \\xXX escape") |
| 1668 |
assert exc.lineno == 2 |
| 1669 |
assert exc.offset == 7 |
| 1670 |
|
| 1671 |
def test_fstring_lineno(self): |
| 1672 |
mod = self.get_ast('x=1\nf"{ x + 1}"') |
| 1673 |
assert mod.body[1].value.values[0].value.lineno == 2 |
| 1674 |
assert mod.body[1].value.values[0].value.col_offset == 7 |
| 1675 |
assert mod.body[1].value.values[0].value.end_lineno == 2 |
| 1676 |
assert mod.body[1].value.values[0].value.end_col_offset == 12 |
| 1677 |
|
| 1678 |
def test_wrong_async_def_col_offset(self): |
| 1679 |
mod = self.get_ast("async def f():\n pass") |
| 1680 |
asyncdef = mod.body[0] |
| 1681 |
assert asyncdef.col_offset == 0 |
| 1682 |
|
| 1683 |
def get_first_typed_stmt(self, source): |
| 1684 |
return self.get_first_stmt(source, flags=consts.PyCF_TYPE_COMMENTS) |
| 1685 |
|
| 1686 |
def test_type_comments(self): |
| 1687 |
eq_w, w = self.space.eq_w, self.space.wrap |
| 1688 |
assign = self.get_first_typed_stmt("a = 5 # type: int") |
| 1689 |
assert eq_w(assign.type_comment, w('int')) |
| 1690 |
lines = ( |
| 1691 |
"def func(\n" |
| 1692 |
" a, # type: List[int]\n" |
| 1693 |
" b = 5, # type: int\n" |
| 1694 |
" c = None\n" |
| 1695 |
"): pass" |
| 1696 |
) |
| 1697 |
func = self.get_first_typed_stmt(lines) |
| 1698 |
args = func.args |
| 1699 |
assert eq_w(args.args[0].type_comment, w("List[int]")) |
| 1700 |
assert eq_w(args.args[1].type_comment, w("int")) |
| 1701 |
assert self.space.is_none(args.args[2].type_comment) |
| 1702 |
|
| 1703 |
def test_type_comments_func_body(self): |
| 1704 |
eq_w, w = self.space.eq_w, self.space.wrap |
| 1705 |
source = textwrap.dedent("""\ |
| 1706 |
def foo(): |
| 1707 |
# type: () -> int |
| 1708 |
pass |
| 1709 |
""") |
| 1710 |
func = self.get_first_typed_stmt(source) |
| 1711 |
assert eq_w(func.type_comment, w("() -> int")) |
| 1712 |
|
| 1713 |
source = textwrap.dedent("""\ |
| 1714 |
def foo(): # type: () -> int |
| 1715 |
pass |
| 1716 |
""") |
| 1717 |
func = self.get_first_typed_stmt(source) |
| 1718 |
assert eq_w(func.type_comment, w("() -> int")) |
| 1719 |
|
| 1720 |
def test_type_comments_statements(self): |
| 1721 |
eq_w, w = self.space.eq_w, self.space.wrap |
| 1722 |
asyncdef = textwrap.dedent("""\ |
| 1723 |
async def foo(): |
| 1724 |
# type: () -> int |
| 1725 |
return await bar() |
| 1726 |
""") |
| 1727 |
node = self.get_first_typed_stmt(asyncdef) |
| 1728 |
assert eq_w(node.type_comment, w("() -> int")) |
| 1729 |
|
| 1730 |
nonasciidef = textwrap.dedent("""\ |
| 1731 |
def foo(): |
| 1732 |
# type: () -> àçčéñt |
| 1733 |
pass |
| 1734 |
""") |
| 1735 |
node = self.get_first_typed_stmt(nonasciidef) |
| 1736 |
assert eq_w(node.type_comment, w("() -> àçčéñt")) |
| 1737 |
|
| 1738 |
forstmt = textwrap.dedent("""\ |
| 1739 |
for a in []: # type: int |
| 1740 |
pass |
| 1741 |
""") |
| 1742 |
node = self.get_first_typed_stmt(forstmt) |
| 1743 |
assert eq_w(node.type_comment, w("int")) |
| 1744 |
|
| 1745 |
withstmt = textwrap.dedent("""\ |
| 1746 |
with context() as a: # type: int |
| 1747 |
pass |
| 1748 |
""") |
| 1749 |
node = self.get_first_typed_stmt(withstmt) |
| 1750 |
assert eq_w(node.type_comment, w("int")) |
| 1751 |
|
| 1752 |
vardecl = textwrap.dedent("""\ |
| 1753 |
a = 0 # type: int |
| 1754 |
""") |
| 1755 |
node = self.get_first_typed_stmt(vardecl) |
| 1756 |
assert eq_w(node.type_comment, w("int")) |
| 1757 |
|
| 1758 |
def test_type_ignore(self): |
| 1759 |
eq_w, w = self.space.eq_w, self.space.wrap |
| 1760 |
module = self.get_ast(textwrap.dedent("""\ |
| 1761 |
import x # type: ignore |
| 1762 |
# type: ignore@abc |
| 1763 |
test = 1 # type: ignore |
| 1764 |
if test: # type: ignore |
| 1765 |
... |
| 1766 |
... |
| 1767 |
... |
| 1768 |
with x() as y: # type: ignore@def |
| 1769 |
... |
| 1770 |
"""), flags=consts.PyCF_TYPE_COMMENTS) |
| 1771 |
|
| 1772 |
expecteds = [ |
| 1773 |
(1, ''), |
| 1774 |
(2, '@abc'), |
| 1775 |
(3, ''), |
| 1776 |
(4, ''), |
| 1777 |
(8, '@def') |
| 1778 |
] |
| 1779 |
|
| 1780 |
assert all([ |
| 1781 |
eq_w(type_ignore.tag, w(expected[1])) |
| 1782 |
and type_ignore.lineno == expected[0] |
| 1783 |
for type_ignore, expected in zip(module.type_ignores, expecteds) |
| 1784 |
]) |
| 1785 |
|
| 1786 |
def test_type_comments_function_args(self): |
| 1787 |
eq_w, w = self.space.eq_w, self.space.wrap |
| 1788 |
module = self.get_ast(textwrap.dedent("""\ |
| 1789 |
def fa( |
| 1790 |
a = 1, # type: 1 |
| 1791 |
): |
| 1792 |
pass |
| 1793 |
|
| 1794 |
def fa( |
| 1795 |
a = 1 # type: 1 |
| 1796 |
): |
| 1797 |
pass |
| 1798 |
|
| 1799 |
def fab( |
| 1800 |
a, # type: 1 |
| 1801 |
b, # type: 2 |
| 1802 |
): |
| 1803 |
pass |
| 1804 |
|
| 1805 |
def fab( |
| 1806 |
a, # type: 1 |
| 1807 |
b # type: 2 |
| 1808 |
): |
| 1809 |
pass |
| 1810 |
|
| 1811 |
def fv( |
| 1812 |
*v, # type: 1 |
| 1813 |
): |
| 1814 |
pass |
| 1815 |
|
| 1816 |
def fv( |
| 1817 |
*v # type: 1 |
| 1818 |
): |
| 1819 |
pass |
| 1820 |
|
| 1821 |
def fk( |
| 1822 |
**k, # type: 1 |
| 1823 |
): |
| 1824 |
pass |
| 1825 |
|
| 1826 |
def fk( |
| 1827 |
**k # type: 1 |
| 1828 |
): |
| 1829 |
pass |
| 1830 |
|
| 1831 |
def fvk( |
| 1832 |
*v, # type: 1 |
| 1833 |
**k, # type: 2 |
| 1834 |
): |
| 1835 |
pass |
| 1836 |
|
| 1837 |
def fvk( |
| 1838 |
*v, # type: 1 |
| 1839 |
**k # type: 2 |
| 1840 |
): |
| 1841 |
pass |
| 1842 |
|
| 1843 |
def fav( |
| 1844 |
a, # type: 1 |
| 1845 |
*v, # type: 2 |
| 1846 |
): |
| 1847 |
pass |
| 1848 |
|
| 1849 |
def fav( |
| 1850 |
a, # type: 1 |
| 1851 |
*v # type: 2 |
| 1852 |
): |
| 1853 |
pass |
| 1854 |
|
| 1855 |
def fak( |
| 1856 |
a, # type: 1 |
| 1857 |
**k, # type: 2 |
| 1858 |
): |
| 1859 |
pass |
| 1860 |
|
| 1861 |
def fak( |
| 1862 |
a, # type: 1 |
| 1863 |
**k # type: 2 |
| 1864 |
): |
| 1865 |
pass |
| 1866 |
|
| 1867 |
def favk( |
| 1868 |
a, # type: 1 |
| 1869 |
*v, # type: 2 |
| 1870 |
**k, # type: 3 |
| 1871 |
): |
| 1872 |
pass |
| 1873 |
|
| 1874 |
def favk( |
| 1875 |
a, # type: 1 |
| 1876 |
*v, # type: 2 |
| 1877 |
**k # type: 3 |
| 1878 |
): |
| 1879 |
pass |
| 1880 |
|
| 1881 |
def fkwo( |
| 1882 |
a, # type: 1 |
| 1883 |
*, |
| 1884 |
b # type: 2 |
| 1885 |
): |
| 1886 |
pass |
| 1887 |
"""), flags=consts.PyCF_TYPE_COMMENTS) |
| 1888 |
|
| 1889 |
for function in module.body: |
| 1890 |
args = function.args |
| 1891 |
all_args = [] |
| 1892 |
all_args.extend(args.args or []) |
| 1893 |
all_args.extend(args.kwonlyargs or []) |
| 1894 |
if args.vararg: |
| 1895 |
all_args.append(args.vararg) |
| 1896 |
if args.kwarg: |
| 1897 |
all_args.append(args.kwarg) |
| 1898 |
assert all([ |
| 1899 |
eq_w(arg.type_comment, w(str(i))) |
| 1900 |
for i, arg in enumerate(all_args, 1) |
| 1901 |
]) |
| 1902 |
|
| 1903 |
def test_double_type_comment(self): |
| 1904 |
with pytest.raises(SyntaxError) as excinfo: |
| 1905 |
tree = self.get_ast(textwrap.dedent("""\ |
| 1906 |
def foo(): # type: () -> int |
| 1907 |
# type: () -> str |
| 1908 |
return test |
| 1909 |
"""), flags=consts.PyCF_TYPE_COMMENTS) |
| 1910 |
assert excinfo.value.msg.startswith("Cannot have two type comments on def") |
| 1911 |
|
| 1912 |
def test_invalid_type_comments(self): |
| 1913 |
def check_both_ways(source): |
| 1914 |
self.get_ast(source) |
| 1915 |
with pytest.raises(SyntaxError): |
| 1916 |
self.get_ast(source, flags=consts.PyCF_TYPE_COMMENTS) |
| 1917 |
|
| 1918 |
check_both_ways("pass # type: int\n") |
| 1919 |
check_both_ways("foo() # type: int\n") |
| 1920 |
check_both_ways("x += 1 # type: int\n") |
| 1921 |
check_both_ways("while True: # type: int\n continue\n") |
| 1922 |
check_both_ways("while True:\n continue # type: int\n") |
| 1923 |
check_both_ways("try: # type: int\n pass\nfinally:\n pass\n") |
| 1924 |
check_both_ways("try:\n pass\nfinally: # type: int\n pass\n") |
| 1925 |
check_both_ways("pass # type: ignorewhatever\n") |
| 1926 |
check_both_ways("pass # type: ignoreé\n") |
| 1927 |
with pytest.raises(SyntaxError) as e: |
| 1928 |
s = 'def f(\n *, # type: int\n a, # type: int\n):\n pass' |
| 1929 |
self.get_ast(s, flags=consts.PyCF_TYPE_COMMENTS) |
| 1930 |
assert type(e.value) is SyntaxError |
| 1931 |
with pytest.raises(SyntaxError) as e: |
| 1932 |
s = 'def foo(x, /, y, *, z=2):\npass\n' |
| 1933 |
self.get_ast(s) |
| 1934 |
assert "type comment" not in e.value.msg |
| 1935 |
|
| 1936 |
def test_walrus(self): |
| 1937 |
mod = self.get_ast("(a := 1)") |
| 1938 |
expr = mod.body[0].value |
| 1939 |
assert isinstance(expr, ast.NamedExpr) |
| 1940 |
assert expr.target.id == 'a' |
| 1941 |
assert expr.target.ctx == ast.Store |
| 1942 |
assert isinstance(expr.value, ast.Constant) |
| 1943 |
|
| 1944 |
def test_func_type(self): |
| 1945 |
func = self.get_ast("() -> int", p_mode="func_type") |
| 1946 |
assert not func.argtypes |
| 1947 |
assert isinstance(func.returns, ast.Name) |
| 1948 |
assert func.returns.id == 'int' |
| 1949 |
|
| 1950 |
func = self.get_ast("(str, int) -> str", p_mode="func_type") |
| 1951 |
assert len(func.argtypes) == 2 |
| 1952 |
assert [arg_type.id for arg_type in func.argtypes] == ['str', 'int'] |
| 1953 |
assert isinstance(func.returns, ast.Name) |
| 1954 |
|
| 1955 |
def test_constant_kind(self): |
| 1956 |
expr = self.get_first_expr("'bruh'") |
| 1957 |
assert isinstance(expr, ast.Constant) |
| 1958 |
assert self.space.is_none(expr.kind) |
| 1959 |
|
| 1960 |
expr = self.get_first_expr("u'bruh'") |
| 1961 |
assert isinstance(expr, ast.Constant) |
| 1962 |
assert self.space.eq_w(expr.kind, self.space.wrap("u")) |
| 1963 |
|
| 1964 |
def test_end_positions(self): |
| 1965 |
s = "a + b" |
| 1966 |
expr = self.get_first_expr(s) |
| 1967 |
assert expr.end_lineno == expr.lineno |
| 1968 |
assert expr.col_offset + len(s) == expr.end_col_offset |
| 1969 |
|
| 1970 |
s = '''def func(x: int, |
| 1971 |
*args: str, |
| 1972 |
z: float = 0, |
| 1973 |
**kwargs: Any) -> bool: |
| 1974 |
return True''' |
| 1975 |
fdef = self.get_ast(s).body[0] |
| 1976 |
assert fdef.end_lineno == 5 |
| 1977 |
assert fdef.end_col_offset == 15 |
| 1978 |
assert fdef.get_source_segment(s) == s |
| 1979 |
|
| 1980 |
s = 'lambda a, b, *c: (a + b) * c' |
| 1981 |
fdef = self.get_ast(s).body[0].value |
| 1982 |
assert fdef.get_source_segment(s) == s |
| 1983 |
assert fdef.args.args[0].get_source_segment(s) == "a" |
| 1984 |
assert fdef.body.get_source_segment(s) == "(a + b) * c" |
| 1985 |
|
| 1986 |
s = '( ( ( a ) ) ) ( )' |
| 1987 |
tree = self.get_first_expr(s) |
| 1988 |
assert tree.end_col_offset == len(s) |
| 1989 |
assert fdef.get_source_segment(s) == s |
| 1990 |
|
| 1991 |
s = "a.b" |
| 1992 |
tree = self.get_first_expr(s) |
| 1993 |
assert tree.end_col_offset == len(s) |
| 1994 |
assert tree.col_offset == 0 |
| 1995 |
assert fdef.get_source_segment(s) == s |
| 1996 |
|
| 1997 |
s = "a[x:y]" |
| 1998 |
tree = self.get_first_expr(s) |
| 1999 |
assert tree.end_col_offset == len(s) |
| 2000 |
assert tree.col_offset == 0 |
| 2001 |
assert fdef.get_source_segment(s) == s |
| 2002 |
|
| 2003 |
s = "f(x for x in y)" |
| 2004 |
tree = self.get_first_expr(s) |
| 2005 |
assert tree.end_col_offset == len(s) |
| 2006 |
assert tree.col_offset == 0 |
| 2007 |
gen = tree.args[0] |
| 2008 |
assert gen.end_col_offset in (len(s), len(s) - 1) |
| 2009 |
assert gen.col_offset in (1, 2) |
| 2010 |
assert fdef.get_source_segment(s) == s |
| 2011 |
|
| 2012 |
s = "(x for x in y)" |
| 2013 |
tree = self.get_first_expr(s) |
| 2014 |
assert tree.end_col_offset == len(s) |
| 2015 |
assert tree.col_offset == 0 |
| 2016 |
|
| 2017 |
s = "[x for x in y]" |
| 2018 |
tree = self.get_first_expr(s) |
| 2019 |
assert tree.end_col_offset == len(s) |
| 2020 |
assert tree.col_offset == 0 |
| 2021 |
assert fdef.get_source_segment(s) == s |
| 2022 |
|
| 2023 |
s = "{x for x in y}" |
| 2024 |
tree = self.get_first_expr(s) |
| 2025 |
assert tree.end_col_offset == len(s) |
| 2026 |
assert tree.col_offset == 0 |
| 2027 |
assert fdef.get_source_segment(s) == s |
| 2028 |
|
| 2029 |
s = "{x: x+1 for x in y}" |
| 2030 |
tree = self.get_first_expr(s) |
| 2031 |
assert tree.end_col_offset == len(s) |
| 2032 |
assert tree.col_offset == 0 |
| 2033 |
assert fdef.get_source_segment(s) == s |
| 2034 |
|
| 2035 |
def test_binop_offset_bug(self): |
| 2036 |
s = "1 + 2+3+4" |
| 2037 |
tree = self.get_first_expr(s) |
| 2038 |
assert tree.col_offset == 0 |
| 2039 |
assert tree.end_col_offset == len(s) |
| 2040 |
|
| 2041 |
parent_binop = self.get_first_expr('4+5+6+7') |
| 2042 |
child_binop = parent_binop.left |
| 2043 |
grandchild_binop = child_binop.left |
| 2044 |
assert parent_binop.col_offset == 0 |
| 2045 |
assert parent_binop.end_col_offset == 7 |
| 2046 |
assert child_binop.col_offset == 0 |
| 2047 |
assert child_binop.end_col_offset == 5 |
| 2048 |
assert grandchild_binop.col_offset == 0 |
| 2049 |
assert grandchild_binop.end_col_offset == 3 |
| 2050 |
|
| 2051 |
def test_binop_paren_bug(self): |
| 2052 |
s = "( 1 + 2)" |
| 2053 |
tree = self.get_first_expr(s) |
| 2054 |
assert tree.col_offset == 5 |
| 2055 |
assert tree.end_col_offset == len(s) - 1 |
| 2056 |
|
| 2057 |
def test_tuple_pos_bug(self): |
| 2058 |
s = "(a, bccccccccccccccccccccc)" |
| 2059 |
tree = self.get_first_expr(s) |
| 2060 |
assert tree.col_offset == 0 |
| 2061 |
assert tree.end_col_offset == len(s) |
| 2062 |
|
| 2063 |
def test_tuple_assign_pos_bug(self): |
| 2064 |
s = "(a, b) = c" |
| 2065 |
tree = self.get_ast(s) |
| 2066 |
assert tree.body[0].targets[0].col_offset == 0 |
| 2067 |
assert tree.body[0].targets[0].end_col_offset == 6 |
| 2068 |
|
| 2069 |
def test_dotted_name_bug(self): |
| 2070 |
tree = self.get_ast('@a.b.c\ndef f(): pass') |
| 2071 |
attr_b = tree.body[0].decorator_list[0].value |
| 2072 |
assert attr_b.end_col_offset == 4 |
| 2073 |
|
| 2074 |
def test_get_source_segment(self): |
| 2075 |
s = "a + (b + c)" |
| 2076 |
tree = self.get_first_expr(s) |
| 2077 |
assert tree.get_source_segment(s) == s |
| 2078 |
assert tree.get_source_segment(s, padded=True) == s |
| 2079 |
|
| 2080 |
assert tree.right.get_source_segment(s) == "b + c" |
| 2081 |
assert tree.right.get_source_segment(s, padded=True) == "b + c" |
| 2082 |
|
| 2083 |
|
| 2084 |
s = "a + (b \n + c)" |
| 2085 |
tree = self.get_first_expr(s) |
| 2086 |
assert tree.get_source_segment(s) == s |
| 2087 |
assert tree.get_source_segment(s, padded=True) == s |
| 2088 |
assert tree.right.get_source_segment(s) == "b \n + c" |
| 2089 |
assert tree.right.get_source_segment(s, padded=True) == " b \n + c" |
| 2090 |
|
| 2091 |
def test_fstring_mismatch(self): |
| 2092 |
with pytest.raises(SyntaxError) as excinfo: |
| 2093 |
tree = self.get_ast("f'{((}')") |
| 2094 |
assert excinfo.value.msg == "unmatched ')'" |
| 2095 |
|
| 2096 |
def test_keyword_position(self): |
| 2097 |
tree = self.get_first_expr("f(a=1, **kwarg)") |
| 2098 |
assert tree.keywords[0].col_offset == 2 |
| 2099 |
assert tree.keywords[0].end_col_offset == 5 |
| 2100 |
assert tree.keywords[1].col_offset == 7 |
| 2101 |
assert tree.keywords[1].end_col_offset == 14 |
| 2102 |
|
| 2103 |
def test_invalid_star_expression(self): |
| 2104 |
input = "f(x = 5, *)" |
| 2105 |
with pytest.raises(SyntaxError) as excinfo: |
| 2106 |
self.get_ast(input) |
| 2107 |
assert excinfo.value.msg == "Invalid star expression" |
| 2108 |
|
| 2109 |
def test_invalid_except_star(self): |
| 2110 |
input = """ |
| 2111 |
try: |
| 2112 |
pass |
| 2113 |
except*: |
| 2114 |
pass |
| 2115 |
""" |
| 2116 |
with pytest.raises(SyntaxError) as excinfo: |
| 2117 |
self.get_ast(input) |
| 2118 |
assert excinfo.value.msg == "expected one or more exception types" |
| 2119 |
|
| 2120 |
def test_invalid_star_no_parens(self): |
| 2121 |
import textwrap |
| 2122 |
s = textwrap.dedent(""" |
| 2123 |
try: |
| 2124 |
pass |
| 2125 |
except* A, B, C as zxiensp: |
| 2126 |
pass |
| 2127 |
""") |
| 2128 |
with pytest.raises(SyntaxError) as excinfo: |
| 2129 |
self.get_ast(s) |
| 2130 |
assert excinfo.value.msg == "multiple exception types must be parenthesized" |
| 2131 |
|
| 2132 |
def test_with_parenthesized_conditional_low_feature_version(self): |
| 2133 |
|
| 2134 |
|
| 2135 |
|
| 2136 |
info = pyparse.CompileInfo("<test>", "exec", feature_version=8) |
| 2137 |
ast_node = self.parser.parse_source( |
| 2138 |
"with (x() if y else z()): pass", info) |
| 2139 |
assert isinstance(ast_node.body[0], ast.With) |
| 2140 |
|
| 2141 |
def test_with_parenthesized_items_rejected_on_low_feature_version(self): |
| 2142 |
|
| 2143 |
info = pyparse.CompileInfo("<test>", "exec", feature_version=8) |
| 2144 |
with pytest.raises(SyntaxError) as excinfo: |
| 2145 |
self.parser.parse_source("with (a(), b()): pass", info) |
| 2146 |
assert "Parenthesized with items" in excinfo.value.msg |