Python - 如何对使用 Popen 的方法进行单元测试?
Python - How to unit-test this method that uses Popen?
我有一个看起来像这样的函数:
def run_shell_command_return_output(command_array):
output = []
p = Popen(command_array, stdout=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
output.append(line.decode('utf8').strip())
p.wait()
return output
我正在尝试弄清楚如何对使用此方法的代码进行单元测试,以便它实际上不会命中文件系统,而是使用伪造的 return 数据和状态代码。
我看过有关如何模拟使用 popen 和 communicate() 的代码的信息,例如 How to unit test a function that uses Popen?,但我一直无法弄清楚如何以这种方式使用 popen 模拟代码.
如何在此处伪造 popen 以便此方法可以 return 伪造输出?
首先,我会更简单地重写函数。特别是,with
语句是不必要的,因为您既不打开(也不负责关闭)p.stdout
.
def run_shell_command_return_output(command_array):
output = []
p = Popen(command_array, stdout=PIPE, bufsize=1)
for line in p.stdout:
output.append(line.decode('utf8').strip())
# I think the wait is redundant, since reads on p.stdout
# would block if p is still running.
p.wait()
return output
现在要进行测试,您只需模拟 Popen
并将 p.stdout
配置为具有所需数据的 file-like 对象。
with mock.patch('Popen') as mock_popen:
mock_popen.return_value.stdout = io.StringIO("data\ndata\ndata\n")
output = run_shell_command_return_output(["what", "ever"])
assert output == ["data", "data", "data"]
我有一个看起来像这样的函数:
def run_shell_command_return_output(command_array):
output = []
p = Popen(command_array, stdout=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
output.append(line.decode('utf8').strip())
p.wait()
return output
我正在尝试弄清楚如何对使用此方法的代码进行单元测试,以便它实际上不会命中文件系统,而是使用伪造的 return 数据和状态代码。
我看过有关如何模拟使用 popen 和 communicate() 的代码的信息,例如 How to unit test a function that uses Popen?,但我一直无法弄清楚如何以这种方式使用 popen 模拟代码.
如何在此处伪造 popen 以便此方法可以 return 伪造输出?
首先,我会更简单地重写函数。特别是,with
语句是不必要的,因为您既不打开(也不负责关闭)p.stdout
.
def run_shell_command_return_output(command_array):
output = []
p = Popen(command_array, stdout=PIPE, bufsize=1)
for line in p.stdout:
output.append(line.decode('utf8').strip())
# I think the wait is redundant, since reads on p.stdout
# would block if p is still running.
p.wait()
return output
现在要进行测试,您只需模拟 Popen
并将 p.stdout
配置为具有所需数据的 file-like 对象。
with mock.patch('Popen') as mock_popen:
mock_popen.return_value.stdout = io.StringIO("data\ndata\ndata\n")
output = run_shell_command_return_output(["what", "ever"])
assert output == ["data", "data", "data"]