Debian Codegraph @

testing/code/test_source.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import inspect
5 import linecache
6 from pathlib import Path
7 import sys
8 import textwrap
9 from typing import Any
10 from unittest.mock import patch
11
12 from _pytest._code import Code
13 from _pytest._code import Frame
14 from _pytest._code import getfslineno
15 from _pytest._code import Source
16 from _pytest.pathlib import import_path
17 import pytest
18
19
20 def test_source_str_function() -> None:
21 x = Source("3")
22 assert str(x) == "3"
23
24 x = Source(" 3")
25 assert str(x) == "3"
26
27 x = Source(
28 """
29 3
30 """
31 )
32 assert str(x) == "\n3"
33
34
35 def test_source_from_function() -> None:
36 source = Source(test_source_str_function)
37 assert str(source).startswith("def test_source_str_function() -> None:")
38
39
40 def test_source_from_method() -> None:
41 class TestClass:
42 def test_method(self):
43 pass
44
45 source = Source(TestClass().test_method)
46 assert source.lines == ["def test_method(self):", " pass"]
47
48
49 def test_source_from_lines() -> None:
50 lines = ["a \n", "b\n", "c"]
51 source = Source(lines)
52 assert source.lines == ["a ", "b", "c"]
53
54
55 def test_source_from_inner_function() -> None:
56 def f():
57 raise NotImplementedError()
58
59 source = Source(f)
60 assert str(source).startswith("def f():")
61
62
63 def test_source_strips() -> None:
64 source = Source("")
65 assert source == Source()
66 assert str(source) == ""
67 assert source.strip() == source
68
69
70 def test_source_strip_multiline() -> None:
71 source = Source()
72 source.lines = ["", " hello", " "]
73 source2 = source.strip()
74 assert source2.lines == [" hello"]
75
76
77 class TestAccesses:
78 def setup_class(self) -> None:
79 self.source = Source(
80 """\
81 def f(x):
82 pass
83 def g(x):
84 pass
85 """
86 )
87
88 def test_getrange(self) -> None:
89 x = self.source[0:2]
90 assert len(x.lines) == 2
91 assert str(x) == "def f(x):\n pass"
92
93 def test_getrange_step_not_supported(self) -> None:
94 with pytest.raises(IndexError, match=r"step"):
95 self.source[::2]
96
97 def test_getline(self) -> None:
98 x = self.source[0]
99 assert x == "def f(x):"
100
101 def test_len(self) -> None:
102 assert len(self.source) == 4
103
104 def test_iter(self) -> None:
105 values = [x for x in self.source]
106 assert len(values) == 4
107
108
109 class TestSourceParsing:
110 def setup_class(self) -> None:
111 self.source = Source(
112 """\
113 def f(x):
114 assert (x ==
115 3 +
116 4)
117 """
118 ).strip()
119
120 def test_getstatement(self) -> None:
121 # print str(self.source)
122 ass = str(self.source[1:])
123 for i in range(1, 4):
124 # print "trying start in line %r" % self.source[i]
125 s = self.source.getstatement(i)
126 # x = s.deindent()
127 assert str(s) == ass
128
129 def test_getstatementrange_triple_quoted(self) -> None:
130 # print str(self.source)
131 source = Source(
132 """hello('''
133 ''')"""
134 )
135 s = source.getstatement(0)
136 assert s == source
137 s = source.getstatement(1)
138 assert s == source
139
140 def test_getstatementrange_within_constructs(self) -> None:
141 source = Source(
142 """\
143 try:
144 try:
145 raise ValueError
146 except SomeThing:
147 pass
148 finally:
149 42
150 """
151 )
152 assert len(source) == 7
153 # check all lineno's that could occur in a traceback
154 # assert source.getstatementrange(0) == (0, 7)
155 # assert source.getstatementrange(1) == (1, 5)
156 assert source.getstatementrange(2) == (2, 3)
157 assert source.getstatementrange(3) == (3, 4)
158 assert source.getstatementrange(4) == (4, 5)
159 # assert source.getstatementrange(5) == (0, 7)
160 assert source.getstatementrange(6) == (6, 7)
161
162 def test_getstatementrange_bug(self) -> None:
163 source = Source(
164 """\
165 try:
166 x = (
167 y +
168 z)
169 except:
170 pass
171 """
172 )
173 assert len(source) == 6
174 assert source.getstatementrange(2) == (1, 4)
175
176 def test_getstatementrange_bug2(self) -> None:
177 source = Source(
178 """\
179 assert (
180 33
181 ==
182 [
183 X(3,
184 b=1, c=2
185 ),
186 ]
187 )
188 """
189 )
190 assert len(source) == 9
191 assert source.getstatementrange(5) == (0, 9)
192
193 def test_getstatementrange_ast_issue58(self) -> None:
194 source = Source(
195 """\
196
197 def test_some():
198 for a in [a for a in
199 CAUSE_ERROR]: pass
200
201 x = 3
202 """
203 )
204 assert getstatement(2, source).lines == source.lines[2:3]
205 assert getstatement(3, source).lines == source.lines[3:4]
206
207 def test_getstatementrange_out_of_bounds_py3(self) -> None:
208 source = Source("if xxx:\n from .collections import something")
209 r = source.getstatementrange(1)
210 assert r == (1, 2)
211
212 def test_getstatementrange_with_syntaxerror_issue7(self) -> None:
213 source = Source(":")
214 with pytest.raises(SyntaxError):
215 source.getstatementrange(0)
216
217
218 def test_getstartingblock_singleline() -> None:
219 class A:
220 def __init__(self, *args) -> None:
221 frame = sys._getframe(1)
222 self.source = Frame(frame).statement
223
224 x = A("x", "y")
225
226 values = [i for i in x.source.lines if i.strip()]
227 assert len(values) == 1
228
229
230 def test_getline_finally() -> None:
231 def c() -> None:
232 pass
233
234 with pytest.raises(TypeError) as excinfo:
235 teardown = None
236 try:
237 c(1) # type: ignore
238 finally:
239 if teardown:
240 teardown() # type: ignore[unreachable]
241 source = excinfo.traceback[-1].statement
242 assert str(source).strip() == "c(1) # type: ignore"
243
244
245 def test_getfuncsource_dynamic() -> None:
246 def f():
247 raise NotImplementedError()
248
249 def g():
250 pass # pragma: no cover
251
252 f_source = Source(f)
253 g_source = Source(g)
254 assert str(f_source).strip() == "def f():\n raise NotImplementedError()"
255 assert str(g_source).strip() == "def g():\n pass # pragma: no cover"
256
257
258 def test_getfuncsource_with_multiline_string() -> None:
259 def f():
260 c = """while True:
261 pass
262 """
263
264 expected = '''\
265 def f():
266 c = """while True:
267 pass
268 """
269 '''
270 assert str(Source(f)) == expected.rstrip()
271
272
273 def test_deindent() -> None:
274 from _pytest._code.source import deindent as deindent
275
276 assert deindent(["\tfoo", "\tbar"]) == ["foo", "bar"]
277
278 source = """\
279 def f():
280 def g():
281 pass
282 """
283 lines = deindent(source.splitlines())
284 assert lines == ["def f():", " def g():", " pass"]
285
286
287 def test_source_of_class_at_eof_without_newline(_sys_snapshot, tmp_path: Path) -> None:
288 # this test fails because the implicit inspect.getsource(A) below
289 # does not return the "x = 1" last line.
290 source = Source(
291 """
292 class A:
293 def method(self):
294 x = 1
295 """
296 )
297 path = tmp_path.joinpath("a.py")
298 path.write_text(str(source), encoding="utf-8")
299 mod: Any = import_path(path, root=tmp_path, consider_namespace_packages=False)
300 s2 = Source(mod.A)
301 assert str(source).strip() == str(s2).strip()
302
303
304 if True:
305
306 def x():
307 pass
308
309
310 def test_source_fallback() -> None:
311 src = Source(x)
312 expected = """def x():
313 pass"""
314 assert str(src) == expected
315
316
317 def test_findsource_fallback() -> None:
318 from _pytest._code.source import findsource
319
320 src, lineno = findsource(x)
321 assert src is not None
322 assert "test_findsource_simple" in str(src)
323 assert src[lineno] == " def x():"
324
325
326 def test_findsource(monkeypatch) -> None:
327 from _pytest._code.source import findsource
328
329 filename = "<pytest-test_findsource>"
330 lines = ["if 1:\n", " def x():\n", " pass\n"]
331 co = compile("".join(lines), filename, "exec")
332
333 monkeypatch.setitem(linecache.cache, filename, (1, None, lines, filename))
334
335 src, lineno = findsource(co)
336 assert src is not None
337 assert "if 1:" in str(src)
338
339 d: dict[str, Any] = {}
340 eval(co, d)
341 src, lineno = findsource(d["x"])
342 assert src is not None
343 assert "if 1:" in str(src)
344 assert src[lineno] == " def x():"
345
346
347 def test_getfslineno() -> None:
348 def f(x) -> None:
349 raise NotImplementedError()
350
351 fspath, lineno = getfslineno(f)
352
353 assert isinstance(fspath, Path)
354 assert fspath.name == "test_source.py"
355 assert lineno == f.__code__.co_firstlineno - 1 # see findsource
356
357 class A:
358 pass
359
360 fspath, lineno = getfslineno(A)
361
362 _, A_lineno = inspect.findsource(A)
363 assert isinstance(fspath, Path)
364 assert fspath.name == "test_source.py"
365 assert lineno == A_lineno
366
367 assert getfslineno(3) == ("", -1)
368
369 class B:
370 pass
371
372 B.__name__ = B.__qualname__ = "B2"
373 # Since Python 3.13 this started working.
374 if sys.version_info >= (3, 13):
375 assert getfslineno(B)[1] != -1
376 else:
377 assert getfslineno(B)[1] == -1
378
379
380 def test_code_of_object_instance_with_call() -> None:
381 class A:
382 pass
383
384 with pytest.raises(TypeError):
385 Source(A())
386
387 class WithCall:
388 def __call__(self) -> None:
389 pass
390
391 code = Code.from_function(WithCall())
392 assert "pass" in str(code.source())
393
394 class Hello:
395 def __call__(self) -> None:
396 pass
397
398 with pytest.raises(TypeError):
399 Code.from_function(Hello)
400
401
402 def getstatement(lineno: int, source) -> Source:
403 from _pytest._code.source import getstatementrange_ast
404
405 src = Source(source)
406 _ast, start, end = getstatementrange_ast(lineno, src)
407 return src[start:end]
408
409
410 def test_oneline() -> None:
411 source = getstatement(0, "raise ValueError")
412 assert str(source) == "raise ValueError"
413
414
415 def test_comment_and_no_newline_at_end() -> None:
416 from _pytest._code.source import getstatementrange_ast
417
418 source = Source(
419 [
420 "def test_basic_complex():",
421 " assert 1 == 2",
422 "# vim: filetype=pyopencl:fdm=marker",
423 ]
424 )
425 _ast, _start, end = getstatementrange_ast(1, source)
426 assert end == 2
427
428
429 def test_oneline_and_comment() -> None:
430 source = getstatement(0, "raise ValueError\n#hello")
431 assert str(source) == "raise ValueError"
432
433
434 def test_comments() -> None:
435 source = '''def test():
436 "comment 1"
437 x = 1
438 # comment 2
439 # comment 3
440
441 assert False
442
443 """
444 comment 4
445 """
446 '''
447 for line in range(2, 6):
448 assert str(getstatement(line, source)) == " x = 1"
449 for line in range(6, 8):
450 assert str(getstatement(line, source)) == " assert False"
451 for line in range(8, 10):
452 assert str(getstatement(line, source)) == '"""\ncomment 4\n"""'
453
454
455 def test_comment_in_statement() -> None:
456 source = """test(foo=1,
457 # comment 1
458 bar=2)
459 """
460 for line in range(1, 3):
461 assert (
462 str(getstatement(line, source))
463 == "test(foo=1,\n # comment 1\n bar=2)"
464 )
465
466
467 def test_source_with_decorator() -> None:
468 """Test behavior with Source / Code().source with regard to decorators."""
469
470 @pytest.mark.foo
471 def deco_mark():
472 assert False
473
474 src = inspect.getsource(deco_mark)
475 assert textwrap.indent(str(Source(deco_mark)), " ") + "\n" == src
476 assert src.startswith(" @pytest.mark.foo")
477
478 @pytest.fixture
479 def deco_fixture():
480 assert False
481
482 src = inspect.getsource(deco_fixture._get_wrapped_function())
483 assert src == " @pytest.fixture\n def deco_fixture():\n assert False\n"
484 # Make sure the decorator is not a wrapped function
485 assert not str(Source(deco_fixture)).startswith("@functools.wraps(function)")
486 assert (
487 textwrap.indent(str(Source(deco_fixture._get_wrapped_function())), " ")
488 + "\n"
489 == src
490 )
491
492
493 def test_single_line_else() -> None:
494 source = getstatement(1, "if False: 2\nelse: 3")
495 assert str(source) == "else: 3"
496
497
498 def test_single_line_finally() -> None:
499 source = getstatement(1, "try: 1\nfinally: 3")
500 assert str(source) == "finally: 3"
501
502
503 def test_issue55() -> None:
504 source = (
505 "def round_trip(dinp):\n assert 1 == dinp\n"
506 'def test_rt():\n round_trip("""\n""")\n'
507 )
508 s = getstatement(3, source)
509 assert str(s) == ' round_trip("""\n""")'
510
511
512 def test_multiline() -> None:
513 source = getstatement(
514 0,
515 """\
516 raise ValueError(
517 23
518 )
519 x = 3
520 """,
521 )
522 assert str(source) == "raise ValueError(\n 23\n)"
523
524
525 class TestTry:
526 def setup_class(self) -> None:
527 self.source = """\
528 try:
529 raise ValueError
530 except Something:
531 raise IndexError(1)
532 else:
533 raise KeyError()
534 """
535
536 def test_body(self) -> None:
537 source = getstatement(1, self.source)
538 assert str(source) == " raise ValueError"
539
540 def test_except_line(self) -> None:
541 source = getstatement(2, self.source)
542 assert str(source) == "except Something:"
543
544 def test_except_body(self) -> None:
545 source = getstatement(3, self.source)
546 assert str(source) == " raise IndexError(1)"
547
548 def test_else(self) -> None:
549 source = getstatement(5, self.source)
550 assert str(source) == " raise KeyError()"
551
552
553 class TestTryFinally:
554 def setup_class(self) -> None:
555 self.source = """\
556 try:
557 raise ValueError
558 finally:
559 raise IndexError(1)
560 """
561
562 def test_body(self) -> None:
563 source = getstatement(1, self.source)
564 assert str(source) == " raise ValueError"
565
566 def test_finally(self) -> None:
567 source = getstatement(3, self.source)
568 assert str(source) == " raise IndexError(1)"
569
570
571 class TestIf:
572 def setup_class(self) -> None:
573 self.source = """\
574 if 1:
575 y = 3
576 elif False:
577 y = 5
578 else:
579 y = 7
580 """
581
582 def test_body(self) -> None:
583 source = getstatement(1, self.source)
584 assert str(source) == " y = 3"
585
586 def test_elif_clause(self) -> None:
587 source = getstatement(2, self.source)
588 assert str(source) == "elif False:"
589
590 def test_elif(self) -> None:
591 source = getstatement(3, self.source)
592 assert str(source) == " y = 5"
593
594 def test_else(self) -> None:
595 source = getstatement(5, self.source)
596 assert str(source) == " y = 7"
597
598
599 def test_semicolon() -> None:
600 s = """\
601 hello ; pytest.skip()
602 """
603 source = getstatement(0, s)
604 assert str(source) == s.strip()
605
606
607 def test_def_online() -> None:
608 s = """\
609 def func(): raise ValueError(42)
610
611 def something():
612 pass
613 """
614 source = getstatement(0, s)
615 assert str(source) == "def func(): raise ValueError(42)"
616
617
618 def test_decorator() -> None:
619 s = """\
620 def foo(f):
621 pass
622
623 @foo
624 def bar():
625 pass
626 """
627 source = getstatement(3, s)
628 assert "@foo" in str(source)
629
630
631 def XXX_test_expression_multiline() -> None:
632 source = """\
633 something
634 '''
635 '''"""
636 result = getstatement(1, source)
637 assert str(result) == "'''\n'''"
638
639
640 def test_getstartingblock_multiline() -> None:
641 class A:
642 def __init__(self, *args):
643 frame = sys._getframe(1)
644 self.source = Frame(frame).statement
645
646 # fmt: off
647 x = A('x',
648 'y'
649 ,
650 'z')
651 # fmt: on
652 values = [i for i in x.source.lines if i.strip()]
653 assert len(values) == 4
654
655
656 def test_patched_compile() -> None:
657 # ensure Source doesn't break
658 # when compile() modifies code dynamically
659 from builtins import compile
660
661 def patched_compile1(_, *args, **kwargs):
662 return compile("", *args, **kwargs)
663
664 with patch("builtins.compile", new=patched_compile1):
665 Source(patched_compile1).getstatement(1)
666
667 # fmt: off
668 def patched_compile2(_, *args, **kwargs):
669
670 # first line of this function (the one above this one) must be empty
671 # LINES must be equal or higher than number of lines of this function
672 LINES = 99
673 return compile("\ndef a():\n" + "\n" * LINES + " pass", *args, **kwargs)
674 # fmt: on
675
676 with patch("builtins.compile", new=patched_compile2):
677 Source(patched_compile2).getstatement(1)