我正在尝试为我的打印功能编写测试功能。但是我有问题。如果我做对了,您能帮我吗?我在做什么错?我正在使用捕获标准输出语句进行测试。
def func(name):
print('')
print(' %s' % name)
print('You have finished your test.')
@pytest.mark.parametrize('name, expected_out',
[('', ''),
('something', 'something'),
('You have finished your test.', 'You have finished your test.')])
def test_func(capsys, name, expected_out):
func('name')# I don't sure that here I need to pass an argument
out, _ = capsys.readoutter()
assert out == expected_out
根据您应该将I / O尽可能推到程序的“边缘”的理论,我将func
重新编写为类似的内容
def func(name, f=sys.stdout):
print('', file=f)
print(' %s' % fname, file=f)
print('You have finished your test.', file=f)
然后您的测试仅传递了一个类似文件的对象,事实发生后您可以检查该对象。
def test_func():
o = io.StringIO()
func("bob", o)
assert x.getvalue() == '\n bob\nYou have finished your test.\n')