How to capture print statements inside pytest hooks

Viewed 589

I am new to pytest frame work and trying to understand pytest hooks. I have placed some print statements in pytest hooks but not sure about how i can print the statement on console. Here is the example that i tried

# content of conftest.py
import pytest
import sys

def pytest_load_initial_conftests(args):
  print ("Hello")
  if 'xdist' in sys.modules:  # pytest-xdist plugin
    import multiprocessing

    num = max(multiprocessing.cpu_count() / 2, 1)
    args[:] = ["-n", str(num)] + args
    print ("args: ", args)

# content of the test_sample.py
def test_answer():
  # assert 0
  print ("test function")
  pass

I have tried using pytest test_sample.py -s, pytest --capture=sys/fd/no. I could only obtain print statement on console from the test_answer function but not from the pytest hook.

Thanks

1 Answers

Referring to the documentation of the pytest_load_initial_conftests hook,

Note:

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

So placing it into conftest.py has no effect. You need to invoke the hook via pytest plugin system. Either move the hook impl to a separate package, as advised in the docs:

# myplugin.py

def pytest_load_initial_conftests(args):
    ...

# setup.py
from setuptools import setup

setup(
    name='myplugin',
    py_modules=['myplugin'],
    entry_points={'pytest11': ['myplugin = myplugin']}
)

and install it as usual via pip install/python setup.py install.

Or keep myplugin.py with the rest of the code and pass the custom plugin via -p arg:

$ pytest -p myplugin

You may need to update PYTHONPATH for myplugin.py to become importable. The custom plugin arg may be moved to pytest.ini to ease the invocation:

[pytest]
addopts = -p myplugin
Related