我如何拥有这样的东西:
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
以上代码失败,因为在我们使用参数化时无法使用全局夹具。我的意思是我无法找到一种方法将其传递给函数。我有没有看到我可以capture the output但仍然使用parametrize的位置?
答案 0 :(得分:1)
我不完全确定我是否正确理解了您的问题,但以下代码剪辑有效(2个测试通过,1个失败):
Python version 3.5.3
Tensorflow version 1.2.1
Keras version 2.0.4
首先,我总是把灯具放在参数'列表'的开头。似乎以这种方式工作。其次,我只是将你的元组发送到测试中(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 ===================================================
。这是由测试中的打印功能打印出来的。