1

How can I make pytest fail if there is a print statement in the code?

Also (for security it can be useful), it will be great if the print does not actually get executed or shown in the CI.

alex_noname
  • 26,459
  • 5
  • 69
  • 86
Newskooler
  • 3,973
  • 7
  • 46
  • 84

1 Answers1

2

Try to use session scope autouse fixture for print monkey patching , like so:

@pytest.fixture(scope='session', autouse=True)
def mock_print():
    with mock.patch("builtins.print", side_effect=Exception('Print is not allowed!')) as _fixture:
        yield _fixture

Put this fixture in the conftest.py file, which is located in your test directory. We can define the fixture functions in this file to make them accessible across multiple test files. You can read more about this file here:

In pytest, what is the use of conftest.py files?

https://docs.pytest.org/en/2.7.3/fixture.html?highlight=conftest#sharing-a-fixture-across-tests-in-a-module-or-class-session

alex_noname
  • 26,459
  • 5
  • 69
  • 86