1"""Hook specifications for pytest plugins which are invoked by pytest itself

2 and by builtin plugins."""

3 from pathlib import Path

4 from typing import Any

5 from typing import Dict

6 from typing import List

7 from typing import Mapping

8 from typing import Optional

9 from typing import Sequence

10 from typing import Tuple

11 from typing import TYPE_CHECKING

12 from typing import Union

13

14 from pluggy import HookspecMarker

15

16 from _pytest.deprecated import WARNING_CMDLINE_PREPARSE_HOOK

17

18 if TYPE_CHECKING:

19 import pdb

20 import warnings

21 from typing_extensions import Literal

22

23 from _pytest._code.code import ExceptionRepr

24 from _pytest.code import ExceptionInfo

25 from _pytest.config import Config

26 from _pytest.config import ExitCode

27 from _pytest.config import PytestPluginManager

28 from _pytest.config import _PluggyPlugin

29 from _pytest.config.argparsing import Parser

30 from _pytest.fixtures import FixtureDef

31 from _pytest.fixtures import SubRequest

32 from _pytest.main import Session

33 from _pytest.nodes import Collector

34 from _pytest.nodes import Item

35 from _pytest.outcomes import Exit

36 from _pytest.python import Class

37 from _pytest.python import Function

38 from _pytest.python import Metafunc

39 from _pytest.python import Module

40 from _pytest.reports import CollectReport

41 from _pytest.reports import TestReport

42 from _pytest.runner import CallInfo

43 from _pytest.terminal import TerminalReporter

44 from _pytest.compat import LEGACY_PATH

45

46

47 hookspec = HookspecMarker("pytest")

48

49# -------------------------------------------------------------------------

50# Initialization hooks called for every plugin

51# -------------------------------------------------------------------------

52

53

54@hookspec(historic=True)

55 def pytest_addhooks(pluginmanager: "PytestPluginManager") -> None:

56 """Called at plugin registration time to allow adding new hooks via a call to

57 ``pluginmanager.add_hookspecs(module_or_class, prefix)``.

58

59 :param pytest.PytestPluginManager pluginmanager: The pytest plugin manager.

60

61 .. note::

62 This hook is incompatible with ``hookwrapper=True``.

63 """

64

65

66@hookspec(historic=True)

67 def pytest_plugin_registered(

68 plugin: "_PluggyPlugin", manager: "PytestPluginManager"

69) -> None:

70 """A new pytest plugin got registered.

71

72 :param plugin: The plugin module or instance.

73 :param pytest.PytestPluginManager manager: pytest plugin manager.

74

75 .. note::

76 This hook is incompatible with ``hookwrapper=True``.

77 """

78

79

80@hookspec(historic=True)

81 def pytest_addoption(parser: "Parser", pluginmanager: "PytestPluginManager") -> None:

82 """Register argparse-style options and ini-style config values,

83 called once at the beginning of a test run.

84

85 .. note::

86

87 This function should be implemented only in plugins or ``conftest.py``

88 files situated at the tests root directory due to how pytest

89 :ref:`discovers plugins during startup <pluginorder>`.

90

91 :param pytest.Parser parser:

92 To add command line options, call

93 :py:func:`parser.addoption(...) <pytest.Parser.addoption>`.

94 To add ini-file values call :py:func:`parser.addini(...)

95 <pytest.Parser.addini>`.

96

97 :param pytest.PytestPluginManager pluginmanager:

98 The pytest plugin manager, which can be used to install :py:func:`hookspec`'s

99 or :py:func:`hookimpl`'s and allow one plugin to call another plugin's hooks

100 to change how command line options are added.

101

102 Options can later be accessed through the

103 :py:class:`config <pytest.Config>` object, respectively:

104

105 - :py:func:`config.getoption(name) <pytest.Config.getoption>` to

106 retrieve the value of a command line option.

107

108 - :py:func:`config.getini(name) <pytest.Config.getini>` to retrieve

109 a value read from an ini-style file.

110

111 The config object is passed around on many internal objects via the ``.config``

112 attribute or can be retrieved as the ``pytestconfig`` fixture.

113

114 .. note::

115 This hook is incompatible with ``hookwrapper=True``.

116 """

117

118

119@hookspec(historic=True)

120 def pytest_configure(config: "Config") -> None:

121 """Allow plugins and conftest files to perform initial configuration.

122

123 This hook is called for every plugin and initial conftest file

124 after command line options have been parsed.

125

126 After that, the hook is called for other conftest files as they are

127 imported.

128

129 .. note::

130 This hook is incompatible with ``hookwrapper=True``.

131

132 :param pytest.Config config: The pytest config object.

133 """

134

135

136# -------------------------------------------------------------------------

137# Bootstrapping hooks called for plugins registered early enough:

138# internal and 3rd party plugins.

139# -------------------------------------------------------------------------

140

141

142@hookspec(firstresult=True)

143 def pytest_cmdline_parse(

144 pluginmanager: "PytestPluginManager", args: List[str]

145) -> Optional["Config"]:

146 """Return an initialized :class:`~pytest.Config`, parsing the specified args.

147

148 Stops at first non-None result, see :ref:`firstresult`.

149

150 .. note::

151 This hook will only be called for plugin classes passed to the

152 ``plugins`` arg when using `pytest.main`_ to perform an in-process

153 test run.

154

155 :param pluginmanager: The pytest plugin manager.

156 :param args: List of arguments passed on the command line.

157 :returns: A pytest config object.

158 """

159

160

161@hookspec(warn_on_impl=WARNING_CMDLINE_PREPARSE_HOOK)

162 def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:

163 """(**Deprecated**) modify command line arguments before option parsing.

164

165 This hook is considered deprecated and will be removed in a future pytest version. Consider

166 using :hook:`pytest_load_initial_conftests` instead.

167

168 .. note::

169 This hook will not be called for ``conftest.py`` files, only for setuptools plugins.

170

171 :param config: The pytest config object.

172 :param args: Arguments passed on the command line.

173 """

174

175

176@hookspec(firstresult=True)

177 def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:

178 """Called for performing the main command line action. The default

179 implementation will invoke the configure hooks and runtest_mainloop.

180

181 Stops at first non-None result, see :ref:`firstresult`.

182

183 :param config: The pytest config object.

184 :returns: The exit code.

185 """

186

187

188 def pytest_load_initial_conftests(

189 early_config: "Config", parser: "Parser", args: List[str]

190) -> None:

191 """Called to implement the loading of initial conftest files ahead

192 of command line option parsing.

193

194 .. note::

195 This hook will not be called for ``conftest.py`` files, only for setuptools plugins.

196

197 :param early_config: The pytest config object.

198 :param args: Arguments passed on the command line.

199 :param parser: To add command line options.

200 """

201

202

203# -------------------------------------------------------------------------

204# collection hooks

205# -------------------------------------------------------------------------

206

207

208@hookspec(firstresult=True)

209 def pytest_collection(session: "Session") -> Optional[object]:

210 """Perform the collection phase for the given session.

211

212 Stops at first non-None result, see :ref:`firstresult`.

213 The return value is not used, but only stops further processing.

214

215 The default collection phase is this (see individual hooks for full details):

216

217 1. Starting from ``session`` as the initial collector:

218

219 1. ``pytest_collectstart(collector)``

220 2. ``report = pytest_make_collect_report(collector)``

221 3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred

222 4. For each collected node:

223

224 1. If an item, ``pytest_itemcollected(item)``

225 2. If a collector, recurse into it.

226

227 5. ``pytest_collectreport(report)``

228

229 2. ``pytest_collection_modifyitems(session, config, items)``

230

231 1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times)

232

233 3. ``pytest_collection_finish(session)``

234 4. Set ``session.items`` to the list of collected items

235 5. Set ``session.testscollected`` to the number of collected items

236

237 You can implement this hook to only perform some action before collection,

238 for example the terminal plugin uses it to start displaying the collection

239 counter (and returns `None`).

240

241 :param session: The pytest session object.

242 """

243

244

245 def pytest_collection_modifyitems(

246 session: "Session", config: "Config", items: List["Item"]

247) -> None:

248 """Called after collection has been performed. May filter or re-order

249 the items in-place.

250

251 :param session: The pytest session object.

252 :param config: The pytest config object.

253 :param items: List of item objects.

254 """

255

256

257 def pytest_collection_finish(session: "Session") -> None:

258 """Called after collection has been performed and modified.

259

260 :param session: The pytest session object.

261 """

262

263

264@hookspec(firstresult=True)

265 def pytest_ignore_collect(

266 collection_path: Path, path: "LEGACY_PATH", config: "Config"

267) -> Optional[bool]:

268 """Return True to prevent considering this path for collection.

269

270 This hook is consulted for all files and directories prior to calling

271 more specific hooks.

272

273 Stops at first non-None result, see :ref:`firstresult`.

274

275 :param collection_path: The path to analyze.

276 :param path: The path to analyze (deprecated).

277 :param config: The pytest config object.

278

279 .. versionchanged:: 7.0.0

280 The ``collection_path`` parameter was added as a :class:`pathlib.Path`

281 equivalent of the ``path`` parameter. The ``path`` parameter

282 has been deprecated.

283 """

284

285

286 def pytest_collect_file(

287 file_path: Path, path: "LEGACY_PATH", parent: "Collector"

288) -> "Optional[Collector]":

289 """Create a :class:`~pytest.Collector` for the given path, or None if not relevant.

290

291 The new node needs to have the specified ``parent`` as a parent.

292

293 :param file_path: The path to analyze.

294 :param path: The path to collect (deprecated).

295

296 .. versionchanged:: 7.0.0

297 The ``file_path`` parameter was added as a :class:`pathlib.Path`

298 equivalent of the ``path`` parameter. The ``path`` parameter

299 has been deprecated.

300 """

301

302

303# logging hooks for collection

304

305

306 def pytest_collectstart(collector: "Collector") -> None:

307 """Collector starts collecting.

308

309 :param collector:

310 The collector.

311 """

312

313

314 def pytest_itemcollected(item: "Item") -> None:

315 """We just collected a test item.

316

317 :param item:

318 The item.

319 """

320

321

322 def pytest_collectreport(report: "CollectReport") -> None:

323 """Collector finished collecting.

324

325 :param report:

326 The collect report.

327 """

328

329

330 def pytest_deselected(items: Sequence["Item"]) -> None:

331 """Called for deselected test items, e.g. by keyword.

332

333 May be called multiple times.

334

335 :param items:

336 The items.

337 """

338

339

340@hookspec(firstresult=True)

341 def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectReport]":

342 """Perform :func:`collector.collect() <pytest.Collector.collect>` and return

343 a :class:`~pytest.CollectReport`.

344

345 Stops at first non-None result, see :ref:`firstresult`.

346

347 :param collector:

348 The collector.

349 """

350

351

352# -------------------------------------------------------------------------

353# Python test function related hooks

354# -------------------------------------------------------------------------

355

356

357@hookspec(firstresult=True)

358 def pytest_pycollect_makemodule(

359 module_path: Path, path: "LEGACY_PATH", parent

360) -> Optional["Module"]:

361 """Return a :class:`pytest.Module` collector or None for the given path.

362

363 This hook will be called for each matching test module path.

364 The :hook:`pytest_collect_file` hook needs to be used if you want to

365 create test modules for files that do not match as a test module.

366

367 Stops at first non-None result, see :ref:`firstresult`.

368

369 :param module_path: The path of the module to collect.

370 :param path: The path of the module to collect (deprecated).

371

372 .. versionchanged:: 7.0.0

373 The ``module_path`` parameter was added as a :class:`pathlib.Path`

374 equivalent of the ``path`` parameter.

375

376 The ``path`` parameter has been deprecated in favor of ``fspath``.

377 """

378

379

380@hookspec(firstresult=True)

381 def pytest_pycollect_makeitem(

382 collector: Union["Module", "Class"], name: str, obj: object

383) -> Union[None, "Item", "Collector", List[Union["Item", "Collector"]]]:

384 """Return a custom item/collector for a Python object in a module, or None.

385

386 Stops at first non-None result, see :ref:`firstresult`.

387

388 :param collector:

389 The module/class collector.

390 :param name:

391 The name of the object in the module/class.

392 :param obj:

393 The object.

394 :returns:

395 The created items/collectors.

396 """

397

398

399@hookspec(firstresult=True)

400 def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:

401 """Call underlying test function.

402

403 Stops at first non-None result, see :ref:`firstresult`.

404

405 :param pyfuncitem:

406 The function item.

407 """

408

409

410 def pytest_generate_tests(metafunc: "Metafunc") -> None:

411 """Generate (multiple) parametrized calls to a test function.

412

413 :param metafunc:

414 The :class:`~pytest.Metafunc` helper for the test function.

415 """

416

417

418@hookspec(firstresult=True)

419 def pytest_make_parametrize_id(

420 config: "Config", val: object, argname: str

421) -> Optional[str]:

422 """Return a user-friendly string representation of the given ``val``

423 that will be used by @pytest.mark.parametrize calls, or None if the hook

424 doesn't know about ``val``.

425

426 The parameter name is available as ``argname``, if required.

427

428 Stops at first non-None result, see :ref:`firstresult`.

429

430 :param config: The pytest config object.

431 :param val: The parametrized value.

432 :param str argname: The automatic parameter name produced by pytest.

433 """

434

435

436# -------------------------------------------------------------------------

437# runtest related hooks

438# -------------------------------------------------------------------------

439

440

441@hookspec(firstresult=True)

442 def pytest_runtestloop(session: "Session") -> Optional[object]:

443 """Perform the main runtest loop (after collection finished).

444

445 The default hook implementation performs the runtest protocol for all items

446 collected in the session (``session.items``), unless the collection failed

447 or the ``collectonly`` pytest option is set.

448

449 If at any point :py:func:`pytest.exit` is called, the loop is

450 terminated immediately.

451

452 If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the

453 loop is terminated after the runtest protocol for the current item is finished.

454

455 :param session: The pytest session object.

456

457 Stops at first non-None result, see :ref:`firstresult`.

458 The return value is not used, but only stops further processing.

459 """

460

461

462@hookspec(firstresult=True)

463 def pytest_runtest_protocol(

464 item: "Item", nextitem: "Optional[Item]"

465) -> Optional[object]:

466 """Perform the runtest protocol for a single test item.

467

468 The default runtest protocol is this (see individual hooks for full details):

469

470 - ``pytest_runtest_logstart(nodeid, location)``

471

472 - Setup phase:

473 - ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when="setup")``)

474 - ``report = pytest_runtest_makereport(item, call)``

475 - ``pytest_runtest_logreport(report)``

476 - ``pytest_exception_interact(call, report)`` if an interactive exception occurred

477

478 - Call phase, if the the setup passed and the ``setuponly`` pytest option is not set:

479 - ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when="call")``)

480 - ``report = pytest_runtest_makereport(item, call)``

481 - ``pytest_runtest_logreport(report)``

482 - ``pytest_exception_interact(call, report)`` if an interactive exception occurred

483

484 - Teardown phase:

485 - ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when="teardown")``)

486 - ``report = pytest_runtest_makereport(item, call)``

487 - ``pytest_runtest_logreport(report)``

488 - ``pytest_exception_interact(call, report)`` if an interactive exception occurred

489

490 - ``pytest_runtest_logfinish(nodeid, location)``

491

492 :param item: Test item for which the runtest protocol is performed.

493 :param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend).

494

495 Stops at first non-None result, see :ref:`firstresult`.

496 The return value is not used, but only stops further processing.

497 """

498

499

500 def pytest_runtest_logstart(

501 nodeid: str, location: Tuple[str, Optional[int], str]

502) -> None:

503 """Called at the start of running the runtest protocol for a single item.

504

505 See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.

506

507 :param nodeid: Full node ID of the item.

508 :param location: A tuple of ``(filename, lineno, testname)``.

509 """

510

511

512 def pytest_runtest_logfinish(

513 nodeid: str, location: Tuple[str, Optional[int], str]

514) -> None:

515 """Called at the end of running the runtest protocol for a single item.

516

517 See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.

518

519 :param nodeid: Full node ID of the item.

520 :param location: A tuple of ``(filename, lineno, testname)``.

521 """

522

523

524 def pytest_runtest_setup(item: "Item") -> None:

525 """Called to perform the setup phase for a test item.

526

527 The default implementation runs ``setup()`` on ``item`` and all of its

528 parents (which haven't been setup yet). This includes obtaining the

529 values of fixtures required by the item (which haven't been obtained

530 yet).

531

532 :param item:

533 The item.

534 """

535

536

537 def pytest_runtest_call(item: "Item") -> None:

538 """Called to run the test for test item (the call phase).

539

540 The default implementation calls ``item.runtest()``.

541

542 :param item:

543 The item.

544 """

545

546

547 def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:

548 """Called to perform the teardown phase for a test item.

549

550 The default implementation runs the finalizers and calls ``teardown()``

551 on ``item`` and all of its parents (which need to be torn down). This

552 includes running the teardown phase of fixtures required by the item (if

553 they go out of scope).

554

555 :param item:

556 The item.

557 :param nextitem:

558 The scheduled-to-be-next test item (None if no further test item is

559 scheduled). This argument is used to perform exact teardowns, i.e.

560 calling just enough finalizers so that nextitem only needs to call

561 setup functions.

562 """

563

564

565@hookspec(firstresult=True)

566 def pytest_runtest_makereport(

567 item: "Item", call: "CallInfo[None]"

568) -> Optional["TestReport"]:

569 """Called to create a :class:`~pytest.TestReport` for each of

570 the setup, call and teardown runtest phases of a test item.

571

572 See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.

573

574 :param item: The item.

575 :param call: The :class:`~pytest.CallInfo` for the phase.

576

577 Stops at first non-None result, see :ref:`firstresult`.

578 """

579

580

581 def pytest_runtest_logreport(report: "TestReport") -> None:

582 """Process the :class:`~pytest.TestReport` produced for each

583 of the setup, call and teardown runtest phases of an item.

584

585 See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.

586 """

587

588

589@hookspec(firstresult=True)

590 def pytest_report_to_serializable(

591 config: "Config",

592 report: Union["CollectReport", "TestReport"],

593) -> Optional[Dict[str, Any]]:

594 """Serialize the given report object into a data structure suitable for

595 sending over the wire, e.g. converted to JSON.

596

597 :param config: The pytest config object.

598 :param report: The report.

599 """

600

601

602@hookspec(firstresult=True)

603 def pytest_report_from_serializable(

604 config: "Config",

605 data: Dict[str, Any],

606) -> Optional[Union["CollectReport", "TestReport"]]:

607 """Restore a report object previously serialized with

608 :hook:`pytest_report_to_serializable`.

609

610 :param config: The pytest config object.

611 """

612

613

614# -------------------------------------------------------------------------

615# Fixture related hooks

616# -------------------------------------------------------------------------

617

618

619@hookspec(firstresult=True)

620 def pytest_fixture_setup(

621 fixturedef: "FixtureDef[Any]", request: "SubRequest"

622) -> Optional[object]:

623 """Perform fixture setup execution.

624

625 :param fixturdef:

626 The fixture definition object.

627 :param request:

628 The fixture request object.

629 :returns:

630 The return value of the call to the fixture function.

631

632 Stops at first non-None result, see :ref:`firstresult`.

633

634 .. note::

635 If the fixture function returns None, other implementations of

636 this hook function will continue to be called, according to the

637 behavior of the :ref:`firstresult` option.

638 """

639

640

641 def pytest_fixture_post_finalizer(

642 fixturedef: "FixtureDef[Any]", request: "SubRequest"

643) -> None:

644 """Called after fixture teardown, but before the cache is cleared, so

645 the fixture result ``fixturedef.cached_result`` is still available (not

646 ``None``).

647

648 :param fixturdef:

649 The fixture definition object.

650 :param request:

651 The fixture request object.

652 """

653

654

655# -------------------------------------------------------------------------

656# test session related hooks

657# -------------------------------------------------------------------------

658

659

660 def pytest_sessionstart(session: "Session") -> None:

661 """Called after the ``Session`` object has been created and before performing collection

662 and entering the run test loop.

663

664 :param session: The pytest session object.

665 """

666

667

668 def pytest_sessionfinish(

669 session: "Session",

670 exitstatus: Union[int, "ExitCode"],

671) -> None:

672 """Called after whole test run finished, right before returning the exit status to the system.

673

674 :param session: The pytest session object.

675 :param exitstatus: The status which pytest will return to the system.

676 """

677

678

679 def pytest_unconfigure(config: "Config") -> None:

680 """Called before test process is exited.

681

682 :param config: The pytest config object.

683 """

684

685

686# -------------------------------------------------------------------------

687# hooks for customizing the assert methods

688# -------------------------------------------------------------------------

689

690

691 def pytest_assertrepr_compare(

692 config: "Config", op: str, left: object, right: object

693) -> Optional[List[str]]:

694 """Return explanation for comparisons in failing assert expressions.

695

696 Return None for no custom explanation, otherwise return a list

697 of strings. The strings will be joined by newlines but any newlines

698 *in* a string will be escaped. Note that all but the first line will

699 be indented slightly, the intention is for the first line to be a summary.

700

701 :param config: The pytest config object.

702 :param op: The operator, e.g. `"=="`, `"!="`, `"not in"`.

703 :param left: The left operand.

704 :param right: The right operand.

705 """

706

707

708 def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> None:

709 """Called whenever an assertion passes.

710

711 .. versionadded:: 5.0

712

713 Use this hook to do some processing after a passing assertion.

714 The original assertion information is available in the `orig` string

715 and the pytest introspected assertion information is available in the

716 `expl` string.

717

718 This hook must be explicitly enabled by the ``enable_assertion_pass_hook``

719 ini-file option:

720

721 .. code-block:: ini

722

723 [pytest]

724 enable_assertion_pass_hook=true

725

726 You need to **clean the .pyc** files in your project directory and interpreter libraries

727 when enabling this option, as assertions will require to be re-written.

728

729 :param item: pytest item object of current test.

730 :param lineno: Line number of the assert statement.

731 :param orig: String with the original assertion.

732 :param expl: String with the assert explanation.

733 """

734

735

736# -------------------------------------------------------------------------

737# Hooks for influencing reporting (invoked from _pytest_terminal).

738# -------------------------------------------------------------------------

739

740

741 def pytest_report_header(

742 config: "Config", start_path: Path, startdir: "LEGACY_PATH"

743) -> Union[str, List[str]]:

744 """Return a string or list of strings to be displayed as header info for terminal reporting.

745

746 :param config: The pytest config object.

747 :param start_path: The starting dir.

748 :param startdir: The starting dir (deprecated).

749

750 .. note::

751

752 Lines returned by a plugin are displayed before those of plugins which

753 ran before it.

754 If you want to have your line(s) displayed first, use

755 :ref:`trylast=True <plugin-hookorder>`.

756

757 .. note::

758

759 This function should be implemented only in plugins or ``conftest.py``

760 files situated at the tests root directory due to how pytest

761 :ref:`discovers plugins during startup <pluginorder>`.

762

763 .. versionchanged:: 7.0.0

764 The ``start_path`` parameter was added as a :class:`pathlib.Path`

765 equivalent of the ``startdir`` parameter. The ``startdir`` parameter

766 has been deprecated.

767 """

768

769

770 def pytest_report_collectionfinish(

771 config: "Config",

772 start_path: Path,

773 startdir: "LEGACY_PATH",

774 items: Sequence["Item"],

775) -> Union[str, List[str]]:

776 """Return a string or list of strings to be displayed after collection

777 has finished successfully.

778

779 These strings will be displayed after the standard "collected X items" message.

780

781 .. versionadded:: 3.2

782

783 :param config: The pytest config object.

784 :param start_path: The starting dir.

785 :param startdir: The starting dir (deprecated).

786 :param items: List of pytest items that are going to be executed; this list should not be modified.

787

788 .. note::

789

790 Lines returned by a plugin are displayed before those of plugins which

791 ran before it.

792 If you want to have your line(s) displayed first, use

793 :ref:`trylast=True <plugin-hookorder>`.

794

795 .. versionchanged:: 7.0.0

796 The ``start_path`` parameter was added as a :class:`pathlib.Path`

797 equivalent of the ``startdir`` parameter. The ``startdir`` parameter

798 has been deprecated.

799 """

800

801

802@hookspec(firstresult=True)

803 def pytest_report_teststatus(

804 report: Union["CollectReport", "TestReport"], config: "Config"

805) -> Tuple[str, str, Union[str, Mapping[str, bool]]]:

806 """Return result-category, shortletter and verbose word for status

807 reporting.

808

809 The result-category is a category in which to count the result, for

810 example "passed", "skipped", "error" or the empty string.

811

812 The shortletter is shown as testing progresses, for example ".", "s",

813 "E" or the empty string.

814

815 The verbose word is shown as testing progresses in verbose mode, for

816 example "PASSED", "SKIPPED", "ERROR" or the empty string.

817

818 pytest may style these implicitly according to the report outcome.

819 To provide explicit styling, return a tuple for the verbose word,

820 for example ``"rerun", "R", ("RERUN", {"yellow": True})``.

821

822 :param report: The report object whose status is to be returned.

823 :param config: The pytest config object.

824 :returns: The test status.

825

826 Stops at first non-None result, see :ref:`firstresult`.

827 """

828

829

830 def pytest_terminal_summary(

831 terminalreporter: "TerminalReporter",

832 exitstatus: "ExitCode",

833 config: "Config",

834) -> None:

835 """Add a section to terminal summary reporting.

836

837 :param terminalreporter: The internal terminal reporter object.

838 :param exitstatus: The exit status that will be reported back to the OS.

839 :param config: The pytest config object.

840

841 .. versionadded:: 4.2

842 The ``config`` parameter.

843 """

844

845

846@hookspec(historic=True)

847 def pytest_warning_recorded(

848 warning_message: "warnings.WarningMessage",

849 when: "Literal['config', 'collect', 'runtest']",

850 nodeid: str,

851 location: Optional[Tuple[str, int, str]],

852) -> None:

853 """Process a warning captured by the internal pytest warnings plugin.

854

855 :param warning_message:

856 The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains

857 the same attributes as the parameters of :py:func:`warnings.showwarning`.

858

859 :param when:

860 Indicates when the warning was captured. Possible values:

861

862 * ``"config"``: during pytest configuration/initialization stage.

863 * ``"collect"``: during test collection.

864 * ``"runtest"``: during test execution.

865

866 :param nodeid:

867 Full id of the item.

868

869 :param location:

870 When available, holds information about the execution context of the captured

871 warning (filename, linenumber, function). ``function`` evaluates to <module>

872 when the execution context is at the module level.

873

874 .. versionadded:: 6.0

875 """

876

877

878# -------------------------------------------------------------------------

879# Hooks for influencing skipping

880# -------------------------------------------------------------------------

881

882

883 def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]:

884 """Called when constructing the globals dictionary used for

885 evaluating string conditions in xfail/skipif markers.

886

887 This is useful when the condition for a marker requires

888 objects that are expensive or impossible to obtain during

889 collection time, which is required by normal boolean

890 conditions.

891

892 .. versionadded:: 6.2

893

894 :param config: The pytest config object.

895 :returns: A dictionary of additional globals to add.

896 """

897

898

899# -------------------------------------------------------------------------

900# error handling and internal debugging hooks

901# -------------------------------------------------------------------------

902

903

904 def pytest_internalerror(

905 excrepr: "ExceptionRepr",

906 excinfo: "ExceptionInfo[BaseException]",

907) -> Optional[bool]:

908 """Called for internal errors.

909

910 Return True to suppress the fallback handling of printing an

911 INTERNALERROR message directly to sys.stderr.

912

913 :param excrepr: The exception repr object.

914 :param excinfo: The exception info.

915 """

916

917

918 def pytest_keyboard_interrupt(

919 excinfo: "ExceptionInfo[Union[KeyboardInterrupt, Exit]]",

920) -> None:

921 """Called for keyboard interrupt.

922

923 :param excinfo: The exception info.

924 """

925

926

927 def pytest_exception_interact(

928 node: Union["Item", "Collector"],

929 call: "CallInfo[Any]",

930 report: Union["CollectReport", "TestReport"],

931) -> None:

932 """Called when an exception was raised which can potentially be

933 interactively handled.

934

935 May be called during collection (see :hook:`pytest_make_collect_report`),

936 in which case ``report`` is a :class:`CollectReport`.

937

938 May be called during runtest of an item (see :hook:`pytest_runtest_protocol`),

939 in which case ``report`` is a :class:`TestReport`.

940

941 This hook is not called if the exception that was raised is an internal

942 exception like ``skip.Exception``.

943

944 :param node:

945 The item or collector.

946 :param call:

947 The call information. Contains the exception.

948 :param report:

949 The collection or test report.

950 """

951

952

953 def pytest_enter_pdb(config: "Config", pdb: "pdb.Pdb") -> None:

954 """Called upon pdb.set_trace().

955

956 Can be used by plugins to take special action just before the python

957 debugger enters interactive mode.

958

959 :param config: The pytest config object.

960 :param pdb: The Pdb instance.

961 """

962

963

964 def pytest_leave_pdb(config: "Config", pdb: "pdb.Pdb") -> None:

965 """Called when leaving pdb (e.g. with continue after pdb.set_trace()).

966

967 Can be used by plugins to take special action just after the python

968 debugger leaves interactive mode.

969

970 :param config: The pytest config object.

971 :param pdb: The Pdb instance.

972 """