如何在pytest中同时使用灯具和捕获stdout?

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

我怎么样这样的东西:

import pytest
@pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
])
def test_printed_out_value(test_input, expected, capsys): # <-- notice the third argument
    print test_input
    out, err = capsys.readouterr()
    assert out == expected

上面的代码失败是因为当我们使用参数化时不能使用全局夹具capsys。我的意思是我找不到在函数内部传递它的方法。有没有办法我没有看到我可以在哪里capture the output但仍然使用parametrize

python pytest
1个回答
1
投票

我并不完全确定我正确理解了您的问题,但以下代码片段有效(2个测试通过,1个失败):

import pytest

class __capsys_class__:
    def readouterr(self, in_str):
        return eval(in_str), None

@pytest.fixture(scope = 'module')
def capsys():
    return __capsys_class__()

@pytest.mark.parametrize('in_param', [
    ('3+5', 8),
    ('2+4', 6),
    ('6*9', 42),
    ])
def test_printed_out_value(capsys, in_param):
    test_input, expected = in_param
    print(test_input) # Python 3 print function!
    out, err = capsys.readouterr(test_input)
    assert out == expected

首先,我总是将灯具放在参数“列表”的开头。似乎以这种方式工作。其次,我只是将你的元组发送到测试中(in_param)并在测试中解压缩它们。

编辑:当测试失败时,捕获并显示stdout。对于上面的代码,它看起来像这样:

~> pytest 
========================================================== test session starts ===========================================================
platform linux -- Python 3.6.2, pytest-3.3.1, py-1.5.2, pluggy-0.6.0
rootdir: /home/ernst/Desktop/so/tests, inifile:
collected 3 items                                                                                                                        

test_demo.py ..F                                                                                                                   [100%]

================================================================ FAILURES ================================================================
___________________________________________________ test_printed_out_value[in_param2] ____________________________________________________

capsys = <test_demo.__capsys_class__ object at 0x7fd57e60c860>, in_param = ('6*9', 42)

    @pytest.mark.parametrize('in_param', [
        ('3+5', 8),
        ('2+4', 6),
        ('6*9', 42),
        ])
    def test_printed_out_value(capsys, in_param):
        test_input, expected = in_param
        print(test_input)
        out, err = capsys.readouterr(test_input)
>       assert out == expected
E    assert 54 == 42

test_demo.py:21: AssertionError
---------------------------------------------------------- Captured stdout call ----------------------------------------------------------
6*9
=================================================== 1 failed, 2 passed in 0.03 seconds ===================================================

检查倒数第二行的6*9。这是由测试中的打印功能打印的。

© www.soinside.com 2019 - 2024. All rights reserved.