如何在测试中检查我的打印语句?

问题描述 投票:0回答:1

我正在尝试为我的打印功能编写测试功能。但是我有问题。如果我做对了,您能帮我吗?我在做什么错?我正在使用捕获标准输出语句进行测试。

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

而且我所有的行都遇到这种错误。enter image description here

python testing pytest stdout
1个回答
0
投票

根据您应该将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')
© www.soinside.com 2019 - 2024. All rights reserved.