Search code examples
pythonpytestpython-unittest

pytest_sessionstart/finish won't print


This is driving me nuts. I'm following a basic example posted in multiple locations, and it's just not printing to the console, and I don't know what else I can tweak in the interface to make it work.

import unittest, pytest

print("module")

def pytest_sessionstart(session):
  print("before")

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
  outcome = yield
  result = outcome.get_result()
  if result.when == 'call':
    item.session.results[item] = result

def pytest_sessionfinish(session, exitstatus):
  print("after")

class TestFoo(unittest.TestCase):
  def test_foo(self):
    pass

Then:

#> pytest tests/test.py -s
======================================================== test session starts =========================================================
platform darwin -- Python 3.7.3, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: /Users/sean
collecting ... module
collected 1 item                                                                                                                     

tests/test.py .

========================================================= 1 passed in 0.01s ==========================================================

So... dude, where's my output? I got "module" that I printed, but not "before" or "after". I'm sure I'm missing something basic.


Solution

  • pytest_sessionstart and pytest_sessionfinish are initialization hooks, called for plugins and conftest.py files.

    Move their definitions into a conftest.py file next to test.py.