Pytest-bdd:导入常见步骤



编辑:我不再从事这个项目,但我会把这个问题留给回答,以防它对任何人都有用。

我正在努力实现pytest-bdd,并尝试从名为ui_shared.py的不同文件中导入使用步骤。

目前我的目录是结构化的:

proj/lib/ui_file.py
proj/lib/ui_shared.py
proj/tests/test_file.py
proj/features/file.feature

Pytest-bdd 能够识别ui_shared.py中的步骤,只要ui_file.py导入,就可以执行测试:

from ui_shared import *

但我想避免使用导入*。

我已经尝试了import ui_shared.pyfrom ui_shared.py import common_step,其中common_step是我想导入的步进函数,但出现错误:

StepDefinitionNotFoundError: Step definition is not found: Given "common function".

我发现了一个相关的问题: 行为:如何从另一个文件导入步骤? 以及其他一些,其中大多数都说将步骤导入到通用步骤文件中,ui_shared.py在我的情况下,我已经这样做了。

这是ui_shared.py的代码:

#!/usr/bin/python
import pytest
from pytest_bdd import (
scenario,
given,
when,
then
)
@pytest.fixture(scope="function")
def context():
return{}
@given('common step')
def common_step(input):
#some method

以下是其他相关代码:

file.feature

Scenario Outline: ui_file
Given common step
And another given step
When some step
Then last step

test_file.py

#!/usr/bin/python
@pytest.fixture
def pytestbdd_strict_gherkin():
return False
@scenario('proj/features/file.feature', 'ui_file')
def test_ui_file():
"""ui_file"""

并在ui_file.py

import pytest
from pytest_bdd import (
scenario,
given,
when,
then
)
from ui_shared import * #This is what I am trying to change
@given('another given step')
def another_given_step(input)
#some method
@when('some step')
def some_step(input)
#some method
@then('last step')
def last_step(input)
#some method

上述方法应该按原样工作,但是如果更改了导入方法,则pytest将失败并显示E StepDefinitionNotFoundError

我正在寻找的是一种导入ui_shared.py中定义的所有名称的方法,除了我不使用的方法。

基本上,如何使用没有 * 的from file import导入并允许我的ui_file.py使用ui_shared.py中的常见步骤?

conftest.py中添加以下行

pytest_plugins = [
"lib.ui_shared"
]

这样,ui_shared.py内的所有夹具或pytest-bdd步骤都将可用于所有其他文件,就好像它在conftest.py

注意
lib必须是一个包,这意味着lib文件夹中应该有一个__init__.py文件

我刚刚找到了一种方法来完成这项工作,尽管它没有那么优雅。如果将from ui_shared import *更改为from ui_shared import common_step,然后在同一ui_file.py中添加(given('common_step'))(common_step),则可以运行测试导入common_step而不使用import *。所以你会有这个:

在ui_file.py:

import pytest
from pytest_bdd import (
scenario,
given,
when,
then
)
from ui_shared import common_step
(given('common_step'))(common_step)
@given('another given step')
def another_given_step(input)
#some method
@when('some step')
def some_step(input)
#some method
@then('last step')
def last_step(input)
#some method

其余文件将保持不变。

现在,我不清楚这工作的原因,但看起来导入装饰函数使用装饰器的语法糖不起作用,因此只有在显式装饰函数时才可以使用导入的步骤(没有带有@的语法糖(。

编辑:在添加的给定行中更新了偏执。

你可以尝试这样的事情:

from .ui_file import *

这就是我为我的项目写的:

from .devices_steps import *

最新更新