1

I need to fake the return value of sys.stdout.istty() in a test case. Monkeypatching with monkeypatch.setattr("sys.stdout.isatty", lambda: True) is no option because it conflicts with pytest stdout capturing when using option -s. How can I fake on the test case level?

thinwybk
  • 3,345
  • 27
  • 58

1 Answers1

1

Python does not allow monkey-patching built-in types such as file.. sys.stdout is a file object. The patch has to be applied in the production code module namespace (<module>.sys.stdout). When using pytest-mock (fixture mocker) this looks as follows:

def test_of_prod_code_with_dependency(mocker):
    stdout_mock = mocker.patch("<module>.sys.stdout")
    stdout_mock.isatty.return_value = istty

    # production code which depends on sys.stdout.isatty() comes here
thinwybk
  • 3,345
  • 27
  • 58