test_parser.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # -*- coding: utf-8 -*-
  2. from textwrap import dedent
  3. import pytest
  4. from parso import parse
  5. from parso.python import tree
  6. from parso.utils import split_lines
  7. def test_basic_parsing(each_version):
  8. def compare(string):
  9. """Generates the AST object and then regenerates the code."""
  10. assert parse(string, version=each_version).get_code() == string
  11. compare('\na #pass\n')
  12. compare('wblabla* 1\t\n')
  13. compare('def x(a, b:3): pass\n')
  14. compare('assert foo\n')
  15. def test_subscope_names(each_version):
  16. def get_sub(source):
  17. return parse(source, version=each_version).children[0]
  18. name = get_sub('class Foo: pass').name
  19. assert name.start_pos == (1, len('class '))
  20. assert name.end_pos == (1, len('class Foo'))
  21. assert name.value == 'Foo'
  22. name = get_sub('def foo(): pass').name
  23. assert name.start_pos == (1, len('def '))
  24. assert name.end_pos == (1, len('def foo'))
  25. assert name.value == 'foo'
  26. def test_import_names(each_version):
  27. def get_import(source):
  28. return next(parse(source, version=each_version).iter_imports())
  29. imp = get_import('import math\n')
  30. names = imp.get_defined_names()
  31. assert len(names) == 1
  32. assert names[0].value == 'math'
  33. assert names[0].start_pos == (1, len('import '))
  34. assert names[0].end_pos == (1, len('import math'))
  35. assert imp.start_pos == (1, 0)
  36. assert imp.end_pos == (1, len('import math'))
  37. def test_end_pos(each_version):
  38. s = dedent('''
  39. x = ['a', 'b', 'c']
  40. def func():
  41. y = None
  42. ''')
  43. parser = parse(s, version=each_version)
  44. scope = next(parser.iter_funcdefs())
  45. assert scope.start_pos == (3, 0)
  46. assert scope.end_pos == (5, 0)
  47. def test_carriage_return_statements(each_version):
  48. source = dedent('''
  49. foo = 'ns1!'
  50. # this is a namespace package
  51. ''')
  52. source = source.replace('\n', '\r\n')
  53. stmt = parse(source, version=each_version).children[0]
  54. assert '#' not in stmt.get_code()
  55. def test_incomplete_list_comprehension(each_version):
  56. """ Shouldn't raise an error, same bug as #418. """
  57. # With the old parser this actually returned a statement. With the new
  58. # parser only valid statements generate one.
  59. children = parse('(1 for def', version=each_version).children
  60. assert [c.type for c in children] == \
  61. ['error_node', 'error_node', 'endmarker']
  62. def test_newline_positions(each_version):
  63. endmarker = parse('a\n', version=each_version).children[-1]
  64. assert endmarker.end_pos == (2, 0)
  65. new_line = endmarker.get_previous_leaf()
  66. assert new_line.start_pos == (1, 1)
  67. assert new_line.end_pos == (2, 0)
  68. def test_end_pos_error_correction(each_version):
  69. """
  70. Source code without ending newline are given one, because the Python
  71. grammar needs it. However, they are removed again. We still want the right
  72. end_pos, even if something breaks in the parser (error correction).
  73. """
  74. s = 'def x():\n .'
  75. m = parse(s, version=each_version)
  76. func = m.children[0]
  77. assert func.type == 'funcdef'
  78. assert func.end_pos == (2, 2)
  79. assert m.end_pos == (2, 2)
  80. def test_param_splitting(each_version):
  81. """
  82. Jedi splits parameters into params, this is not what the grammar does,
  83. but Jedi does this to simplify argument parsing.
  84. """
  85. def check(src, result):
  86. m = parse(src, version=each_version)
  87. assert not list(m.iter_funcdefs())
  88. check('def x(a, (b, c)):\n pass', ['a'])
  89. check('def x((b, c)):\n pass', [])
  90. def test_unicode_string():
  91. s = tree.String(None, 'bö', (0, 0))
  92. assert repr(s) # Should not raise an Error!
  93. def test_backslash_dos_style(each_version):
  94. assert parse('\\\r\n', version=each_version)
  95. def test_started_lambda_stmt(each_version):
  96. m = parse('lambda a, b: a i', version=each_version)
  97. assert m.children[0].type == 'error_node'
  98. @pytest.mark.parametrize('code', ['foo "', 'foo """\n', 'foo """\nbar'])
  99. def test_open_string_literal(each_version, code):
  100. """
  101. Testing mostly if removing the last newline works.
  102. """
  103. lines = split_lines(code, keepends=True)
  104. end_pos = (len(lines), len(lines[-1]))
  105. module = parse(code, version=each_version)
  106. assert module.get_code() == code
  107. assert module.end_pos == end_pos == module.children[1].end_pos
  108. def test_too_many_params():
  109. with pytest.raises(TypeError):
  110. parse('asdf', hello=3)
  111. def test_dedent_at_end(each_version):
  112. code = dedent('''
  113. for foobar in [1]:
  114. foobar''')
  115. module = parse(code, version=each_version)
  116. assert module.get_code() == code
  117. suite = module.children[0].children[-1]
  118. foobar = suite.children[-1]
  119. assert foobar.type == 'name'
  120. def test_no_error_nodes(each_version):
  121. def check(node):
  122. assert node.type not in ('error_leaf', 'error_node')
  123. try:
  124. children = node.children
  125. except AttributeError:
  126. pass
  127. else:
  128. for child in children:
  129. check(child)
  130. check(parse("if foo:\n bar", version=each_version))
  131. def test_named_expression(works_ge_py38):
  132. works_ge_py38.parse("(a := 1, a + 1)")
  133. def test_extended_rhs_annassign(works_ge_py38):
  134. works_ge_py38.parse("x: y = z,")
  135. works_ge_py38.parse("x: Tuple[int, ...] = z, *q, w")
  136. @pytest.mark.parametrize(
  137. 'param_code', [
  138. 'a=1, /',
  139. 'a, /',
  140. 'a=1, /, b=3',
  141. 'a, /, b',
  142. 'a, /, b',
  143. 'a, /, *, b',
  144. 'a, /, **kwargs',
  145. ]
  146. )
  147. def test_positional_only_arguments(works_ge_py38, param_code):
  148. works_ge_py38.parse("def x(%s): pass" % param_code)
  149. @pytest.mark.parametrize(
  150. 'expression', [
  151. 'a + a',
  152. 'lambda x: x',
  153. 'a := lambda x: x'
  154. ]
  155. )
  156. def test_decorator_expression(works_ge_py39, expression):
  157. works_ge_py39.parse("@%s\ndef x(): pass" % expression)