【发布时间】:2018-05-09 08:24:22
【问题描述】:
如何使用 Pytest 对内置 input 和 print 函数进行修补,以便在重构之前捕获其他人代码的输出并使用 pytest 对其进行测试?
例如,我获取了一些类似这样的代码:
class QueryProcessor:
def __init__(self ...):
...
def write_search_result(self, was_found):
print('yes' if was_found else 'no')
def read_query(self):
return Query(input().split())
我不想从stdin 读取几十个输入参数,也不想print 输出。我想使用我编写的函数来筛选充满mytest.in 和mytest.out 文件的目录,并使用@pytest.mark.parametrize(...) 将输入传递给pytest。
但我不知道如何修补此类中尴尬的 read… 和 write… 函数。
我怀疑是这样的:
@yptest.mark.parametrize("inputs…, expected outputs…", data_reading_func())
def test_QueryProcessor(monkeypatch, inputs…, expected outputs…):
"""Docstring
"""
q = QueryProcessor()
def my_replacement_read():
...
return [...]
def my_replacement_write():
...
return [...]
monkeypatch.???
assert ...
你能帮忙吗?
非常感谢
【问题讨论】:
标签: python mocking pytest monkeypatching