如何在测试用例中伪造 sys.stdout.istty 而不与 pytest stdout 捕获发生冲突? [英] How can I fake sys.stdout.istty in a test case without conflicting with pytest stdout capturing?
问题描述
我需要在测试用例中伪造 sys.stdout.istty()
的返回值.使用 monkeypatch.setattr("sys.stdout.isatty", lambda: True)
进行 Monkeypatching 是没有选择的,因为它在使用选项 -s
时与 pytest stdout 捕获冲突.如何在测试用例级别进行伪造?
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?
推荐答案
Python 不允许对内置类型(如文件..sys.stdout
是一个文件对象. 必须在生产代码模块命名空间 (
) 中应用补丁.当使用 pytest-mock
(fixture mocker
) 时,它看起来如下:
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
这篇关于如何在测试用例中伪造 sys.stdout.istty 而不与 pytest stdout 捕获发生冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!