【发布时间】:2020-12-12 11:42:01
【问题描述】:
我在测试文件中定义了以下夹具:
import os
from dotenv import load_dotenv, find_dotenv
from packaging import version # for comparing version numbers
load_dotenv(find_dotenv())
VERSION = os.environ.get("VERSION")
API_URL = os.environ.get("API_URL")
@pytest.fixture()
def skip_before_version():
"""
Creates a fixture that takes parameters
skips a test if it depends on certain features implemented in a certain version
:parameter target_version:
:parameter type: string
"""
def _skip_before(target_version):
less_than = version.parse(current_version) < version.parse(VERSION)
return pytest.mark.skipif(less_than)
return _skip_before
skip_before = skip_before_version()("0.0.1")
我想在某些测试中使用skip_before 作为夹具。我这样称呼它:
#@skip_before_version("0.0.1") # tried this before and got the same error, so tried reworking it...
@when(parsers.cfparse("{categories} are added as categories"))
def add_categories(skip_before, create_tree, categories): # now putting the fixture alongside parameters
pass
当我运行它时,我收到以下错误:
Fixture "skip_before_version" called directly. Fixtures are not meant to be called directly,
but are created automatically when test functions request them as parameters.
See https://docs.pytest.org/en/stable/fixture.html for more information about fixtures, and
https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code.
这还怎么被直接调用?我该如何解决这个问题?
【问题讨论】:
-
这还怎么被直接调用? - 因为
skip_before = skip_before_version("0.0.1")行。 我该如何解决这个问题? - 从代码中您想要实现的目标不是很清楚,而且代码看起来已损坏。例如。skip_before_version不希望有任何参数,但您将“0.0.1”传递给它。 -
@hoefling 你说得对,我应该在将参数传递给它返回的函数之前调用
skip_before_version,即skip_before = skip_before_version()("0.0.1")。 -
@hoefling 我仍然不确定如何使用这个夹具,如果版本不够高,它将跳过测试(这意味着它需要将版本号作为参数)。我不能将此夹具作为参数添加到函数中,因为它的语法无效,也不能直接调用它。
标签: python pytest decorator fixtures