问题描述
我的代码使用打字机,
但我认为 Click 也是如此。
我无法正确修补命令内的 sys.stdout.isatty
调用。
如果我直接测试函数(i_fail
),我可以成功模拟,
但是当通过 Typer(可能是 Click 的)CliRunner
调用时,我无法修补 isatty
。
如果我尝试修补 "__main__.sys.stdout.isatty"
或 "sys.stdout.isatty"
,也会发生同样的情况。
我可以强制它工作的一种方法是从使用 import sys
和 sys.stdout.isatty
到 from sys import stdout
和 stdout.isatty
。
但我更想知道:
- 在哪里可以正确修补以使
sys.stdout.isatty
模拟按预期工作? - 这里出了什么问题?
我在下面设置了一个示例项目,其中包含失败和成功的测试。 我在测试套件中同时使用 pytest 和 pytest-mock。
.
├── src
│ └── package
│ ├── __init__.py
│ └── __main__.py
└── tests
└── test_main.py
"""__main__.py"""
import sys
from sys import stdout
import typer
app = typer.Typer()
@app.command()
def i_fail():
"""This fails when tested."""
print(sys.stdout.isatty())
@app.command()
def i_pass():
"""This passes when tested."""
print(stdout.isatty())
if __name__ == "__main__":
app()
"""test_main.py"""
from typer import testing
from package.__main__ import app
def test_i_fail(mocker):
"""This test fails."""
runner = testing.CliRunner()
mock = mocker.patch("package.__main__.sys.stdout.isatty")
mock.return_value = "successfully mocked"
assert runner.invoke(app,args=["i-fail"]).output == "successfully mocked"
def test_i_pass(mocker):
"""This test passes."""
runer = testing.CliRunner()
mock = mocker.patch("package.__main__.sys.stdout.isatty")
mock.return_value = "successfully mocked"
assert runner.invoke(app,args=["i-pass"]).output == "successfully mocked"
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)