gpt4 book ai didi

python - Pytest:模拟/猴子修补 python 中的内置 input() 和 print() 函数

转载 作者:行者123 更新时间:2023-12-04 16:45:32 26 4
gpt4 key购买 nike

我如何使用 Pytest 猴子修补内置的 inputprint 函数,以便捕获其他人代码的输出并使用 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 读取几十个输入参数,也不想打印 输出。我想使用我编写的函数筛选一个充满 mytest.inmytest.out 文件的目录,并将输入传递给 pytest 使用 @pytest.mark.parametrize(...)

但是我不知道如何修补这个类中笨拙的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 ...

你能帮忙吗?

非常感谢

最佳答案

在等待回复的过程中,我自己想到了以下内容。我认为理想的答案是我按照@hoefling 所建议的方式实现的——使用patch

@pytest.mark.parametrize("m, n, commands, expec", helpers.get_external_inputs_outputs('spampath', helpers.read_spam_input_output))
def test_QueryProcessor(monkeypatch, m, n, commands, expec):

def mock_process_queries(cls):
for cmd in commands:
cls.process_query(Query(cmd.split())) # also mocks read_query()

def mock_write_search_result(cls, was_found):
outputs.append('yes' if was_found else 'no')

monkeypatch.setattr('test.QueryProcessor.process_queries', mock_process_queries)
monkeypatch.setattr('test.QueryProcessor.write_search_result', mock_write_search_result)

outputs = []

proc = QueryProcessor(m)
proc.process_queries()

assert outputs == expec

更新:

@pytest.mark.parametrize("m, n, commands, expec",
helpers.get_external_inputs_outputs(
'spampath',
helpers.read_input_output))
def test_QueryProcessor_mockpatch(m, n, commands, expec):

commands.insert(0,n)

mock_stdout = io.StringIO()

with patch('spammodule.input', side_effect=commands):
with patch('sys.stdout', mock_stdout):
proc = hash_chains.QueryProcessor(m)
proc.process_queries()

assert mock_stdout.getvalue().split('\n')[:-1] == expec

关于python - Pytest:模拟/猴子修补 python 中的内置 input() 和 print() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com