我在py.test中运行fixture conftest file。你可以看到下面的代码(一切正常):
example_test.py
import pytest
@pytest.fixture
def platform():
return "ios"
@pytest.mark.skipif("platform == 'ios'")
def test_ios(platform):
if platform != 'ios':
raise Exception('not ios')
def test_android_external(platform_external):
if platform_external != 'android':
raise Exception('not android')
conftest.py
import pytest
@pytest.fixture
def platform_external():
return "android"
现在我希望能够跳过一些不适用于我当前测试运行的测试。在我的示例中,我正在为 iOS 或 Android 运行测试(这仅用于演示目的,可以是任何其他表达式。)
不幸的是,我无法在platform_external
语句中看到(我的外部定义的 fixture )skipif
。当我运行下面的代码时,我收到以下异常:NameError: name 'platform_external' is not defined
。我不知道这是 py.test 错误,因为本地定义的灯具正在运行。
example_test.py
的附加组件@pytest.mark.skipif("platform_external == 'android'")
def test_android(platform_external):
"""This test will fail as 'platform_external' is not available in the decorator.
It is only available for the function parameter."""
if platform_external != 'android':
raise Exception('not android')
所以我想我会创建自己的装饰器,只是为了看到它不会收到灯具作为参数:
from functools import wraps
def platform_custom_decorator(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
return func(*args, **kwargs)
return func_wrapper
@platform_custom_decorator
def test_android_2(platform_external):
"""This test will also fail as 'platform_external' will not be given to the
decorator."""
if platform_external != 'android':
raise Exception('not android')
如何在 conftest 文件中定义灯具并将其用于(有条件地)跳过测试?
答案 0 :(得分:25)
在评估skipif
的表达式时,似乎py.test不使用测试夹具。根据您的示例,test_ios
实际上是成功的,因为它将模块命名空间中的函数 platform
与"ios"
字符串进行比较,后者的计算结果为{{1因此测试执行并成功。如果pytest正在按预期插入夹具进行评估,那么应该跳过该测试。
问题的解决方案(不是你的问题)是实现一个夹具,检查标记到测试中,并相应地跳过它们:
False
关键点是# conftest.py
import pytest
@pytest.fixture
def platform():
return "ios"
@pytest.fixture(autouse=True)
def skip_by_platform(request, platform):
if request.node.get_closest_marker('skip_platform'):
if request.node.get_closest_marker('skip_platform').args[0] == platform:
pytest.skip('skipped on this platform: {}'.format(platform))
参数,这将使所有测试自动包含该灯具。然后,您的测试可以标记要跳过的平台:
autouse
希望有所帮助!
答案 1 :(得分:2)
从这个answer的灵感到另一个SO问题,我正在使用这种方法来解决这个问题,效果很好:
import pytest
@pytest.fixture(scope='session')
def requires_something(request):
something = 'a_thing'
if request.param != something:
pytest.skip(f"Test requires {request.param} but environment has {something}")
@pytest.mark.parametrize('requires_something',('something_else',), indirect=True)
def test_indirect(requires_something):
print("Executing test: test_indirect")
答案 2 :(得分:0)
我遇到了类似的问题而且我不知道这是否仍然与您相关,但我可能找到了一种能够满足您需求的解决方法。
我们的想法是扩展MarkEvaluator
类并覆盖_getglobals
方法以强制在评估者使用的全局集中添加fixture值:
<强> conftest.py 强>
from _pytest.skipping import MarkEvaluator
class ExtendedMarkEvaluator(MarkEvaluator):
def _getglobals(self):
d = super()._getglobals()
d.update(self.item._request._fixture_values)
return d
为测试调用添加一个钩子:
def pytest_runtest_call(item):
evalskipif = ExtendedMarkEvaluator(item, "skipif_call")
if evalskipif.istrue():
pytest.skip('[CANNOT RUN]' + evalskipif.getexplanation())
然后您可以在测试用例中使用标记skipif_call
:
<强> test_example.py 强>
class Machine():
def __init__(self, state):
self.state = state
@pytest.fixture
def myfixture(request):
return Machine("running")
@pytest.mark.skipif_call('myfixture.state != "running"')
def test_my_fixture_running_success(myfixture):
print(myfixture.state)
myfixture.state = "stopped"
assert True
@pytest.mark.skipif_call('myfixture.state != "running"')
def test_my_fixture_running_fail(myfixture):
print(myfixture.state)
assert False
@pytest.mark.skipif_call('myfixture.state != "stopped"')
def test_my_fixture_stopped_success(myfixture):
print(myfixture.state)
myfixture.state = "running"
@pytest.mark.skipif_call('myfixture.state != "stopped"')
def test_my_fixture_stopped_fail(myfixture):
print(myfixture.state)
assert False
生成强>
pytest -v --tb=line
============================= test session starts =============================
[...]
collected 4 items
test_example.py::test_my_fixture_running_success PASSED
test_example.py::test_my_fixture_running_fail FAILED
test_example.py::test_my_fixture_stopped_success PASSED
test_example.py::test_my_fixture_stopped_fail FAILED
================================== FAILURES ===================================
C:\test_example.py:21: assert False
C:\test_example.py:31: assert False
===================== 2 failed, 2 passed in 0.16 seconds ======================
<强>问题强>
不幸的是,这对每个评估表达式只有一次,因为MarkEvaluator使用基于表达式的缓存eval作为键,因此下次测试相同的表达式时,结果将是缓存的值。
<强>解决方案强>
表达式在_istrue
方法中进行评估。遗憾的是,无法配置评估程序以避免缓存结果。
避免缓存的唯一方法是覆盖_istrue
方法以不使用cached_eval函数:
class ExtendedMarkEvaluator(MarkEvaluator):
def _getglobals(self):
d = super()._getglobals()
d.update(self.item._request._fixture_values)
return d
def _istrue(self):
if self.holder:
self.result = False
args = self.holder.args
kwargs = self.holder.kwargs
for expr in args:
import _pytest._code
self.expr = expr
d = self._getglobals()
# Non cached eval to reload fixture values
exprcode = _pytest._code.compile(expr, mode="eval")
result = eval(exprcode, d)
if result:
self.result = True
self.reason = expr
self.expr = expr
break
return self.result
return False
生成强>
pytest -v --tb=line
============================= test session starts =============================
[...]
collected 4 items
test_example.py::test_my_fixture_running_success PASSED
test_example.py::test_my_fixture_running_fail SKIPPED
test_example.py::test_my_fixture_stopped_success PASSED
test_example.py::test_my_fixture_stopped_fail SKIPPED
===================== 2 passed, 2 skipped in 0.10 seconds =====================
现在跳过了测试,因为&#39; myfixture&#39;价值已经更新。
希望它有所帮助。
干杯
亚历
答案 3 :(得分:0)
Bruno Oliveira的解决方案正在运行,但是对于新的pytest(> = 3.5.0),您需要添加pytest_configure:
# conftest.py
import pytest
@pytest.fixture
def platform():
return "ios"
@pytest.fixture(autouse=True)
def skip_by_platform(request, platform):
if request.node.get_closest_marker('skip_platform'):
if request.node.get_closest_marker('skip_platform').args[0] == platform:
pytest.skip('skipped on this platform: {}'.format(platform))
def pytest_configure(config):
config.addinivalue_line(
"markers", "skip_by_platform(platform): skip test for the given search engine",
)
使用:
@pytest.mark.skip_platform('ios')
def test_ios(platform, request):
assert 0, 'should be skipped'