使用
capfd固定装置。
例:
def test_foo(capfd): foo() # Writes "Hello World!" to stdout out, err = capfd.readouterr() assert out == "Hello World!"
有关更多详细信息,请参见:http :
//pytest.org/en/latest/fixture.html
并请参见:
py.test --fixtures有关内置灯具的列表。
您的示例存在一些问题。这是更正的版本:
def f(name): print "hello {}".format(name)def test_f(capfd): f("Tom") out, err = capfd.readouterr() assert out == "hello Tomn"注意:
- 请勿使用
sys.stdout
-capfd
照原样使用pytest提供的灯具。 - 使用以下命令运行测试:
py.test foo.py
测试运行输出:
$ py.test foo.py====================================================================== test session starts ======================================================================platform linux2 -- Python 2.7.5 -- pytest-2.4.2plugins: flakes, cache, pep8, covcollected 1 itemsfoo.py .=================================================================== 1 passed in 0.01 seconds ====================================================================
另请注意:
- 您不需要在测试模块中运行 测试功能 。
py.test
( CLI工具和Test Runner )可以为您完成此任务。
py.test主要做三件事:
- 收集测试
- 运行测试
- 显示统计信息和可能的错误
默认情况下
py.test,在测试模块中查找(可 配置iirc )
test_foo.py测试模块和
test_foo()测试功能。



