Debian Codegraph @

test/test_parso_integration/test_parser_utils.py

raw symbols SCIP
1 import gc
2 from pathlib import Path
3
4 from jedi import parser_utils
5 from parso import parse
6 from parso.cache import parser_cache
7 from parso.python import tree
8
9 import pytest
10
11
12 class TestCallAndName:
13 def get_call(self, source):
14 # Get the simple_stmt and then the first one.
15 node = parse(source).children[0]
16 if node.type == 'simple_stmt':
17 return node.children[0]
18 return node
19
20 def test_name_and_call_positions(self):
21 name = self.get_call('name\nsomething_else')
22 assert name.value == 'name'
23 assert name.start_pos == (1, 0)
24 assert name.end_pos == (1, 4)
25
26 leaf = self.get_call('1.0\n')
27 assert leaf.value == '1.0'
28 assert parser_utils.safe_literal_eval(leaf.value) == 1.0
29 assert leaf.start_pos == (1, 0)
30 assert leaf.end_pos == (1, 3)
31
32 def test_call_type(self):
33 call = self.get_call('hello')
34 assert isinstance(call, tree.Name)
35
36 def test_literal_type(self):
37 literal = self.get_call('1.0')
38 assert isinstance(literal, tree.Literal)
39 assert type(parser_utils.safe_literal_eval(literal.value)) == float
40
41 literal = self.get_call('1')
42 assert isinstance(literal, tree.Literal)
43 assert type(parser_utils.safe_literal_eval(literal.value)) == int
44
45 literal = self.get_call('"hello"')
46 assert isinstance(literal, tree.Literal)
47 assert parser_utils.safe_literal_eval(literal.value) == 'hello'
48
49
50 def test_hex_values_in_docstring():
51 source = r'''
52 def foo(object):
53 """
54 \xff
55 """
56 return 1
57 '''
58
59 doc = parser_utils.clean_scope_docstring(next(parse(source).iter_funcdefs()))
60 assert doc == '\xff'
61
62
63 @pytest.mark.parametrize(
64 'code,signature', [
65 ('def my_function(x, typed: Type, z):\n return', 'my_function(x, typed: Type, z)'),
66 ('def my_function(x, y, z) -> str:\n return', 'my_function(x, y, z) -> str'),
67 ('lambda x, y, z: x + y * z\n', '<lambda>(x, y, z)')
68 ])
69 def test_get_signature(code, signature):
70 node = parse(code, version='3.14').children[0]
71 if node.type == 'simple_stmt':
72 node = node.children[0]
73 assert parser_utils.get_signature(node) == signature
74
75
76 def test_parser_cache_clear(Script):
77 """
78 If parso clears its cache, Jedi should not keep those resources, they
79 should be freed.
80 """
81 script = Script("a = abs\na", path=Path(__file__).parent / 'parser_cache_test_foo.py')
82 script.complete()
83 module_id = id(script._module_node)
84 del parser_cache[script._inference_state.grammar._hashed][script.path]
85 del script
86
87 gc.collect()
88 assert module_id not in [id(m) for m in gc.get_referrers(tree.Module)]