Debian Codegraph @

testing/test_reports.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Sequence
5
6 from _pytest._code.code import ExceptionChainRepr
7 from _pytest._code.code import ExceptionRepr
8 from _pytest.config import Config
9 from _pytest.pytester import Pytester
10 from _pytest.python_api import approx
11 from _pytest.reports import CollectReport
12 from _pytest.reports import TestReport
13 import pytest
14
15
16 class TestReportSerialization:
17 def test_xdist_longrepr_to_str_issue_241(self, pytester: Pytester) -> None:
18 """Regarding issue pytest-xdist#241.
19
20 This test came originally from test_remote.py in xdist (ca03269).
21 """
22 pytester.makepyfile(
23 """
24 def test_a(): assert False
25 def test_b(): pass
26 """
27 )
28 reprec = pytester.inline_run()
29 reports = reprec.getreports("pytest_runtest_logreport")
30 assert len(reports) == 6
31 test_a_call = reports[1]
32 assert test_a_call.when == "call"
33 assert test_a_call.outcome == "failed"
34 assert test_a_call._to_json()["longrepr"]["reprtraceback"]["style"] == "long"
35 test_b_call = reports[4]
36 assert test_b_call.when == "call"
37 assert test_b_call.outcome == "passed"
38 assert test_b_call._to_json()["longrepr"] is None
39
40 def test_xdist_report_longrepr_reprcrash_130(self, pytester: Pytester) -> None:
41 """Regarding issue pytest-xdist#130
42
43 This test came originally from test_remote.py in xdist (ca03269).
44 """
45 reprec = pytester.inline_runsource(
46 """
47 def test_fail():
48 assert False, 'Expected Message'
49 """
50 )
51 reports = reprec.getreports("pytest_runtest_logreport")
52 assert len(reports) == 3
53 rep = reports[1]
54 added_section = ("Failure Metadata", "metadata metadata", "*")
55 assert isinstance(rep.longrepr, ExceptionRepr)
56 rep.longrepr.sections.append(added_section)
57 d = rep._to_json()
58 a = TestReport._from_json(d)
59 assert isinstance(a.longrepr, ExceptionRepr)
60 # Check assembled == rep
61 assert a.__dict__.keys() == rep.__dict__.keys()
62 for key in rep.__dict__.keys():
63 if key != "longrepr":
64 assert getattr(a, key) == getattr(rep, key)
65 assert rep.longrepr.reprcrash is not None
66 assert a.longrepr.reprcrash is not None
67 assert rep.longrepr.reprcrash.lineno == a.longrepr.reprcrash.lineno
68 assert rep.longrepr.reprcrash.message == a.longrepr.reprcrash.message
69 assert rep.longrepr.reprcrash.path == a.longrepr.reprcrash.path
70 assert rep.longrepr.reprtraceback.entrysep == a.longrepr.reprtraceback.entrysep
71 assert (
72 rep.longrepr.reprtraceback.extraline == a.longrepr.reprtraceback.extraline
73 )
74 assert rep.longrepr.reprtraceback.style == a.longrepr.reprtraceback.style
75 assert rep.longrepr.sections == a.longrepr.sections
76 # Missing section attribute PR171
77 assert added_section in a.longrepr.sections
78
79 def test_reprentries_serialization_170(self, pytester: Pytester) -> None:
80 """Regarding issue pytest-xdist#170
81
82 This test came originally from test_remote.py in xdist (ca03269).
83 """
84 from _pytest._code.code import ReprEntry
85
86 reprec = pytester.inline_runsource(
87 """
88 def test_repr_entry():
89 x = 0
90 assert x
91 """,
92 "--showlocals",
93 )
94 reports = reprec.getreports("pytest_runtest_logreport")
95 assert len(reports) == 3
96 rep = reports[1]
97 assert isinstance(rep.longrepr, ExceptionRepr)
98 d = rep._to_json()
99 a = TestReport._from_json(d)
100 assert isinstance(a.longrepr, ExceptionRepr)
101
102 rep_entries = rep.longrepr.reprtraceback.reprentries
103 a_entries = a.longrepr.reprtraceback.reprentries
104 for a_entry, rep_entry in zip(a_entries, rep_entries, strict=True):
105 assert isinstance(rep_entry, ReprEntry)
106 assert rep_entry.reprfileloc is not None
107 assert rep_entry.reprfuncargs is not None
108 assert rep_entry.reprlocals is not None
109
110 assert isinstance(a_entry, ReprEntry)
111 assert a_entry.reprfileloc is not None
112 assert a_entry.reprfuncargs is not None
113 assert a_entry.reprlocals is not None
114
115 assert rep_entry.lines == a_entry.lines
116 assert rep_entry.reprfileloc.lineno == a_entry.reprfileloc.lineno
117 assert rep_entry.reprfileloc.message == a_entry.reprfileloc.message
118 assert rep_entry.reprfileloc.path == a_entry.reprfileloc.path
119 assert rep_entry.reprfuncargs.args == a_entry.reprfuncargs.args
120 assert rep_entry.reprlocals.lines == a_entry.reprlocals.lines
121 assert rep_entry.style == a_entry.style
122
123 def test_reprentries_serialization_196(self, pytester: Pytester) -> None:
124 """Regarding issue pytest-xdist#196
125
126 This test came originally from test_remote.py in xdist (ca03269).
127 """
128 from _pytest._code.code import ReprEntryNative
129
130 reprec = pytester.inline_runsource(
131 """
132 def test_repr_entry_native():
133 x = 0
134 assert x
135 """,
136 "--tb=native",
137 )
138 reports = reprec.getreports("pytest_runtest_logreport")
139 assert len(reports) == 3
140 rep = reports[1]
141 assert isinstance(rep.longrepr, ExceptionRepr)
142 d = rep._to_json()
143 a = TestReport._from_json(d)
144 assert isinstance(a.longrepr, ExceptionRepr)
145
146 rep_entries = rep.longrepr.reprtraceback.reprentries
147 a_entries = a.longrepr.reprtraceback.reprentries
148 for rep_entry, a_entry in zip(rep_entries, a_entries, strict=True):
149 assert isinstance(rep_entry, ReprEntryNative)
150 assert rep_entry.lines == a_entry.lines
151
152 def test_itemreport_outcomes(self, pytester: Pytester) -> None:
153 # This test came originally from test_remote.py in xdist (ca03269).
154 reprec = pytester.inline_runsource(
155 """
156 import pytest
157 def test_pass(): pass
158 def test_fail(): 0/0
159 @pytest.mark.skipif("True")
160 def test_skip(): pass
161 def test_skip_imperative():
162 pytest.skip("hello")
163 @pytest.mark.xfail("True")
164 def test_xfail(): 0/0
165 def test_xfail_imperative():
166 pytest.xfail("hello")
167 """
168 )
169 reports = reprec.getreports("pytest_runtest_logreport")
170 assert len(reports) == 17 # with setup/teardown "passed" reports
171 for rep in reports:
172 d = rep._to_json()
173 newrep = TestReport._from_json(d)
174 assert newrep.passed == rep.passed
175 assert newrep.failed == rep.failed
176 assert newrep.skipped == rep.skipped
177 if newrep.skipped and not hasattr(newrep, "wasxfail"):
178 assert isinstance(newrep.longrepr, tuple)
179 assert len(newrep.longrepr) == 3
180 assert newrep.outcome == rep.outcome
181 assert newrep.when == rep.when
182 assert newrep.keywords == rep.keywords
183 if rep.failed:
184 assert newrep.longreprtext == rep.longreprtext
185
186 def test_collectreport_passed(self, pytester: Pytester) -> None:
187 """This test came originally from test_remote.py in xdist (ca03269)."""
188 reprec = pytester.inline_runsource("def test_func(): pass")
189 reports = reprec.getreports("pytest_collectreport")
190 for rep in reports:
191 d = rep._to_json()
192 newrep = CollectReport._from_json(d)
193 assert newrep.passed == rep.passed
194 assert newrep.failed == rep.failed
195 assert newrep.skipped == rep.skipped
196
197 def test_collectreport_fail(self, pytester: Pytester) -> None:
198 """This test came originally from test_remote.py in xdist (ca03269)."""
199 reprec = pytester.inline_runsource("qwe abc")
200 reports = reprec.getreports("pytest_collectreport")
201 assert reports
202 for rep in reports:
203 d = rep._to_json()
204 newrep = CollectReport._from_json(d)
205 assert newrep.passed == rep.passed
206 assert newrep.failed == rep.failed
207 assert newrep.skipped == rep.skipped
208 if rep.failed:
209 assert newrep.longrepr == str(rep.longrepr)
210
211 def test_extended_report_deserialization(self, pytester: Pytester) -> None:
212 """This test came originally from test_remote.py in xdist (ca03269)."""
213 reprec = pytester.inline_runsource("qwe abc")
214 reports = reprec.getreports("pytest_collectreport")
215 assert reports
216 for rep in reports:
217 rep.extra = True # type: ignore[attr-defined]
218 d = rep._to_json()
219 newrep = CollectReport._from_json(d)
220 assert newrep.extra
221 assert newrep.passed == rep.passed
222 assert newrep.failed == rep.failed
223 assert newrep.skipped == rep.skipped
224 if rep.failed:
225 assert newrep.longrepr == str(rep.longrepr)
226
227 def test_paths_support(self, pytester: Pytester) -> None:
228 """Report attributes which are path-like should become strings."""
229 pytester.makepyfile(
230 """
231 def test_a():
232 assert False
233 """
234 )
235
236 class MyPathLike:
237 def __init__(self, path: str) -> None:
238 self.path = path
239
240 def __fspath__(self) -> str:
241 return self.path
242
243 reprec = pytester.inline_run()
244 reports = reprec.getreports("pytest_runtest_logreport")
245 assert len(reports) == 3
246 test_a_call = reports[1]
247 test_a_call.path1 = MyPathLike(str(pytester.path)) # type: ignore[attr-defined]
248 test_a_call.path2 = pytester.path # type: ignore[attr-defined]
249 data = test_a_call._to_json()
250 assert data["path1"] == str(pytester.path)
251 assert data["path2"] == str(pytester.path)
252
253 def test_deserialization_failure(self, pytester: Pytester) -> None:
254 """Check handling of failure during deserialization of report types."""
255 pytester.makepyfile(
256 """
257 def test_a():
258 assert False
259 """
260 )
261 reprec = pytester.inline_run()
262 reports = reprec.getreports("pytest_runtest_logreport")
263 assert len(reports) == 3
264 test_a_call = reports[1]
265 data = test_a_call._to_json()
266 entry = data["longrepr"]["reprtraceback"]["reprentries"][0]
267 assert entry["type"] == "ReprEntry"
268
269 entry["type"] = "Unknown"
270 with pytest.raises(
271 RuntimeError, match="INTERNALERROR: Unknown entry type returned: Unknown"
272 ):
273 TestReport._from_json(data)
274
275 @pytest.mark.parametrize("report_class", [TestReport, CollectReport])
276 def test_chained_exceptions(
277 self, pytester: Pytester, tw_mock, report_class
278 ) -> None:
279 """Check serialization/deserialization of report objects containing chained exceptions (#5786)"""
280 pytester.makepyfile(
281 f"""
282 def foo():
283 raise ValueError('value error')
284 def test_a():
285 try:
286 foo()
287 except ValueError as e:
288 raise RuntimeError('runtime error') from e
289 if {report_class is CollectReport}:
290 test_a()
291 """
292 )
293
294 reprec = pytester.inline_run()
295 if report_class is TestReport:
296 reports: Sequence[TestReport] | Sequence[CollectReport] = reprec.getreports(
297 "pytest_runtest_logreport"
298 )
299 # we have 3 reports: setup/call/teardown
300 assert len(reports) == 3
301 # get the call report
302 report = reports[1]
303 else:
304 assert report_class is CollectReport
305 # three collection reports: session, test file, directory
306 reports = reprec.getreports("pytest_collectreport")
307 assert len(reports) == 3
308 report = reports[1]
309
310 def check_longrepr(longrepr: ExceptionChainRepr) -> None:
311 """Check the attributes of the given longrepr object according to the test file.
312
313 We can get away with testing both CollectReport and TestReport with this function because
314 the longrepr objects are very similar.
315 """
316 assert isinstance(longrepr, ExceptionChainRepr)
317 assert longrepr.sections == [("title", "contents", "=")]
318 assert len(longrepr.chain) == 2
319 entry1, entry2 = longrepr.chain
320 tb1, _fileloc1, desc1 = entry1
321 tb2, _fileloc2, desc2 = entry2
322
323 assert "ValueError('value error')" in str(tb1)
324 assert "RuntimeError('runtime error')" in str(tb2)
325
326 assert (
327 desc1
328 == "The above exception was the direct cause of the following exception:"
329 )
330 assert desc2 is None
331
332 assert report.failed
333 assert len(report.sections) == 0
334 assert isinstance(report.longrepr, ExceptionChainRepr)
335 report.longrepr.addsection("title", "contents", "=")
336 check_longrepr(report.longrepr)
337
338 data = report._to_json()
339 loaded_report = report_class._from_json(data)
340
341 assert loaded_report.failed
342 check_longrepr(loaded_report.longrepr)
343
344 # make sure we don't blow up on ``toterminal`` call; we don't test the actual output because it is very
345 # brittle and hard to maintain, but we can assume it is correct because ``toterminal`` is already tested
346 # elsewhere and we do check the contents of the longrepr object after loading it.
347 loaded_report.longrepr.toterminal(tw_mock)
348
349 def test_chained_exceptions_no_reprcrash(self, pytester: Pytester, tw_mock) -> None:
350 """Regression test for tracebacks without a reprcrash (#5971)
351
352 This happens notably on exceptions raised by multiprocess.pool: the exception transfer
353 from subprocess to main process creates an artificial exception, which ExceptionInfo
354 can't obtain the ReprFileLocation from.
355 """
356 pytester.makepyfile(
357 """
358 from concurrent.futures import ProcessPoolExecutor
359
360 def func():
361 raise ValueError('value error')
362
363 def test_a():
364 with ProcessPoolExecutor() as p:
365 p.submit(func).result()
366 """
367 )
368
369 pytester.syspathinsert()
370 reprec = pytester.inline_run()
371
372 reports = reprec.getreports("pytest_runtest_logreport")
373
374 def check_longrepr(longrepr: object) -> None:
375 assert isinstance(longrepr, ExceptionChainRepr)
376 assert len(longrepr.chain) == 2
377 entry1, entry2 = longrepr.chain
378 tb1, fileloc1, _desc1 = entry1
379 tb2, fileloc2, _desc2 = entry2
380
381 assert "RemoteTraceback" in str(tb1)
382 assert "ValueError: value error" in str(tb2)
383
384 assert fileloc1 is None
385 assert fileloc2 is not None
386 assert fileloc2.message == "ValueError: value error"
387
388 # 3 reports: setup/call/teardown: get the call report
389 assert len(reports) == 3
390 report = reports[1]
391
392 assert report.failed
393 check_longrepr(report.longrepr)
394
395 data = report._to_json()
396 loaded_report = TestReport._from_json(data)
397
398 assert loaded_report.failed
399 check_longrepr(loaded_report.longrepr)
400
401 # for same reasons as previous test, ensure we don't blow up here
402 assert loaded_report.longrepr is not None
403 assert isinstance(loaded_report.longrepr, ExceptionChainRepr)
404 loaded_report.longrepr.toterminal(tw_mock)
405
406 def test_report_prevent_ConftestImportFailure_hiding_exception(
407 self, pytester: Pytester
408 ) -> None:
409 sub_dir = pytester.path.joinpath("ns")
410 sub_dir.mkdir()
411 sub_dir.joinpath("conftest.py").write_text("import unknown", encoding="utf-8")
412
413 result = pytester.runpytest_subprocess(".")
414 result.stdout.fnmatch_lines(["E *Error: No module named 'unknown'"])
415 result.stdout.no_fnmatch_line("ERROR - *ConftestImportFailure*")
416
417 def test_report_timestamps_match_duration(self, pytester: Pytester, mock_timing):
418 reprec = pytester.inline_runsource(
419 """
420 import pytest
421 from _pytest import timing
422 @pytest.fixture
423 def fixture_():
424 timing.sleep(5)
425 yield
426 timing.sleep(5)
427 def test_1(fixture_): timing.sleep(10)
428 """
429 )
430 reports = reprec.getreports("pytest_runtest_logreport")
431 assert len(reports) == 3
432 for report in reports:
433 data = report._to_json()
434 loaded_report = TestReport._from_json(data)
435 assert loaded_report.stop - loaded_report.start == approx(report.duration)
436
437 @pytest.mark.parametrize(
438 "first_skip_reason, second_skip_reason, skip_reason_output",
439 [("A", "B", "(A; B)"), ("A", "A", "(A)")],
440 )
441 def test_exception_group_with_only_skips(
442 self,
443 pytester: Pytester,
444 first_skip_reason: str,
445 second_skip_reason: str,
446 skip_reason_output: str,
447 ):
448 """
449 Test that when an ExceptionGroup with only Skipped exceptions is raised in teardown,
450 it is reported as a single skipped test, not as an error.
451 This is a regression test for issue #13537.
452 """
453 pytester.makepyfile(
454 test_it=f"""
455 import pytest
456 @pytest.fixture
457 def fixA():
458 yield
459 pytest.skip(reason="{first_skip_reason}")
460 @pytest.fixture
461 def fixB():
462 yield
463 pytest.skip(reason="{second_skip_reason}")
464 def test_skip(fixA, fixB):
465 assert True
466 """
467 )
468 result = pytester.runpytest("-v")
469 result.assert_outcomes(passed=1, skipped=1)
470 out = result.stdout.str()
471 assert skip_reason_output in out
472 assert "ERROR at teardown" not in out
473
474 @pytest.mark.parametrize(
475 "use_item_location, skip_file_location",
476 [(True, "test_it.py"), (False, "runner.py")],
477 )
478 def test_exception_group_skips_use_item_location(
479 self, pytester: Pytester, use_item_location: bool, skip_file_location: str
480 ):
481 """
482 Regression for #13537:
483 If any skip inside an ExceptionGroup has _use_item_location=True,
484 the report location should point to the test item, not the fixture teardown.
485 """
486 pytester.makepyfile(
487 test_it=f"""
488 import pytest
489 @pytest.fixture
490 def fix_item1():
491 yield
492 exc = pytest.skip.Exception("A")
493 exc._use_item_location = True
494 raise exc
495 @pytest.fixture
496 def fix_item2():
497 yield
498 exc = pytest.skip.Exception("B")
499 exc._use_item_location = {use_item_location}
500 raise exc
501 def test_both(fix_item1, fix_item2):
502 assert True
503 """
504 )
505 result = pytester.runpytest("-rs")
506 result.assert_outcomes(passed=1, skipped=1)
507
508 out = result.stdout.str()
509 # Both reasons should appear
510 assert "A" and "B" in out
511 # Crucially, the skip should be attributed to the test item, not teardown
512 assert skip_file_location in out
513
514
515 class TestHooks:
516 """Test that the hooks are working correctly for plugins"""
517
518 def test_test_report(self, pytester: Pytester, pytestconfig: Config) -> None:
519 pytester.makepyfile(
520 """
521 def test_a(): assert False
522 def test_b(): pass
523 """
524 )
525 reprec = pytester.inline_run()
526 reports = reprec.getreports("pytest_runtest_logreport")
527 assert len(reports) == 6
528 for rep in reports:
529 data = pytestconfig.hook.pytest_report_to_serializable(
530 config=pytestconfig, report=rep
531 )
532 assert data["$report_type"] == "TestReport"
533 new_rep = pytestconfig.hook.pytest_report_from_serializable(
534 config=pytestconfig, data=data
535 )
536 assert new_rep.nodeid == rep.nodeid
537 assert new_rep.when == rep.when
538 assert new_rep.outcome == rep.outcome
539
540 def test_collect_report(self, pytester: Pytester, pytestconfig: Config) -> None:
541 pytester.makepyfile(
542 """
543 def test_a(): assert False
544 def test_b(): pass
545 """
546 )
547 reprec = pytester.inline_run()
548 reports = reprec.getreports("pytest_collectreport")
549 assert len(reports) == 3
550 for rep in reports:
551 data = pytestconfig.hook.pytest_report_to_serializable(
552 config=pytestconfig, report=rep
553 )
554 assert data["$report_type"] == "CollectReport"
555 new_rep = pytestconfig.hook.pytest_report_from_serializable(
556 config=pytestconfig, data=data
557 )
558 assert new_rep.nodeid == rep.nodeid
559 assert new_rep.when == "collect"
560 assert new_rep.outcome == rep.outcome
561
562 @pytest.mark.parametrize(
563 "hook_name", ["pytest_runtest_logreport", "pytest_collectreport"]
564 )
565 def test_invalid_report_types(
566 self, pytester: Pytester, pytestconfig: Config, hook_name: str
567 ) -> None:
568 pytester.makepyfile(
569 """
570 def test_a(): pass
571 """
572 )
573 reprec = pytester.inline_run()
574 reports = reprec.getreports(hook_name)
575 assert reports
576 rep = reports[0]
577 data = pytestconfig.hook.pytest_report_to_serializable(
578 config=pytestconfig, report=rep
579 )
580 data["$report_type"] = "Unknown"
581 with pytest.raises(AssertionError):
582 _ = pytestconfig.hook.pytest_report_from_serializable(
583 config=pytestconfig, data=data
584 )