Why is pytest_runtest_call not executing as expected in my tests?

I’ve been struggling to get the pytest_runtest_call method working correctly in my test suite. I’m working on a project using Pytest 6.2.4 on Ubuntu 20.04. The goal was to customize how tests are run by injecting some additional functionality. I tried implementing it in a custom plugin, but my hooks don’t seem to trigger at all. Instead, I get the error ‘Hook implementation not found’ when I run pytest. I expected to see my print statements in the console output, indicating the hook was executed. What might be causing this behavior, and how can I ensure pytest_runtest_call executes as intended?

You know, I ran into this issue a few times while customizing hooks in my Pytest projects. It’s often because the hook implementation isn’t registered correctly.

The pytest_runtest_call hook is part of the plugin system in Pytest. When you define a function to override it, you need to ensure it’s correctly identifying it as a hook. One common mistake is not using the @pytest.hookimpl decorator, which is essential for making Pytest recognize your function as a hook implementation.

Here is the snippet that worked for me: python import pytest

@pytest.hookimpl(hookwrapper=True) def pytest_runtest_call(item): outcome = yield result = outcome.get_result() print(f"Result of {item.nodeid} is {result}")

This code utilizes the hookwrapper argument to control the execution flow around the standard call. The yield allows you to manipulate the result post-test execution, offering a way to insert additional logic.

A common issue is forgetting the hookwrapper=True part, which is crucial for wrapping the standard logic. This small oversight often leaves people wondering why their hook isn’t called at all.

I had a similar problem recently, and initially tried the common solutions but they didn’t quite fit my scenario. In my situation, the issue was with the placement of the hook implementation.

When working with pytest hooks like pytest_runtest_call, it’s important to ensure your custom plugin is discoverable by Pytest. This means placing the module in a location that Pytest will scan for plugins or using setuptools entry points if you’re packaging the plugin.

Try this setup: python

conftest.py

import pytest

@pytest.hookimpl(hookwrapper=True) def pytest_runtest_call(item): # Custom logic here, for instance: print(f"Executing test: {item.name}“) yield print(f"Completed test: {item.name}”)

Ensure that this setup either goes into a plugin file in your tests directory or inside the conftest.py file. Pytest automatically looks for conftest.py files, making it an ideal place.

If you’re still facing issues, double-check your test discovery paths or naming conventions, as Pytest might skip files it’s not configured to include.