【发布时间】:2015-03-26 13:44:00
【问题描述】:
背景
我在conftest file 中运行py.test 和fixture。你可以看到下面的代码(这一切都很好):
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 运行测试(这仅用于演示目的,可以是任何其他表达式)。
不幸的是,我无法在skipif 语句中获得(我的外部定义的fixture)platform_external。当我运行下面的代码时,我收到以下异常: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 文件中定义 fixture 并使用它(有条件地)跳过测试?
【问题讨论】:
标签: python decorator pytest python-decorators