File: test_fast_parser.py

package info (click to toggle)
python-jedi 0.10.0~git1%2Bf05c071-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,064 kB
  • ctags: 3,014
  • sloc: python: 16,997; makefile: 149; ansic: 13
file content (496 lines) | stat: -rw-r--r-- 9,929 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
from textwrap import dedent

import pytest

import jedi
from jedi._compatibility import u
from jedi import cache
from jedi.parser import load_grammar
from jedi.parser.fast import FastParser
from jedi.parser.utils import save_parser


def test_add_to_end():
    """
    fast_parser doesn't parse everything again. It just updates with the
    help of caches, this is an example that didn't work.
    """

    a = dedent("""
    class Abc():
        def abc(self):
            self.x = 3

    class Two(Abc):
        def h(self):
            self
    """)      # ^ here is the first completion

    b = "    def g(self):\n" \
        "        self."
    assert jedi.Script(a, 8, 12, 'example.py').completions()
    assert jedi.Script(a + b, path='example.py').completions()

    a = a[:-1] + '.\n'
    assert jedi.Script(a, 8, 13, 'example.py').completions()
    assert jedi.Script(a + b, path='example.py').completions()


def test_class_in_docstr():
    """
    Regression test for a problem with classes in docstrings.
    """
    a = '"\nclasses\n"'
    jedi.Script(a, 1, 0)._get_module()

    b = a + '\nimport os'
    assert jedi.Script(b, 4, 8).goto_assignments()


def test_carriage_return_splitting():
    source = u(dedent('''



        "string"

        class Foo():
            pass
        '''))
    source = source.replace('\n', '\r\n')
    p = FastParser(load_grammar(), source)
    assert [n.value for lst in p.module.names_dict.values() for n in lst] == ['Foo']


def test_split_parts():
    cache.parser_cache.pop(None, None)

    def splits(source):
        class Mock(FastParser):
            def __init__(self, *args):
                self.number_of_splits = 0

        return tuple(FastParser._split_parts(Mock(None, None), source))

    def test(*parts):
        assert splits(''.join(parts)) == parts

    test('a\n\n', 'def b(): pass\n', 'c\n')
    test('a\n', 'def b():\n pass\n', 'c\n')

    test('from x\\\n')
    test('a\n\\\n')


def check_fp(src, number_parsers_used, number_of_splits=None, number_of_misses=0):
    if number_of_splits is None:
        number_of_splits = number_parsers_used

    p = FastParser(load_grammar(), u(src))
    save_parser(None, p, pickling=False)

    assert src == p.module.get_code()
    assert p.number_of_splits == number_of_splits
    assert p.number_parsers_used == number_parsers_used
    assert p.number_of_misses == number_of_misses
    return p.module


def test_change_and_undo():
    # Empty the parser cache for the path None.
    cache.parser_cache.pop(None, None)
    func_before = 'def func():\n    pass\n'
    # Parse the function and a.
    check_fp(func_before + 'a', 2)
    # Parse just b.
    check_fp(func_before + 'b', 1, 2)
    # b has changed to a again, so parse that.
    check_fp(func_before + 'a', 1, 2)
    # Same as before no parsers should be used.
    check_fp(func_before + 'a', 0, 2)

    # Getting rid of an old parser: Still no parsers used.
    check_fp('a', 0, 1)
    # Now the file has completely change and we need to parse.
    check_fp('b', 1, 1)
    # And again.
    check_fp('a', 1, 1)


def test_positions():
    # Empty the parser cache for the path None.
    cache.parser_cache.pop(None, None)

    func_before = 'class A:\n pass\n'
    m = check_fp(func_before + 'a', 2)
    assert m.start_pos == (1, 0)
    assert m.end_pos == (3, 1)

    m = check_fp('a', 0, 1)
    assert m.start_pos == (1, 0)
    assert m.end_pos == (1, 1)


def test_if():
    src = dedent('''\
    def func():
        x = 3
        if x:
            def y():
                return x
        return y()

    func()
    ''')

    # Two parsers needed, one for pass and one for the function.
    check_fp(src, 2)
    assert [d.name for d in jedi.Script(src, 8, 6).goto_definitions()] == ['int']


def test_if_simple():
    src = dedent('''\
    if 1:
        a = 3
    ''')
    check_fp(src + 'a', 1)
    check_fp(src + "else:\n    a = ''\na", 1)


def test_for():
    src = dedent("""\
    for a in [1,2]:
        a

    for a1 in 1,"":
        a1
    """)
    check_fp(src, 1)


def test_class_with_class_var():
    src = dedent("""\
    class SuperClass:
        class_super = 3
        def __init__(self):
            self.foo = 4
    pass
    """)
    check_fp(src, 3)


def test_func_with_if():
    src = dedent("""\
    def recursion(a):
        if foo:
            return recursion(a)
        else:
            if bar:
                return inexistent
            else:
                return a
    """)
    check_fp(src, 1)


def test_decorator():
    src = dedent("""\
    class Decorator():
        @memoize
        def dec(self, a):
            return a
    """)
    check_fp(src, 2)


def test_nested_funcs():
    src = dedent("""\
    def memoize(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    """)
    check_fp(src, 3)


def test_class_and_if():
    src = dedent("""\
    class V:
        def __init__(self):
            pass

        if 1:
            c = 3

    def a_func():
        return 1

    # COMMENT
    a_func()""")
    check_fp(src, 5, 5)
    assert [d.name for d in jedi.Script(src).goto_definitions()] == ['int']


def test_func_with_for_and_comment():
    # The first newline is important, leave it. It should not trigger another
    # parser split.
    src = dedent("""\

    def func():
        pass


    for a in [1]:
        # COMMENT
        a""")
    check_fp(src, 2)
    # We don't need to parse the for loop, but we need to parse the other two,
    # because the split is in a different place.
    check_fp('a\n' + src, 2, 3)


def test_multi_line_params():
    src = dedent("""\
    def x(a,
          b):
        pass

    foo = 1
    """)
    check_fp(src, 2)


def test_one_statement_func():
    src = dedent("""\
    first
    def func(): a
    """)
    check_fp(src + 'second', 3)
    # Empty the parser cache, because we're not interested in modifications
    # here.
    cache.parser_cache.pop(None, None)
    check_fp(src + 'def second():\n a', 3)


def test_class_func_if():
    src = dedent("""\
    class Class:
        def func(self):
            if 1:
                a
            else:
                b

    pass
    """)
    check_fp(src, 3)


def test_for_on_one_line():
    src = dedent("""\
    foo = 1
    for x in foo: pass

    def hi():
        pass
    """)
    check_fp(src, 2)

    src = dedent("""\
    def hi():
        for x in foo: pass
        pass

    pass
    """)
    check_fp(src, 2)

    src = dedent("""\
    def hi():
        for x in foo: pass

        def nested():
            pass
    """)
    check_fp(src, 2)


def test_multi_line_for():
    src = dedent("""\
    for x in [1,
              2]:
        pass

    pass
    """)
    check_fp(src, 1)


def test_wrong_indentation():
    src = dedent("""\
    def func():
        a
         b
        a
    """)
    #check_fp(src, 1)

    src = dedent("""\
    def complex():
        def nested():
            a
             b
            a

        def other():
            pass
    """)
    check_fp(src, 3)


def test_open_parentheses():
    func = 'def func():\n a'
    code = u('isinstance(\n\n' + func)
    p = FastParser(load_grammar(), code)
    # As you can see, the part that was failing is still there in the get_code
    # call. It is not relevant for evaluation, but still available as an
    # ErrorNode.
    assert p.module.get_code() == code
    assert p.number_of_splits == 2
    assert p.number_parsers_used == 2
    save_parser(None, p, pickling=False)

    # Now with a correct parser it should work perfectly well.
    check_fp('isinstance()\n' + func, 1, 2)


def test_strange_parentheses():
    src = dedent("""
    class X():
        a = (1
    if 1 else 2)
        def x():
            pass
    """)
    check_fp(src, 2)


def test_backslash():
    src = dedent(r"""
    a = 1\
        if 1 else 2
    def x():
        pass
    """)
    check_fp(src, 2)

    src = dedent(r"""
    def x():
        a = 1\
    if 1 else 2
        def y():
            pass
    """)
    # The dangling if leads to not splitting where we theoretically could
    # split.
    check_fp(src, 2)

    src = dedent(r"""
    def first():
        if foo \
                and bar \
                or baz:
            pass
    def second():
        pass
    """)
    check_fp(src, 2)



def test_fake_parentheses():
    """
    The fast parser splitting counts parentheses, but not as correct tokens.
    Therefore parentheses in string tokens are included as well. This needs to
    be accounted for.
    """
    src = dedent(r"""
    def x():
        a = (')'
    if 1 else 2)
        def y():
            pass
        def z():
            pass
    """)
    check_fp(src, 3, 2, 1)


def test_additional_indent():
    source = dedent('''\
    int(
      def x():
          pass
    ''')

    check_fp(source, 2)


def test_incomplete_function():
    source = '''return ImportErr'''

    script = jedi.Script(dedent(source), 1, 3)
    assert script.completions()


def test_string_literals():
    """Simplified case of jedi-vim#377."""
    source = dedent("""
    x = ur''' 

    def foo():
        pass
    """)

    script = jedi.Script(dedent(source))
    script._get_module().end_pos == (6, 0)
    assert script.completions()


def test_decorator_string_issue():
    """
    Test case from #589
    """
    source = dedent('''\
    """
      @"""
    def bla():
      pass

    bla.''')

    s = jedi.Script(source)
    assert s.completions()
    assert s._get_module().get_code() == source


def test_round_trip():
    source = dedent('''
    def x():
        """hahaha"""
    func''')

    f = FastParser(load_grammar(), u(source))
    assert f.get_parsed_node().get_code() == source


@pytest.mark.xfail()
def test_parentheses_in_string():
    code = dedent('''
    def x():
        '('

    import abc

    abc.''')
    check_fp(code, 2, 1, 1)