用例:在 pytest 中测试套件我有一个 @fixture如果缺少配置的命令行选项,则会引发异常。我已经使用 xfail 为这个 fixture 编写了一个测试。 :
import pytest
from <module> import <exception>
@pytest.mark.xfail(raises=<exception>)
def test_fixture_with_missing_options_raises_exception(rc_visard):
pass
然而,运行测试后的输出并未表明测试已通过,而是“xfailed”:
============================== 1 xfailed in 0.15 seconds ========================
除此之外,我无法测试 fixture为特定缺失的命令行选项引发异常。
有没有更好的方法来做到这一点?我可以模拟 pytest 吗?我不需要通过 pytest --<commandline-option-a> <test-file-name>::<test-name> 调用特定测试的命令行选项.
请您参考如下方法:
初始设置
假设您有一个简化的项目,conftest.py 包含以下代码:
import pytest
def pytest_addoption(parser):
parser.addoption('--foo', action='store', dest='foo', default='bar',
help='--foo should be always bar!')
@pytest.fixture
def foo(request):
fooval = request.config.getoption('foo')
if fooval != 'bar':
raise ValueError('expected foo to be "bar"; "{}" provided'.format(fooval))
它添加了一个新的命令行 arg --foo 和一个 fixture foo 返回传递的 arg,或者 bar 如果没有指定。如果除了 bar 之外还有其他任何东西通过 --foo 传递,fixture 会引发一个 ValueError。
你像往常一样使用 fixture ,例如
def test_something(foo):
assert foo == 'bar'
现在让我们测试一下这个 fixture 。
准备
在这个例子中,我们需要先做一些简单的重构。将 fixture 和相关代码移动到一些名为 conftest.py 的文件,例如 my_plugin.py:
# my_plugin.py
import pytest
def pytest_addoption(parser):
parser.addoption('--foo', action='store', dest='foo', default='bar',
help='--foo should be always bar!')
@pytest.fixture
def foo(request):
fooval = request.config.getoption('foo')
if fooval != 'bar':
raise ValueError('expected foo to be "bar"; "{}" provided'.format(fooval))
在 conftest.py 中,确保加载了新插件:
# conftest.py
pytest_plugins = ['my_plugin']
运行现有的测试套件以确保我们没有破坏任何东西,所有测试应该仍然通过。
激活pytester
pytest 提供了一个用于编写插件测试的额外插件,称为 pytester。默认情况下未激活,因此您应该手动执行此操作。在 conftest.py 中,使用 pytester 扩展插件列表:
# conftest.py
pytest_plugins = ['my_plugin', 'pytester']
编写测试
一旦 pytester 处于事件状态,您将获得一个名为 testdir 的新 fixture 。它可以从代码生成和运行 pytest 测试套件。这是我们的第一个测试的样子:
# test_foo_fixture.py
def test_all_ok(testdir):
testdata = '''
def test_sample(foo):
assert True
'''
testconftest = '''
pytest_plugins = ['my_plugin']
'''
testdir.makeconftest(testconftest)
testdir.makepyfile(testdata)
result = testdir.runpytest()
result.assert_outcomes(passed=1)
这里发生的事情应该很明显:我们将测试代码作为字符串提供,testdir 将在某个临时目录中从中生成一个 pytest 项目。为了确保我们的 foo fixture 在生成的测试项目中可用,我们在生成的 conftest 中传递它,就像我们在真实项目中所做的那样。 testdir.runpytest() 开始测试运行,产生我们可以检查的结果。
让我们添加另一个测试来检查 foo 是否会引发 ValueError:
def test_foo_valueerror_raised(testdir):
testdata = '''
def test_sample(foo):
assert True
'''
testconftest = '''
pytest_plugins = ['my_plugin']
'''
testdir.makeconftest(testconftest)
testdir.makepyfile(testdata)
result = testdir.runpytest('--foo', 'baz')
result.assert_outcomes(errors=1)
result.stdout.fnmatch_lines([
'*ValueError: expected foo to be "bar"; "baz" provided'
])
在这里,我们使用 --foo baz 执行生成的测试,然后验证一个测试是否以错误结束,并且错误输出是否包含预期的错误消息。
