Fundamentals 8 min read

Common pytest Hooks and Their Usage

This article introduces the most frequently used pytest hooks, categorizing them into guiding, initialization, test execution, collection, reporting, and debug hooks, and explains how to implement custom behavior in conftest.py or plugins for advanced test automation.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Common pytest Hooks and Their Usage

Guiding Hooks

Guiding hooks are only called when the plugin is installed via setuptools and include:

pytest_load_initial_conftests(early_config, parser, args) – called before command‑line argument parsing to load conftest files.

pytest_cmdline_parse(pluginmanager, args) – parses specified arguments and returns the first non‑None configuration object.

pytest_cmdline_main(config) – executes the command‑line instruction, invoking configuration hooks and the main test loop.

Initialization Hooks

Initialization hooks are invoked in plugins and conftest.py files:

pytest_addoption(parser) – registers argparse ‑style options and ini configuration values, accessible via config or the pytestconfig fixture.

pytest_addhooks(pluginmanager) – allows a plugin to add new hooks that other plugins can implement.

pytest_configure(config) – runs after command‑line parsing but before loading plugins and conftest files, for global initialization.

pytest_unconfigure(config) – called just before the test process exits.

pytest_sessionstart(session) – executed after the Session object is created and before test collection begins.

pytest_sessionfinish(session, exitstatus) – executed after all tests have run, before the final exit status is returned.

Test Execution Hooks

Hooks related to each test case’s lifecycle:

pytest_runtestloop(session) – starts the test case loop.

pytest_runtest_protocol(item, nextitem) – implements the setup/call/teardown protocol and reports.

pytest_runtest_logstart(nodeid, location) – called before a test’s setup.

pytest_runtest_logfinish(nodeid, location) – called after a test’s teardown.

pytest_runtest_setup(item) – runs before the test body.

pytest_runtest_call(item) – executes the test.

pytest_runtest_teardown(item, nextitem) – runs after the test body.

pytest_runtest_makereport(item, call) – creates a report for the current phase.

Collection Hooks

Hooks that control test discovery:

pytest_collection(session) – called before any collection starts.

pytest_ignore_collect(path, config) – return True to skip a path.

pytest_collect_directory(path, parent) – called before traversing a directory.

pytest_collect_file(path, parent) – returns a Node or None for a file.

pytest_pycollect_makeitem(collector, name, obj) – creates custom items for Python objects.

pytest_generate_tests(metafunc) – generates parametrized tests.

pytest_make_parametrize_id(config, val, argname) – creates custom IDs for parametrized cases.

pytest_collection_modifyitems(session, config, items) – can add, remove, or reorder collected items after collection.

Reporting Hooks

Hooks related to session‑level reporting:

pytest_collectstart(collector) – before collection begins.

pytest_itemcollected(item) – after a single item is collected.

pytest_collectreport(report) – after collection finishes.

pytest_deselected(items) – when items are deselected by keywords.

pytest_report_header(config, startdir) – defines the report header.

pytest_report_collectionfinish(config, startdir, items) – text shown after "collected X items".

pytest_report_teststatus(report) – sets test status, error messages, and status text.

pytest_terminal_summary(terminalreporter, exitstatus) – customizes the final summary line.

pytest_fixture_setup(fixturedef, request) – runs fixture setup and returns its value.

pytest_fixture_post_finalizer(fixturedef, request) – runs before fixture teardown and cache clearing.

pytest_runtest_logreport(report) – called after each phase (setup/call/teardown) for custom logging.

pytest_assertrepr_compare(config, op, left, right) – provides custom assertion failure explanations.

Debug/Interactive Hooks

Hooks for special reporting and exception interaction, used less frequently:

pytest_internalerror(excrepr, excinfo) – called on internal errors.

pytest_keyboard_interrupt(excinfo) – called on keyboard interrupt.

pytest_exception_interact(node, call, report) – called when an exception is raised.

pytest_enter_pdb(config) – called before entering the debugger.

Hook Lifecycle Diagram

Application Example

To collect test error information and store it in a database after the run, you can save errors to a global variable in pytest_runtest_logreport and then write them to the database in pytest_sessionfinish .

Conclusion

Through pytest’s powerful hook system, you can customize a wide range of functionality, and common extensions can be packaged as reusable plugins.

pythonautomationTestingHooksTest Frameworkpytest
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.