![](/img/trans.png)
[英]Is there a way to use pytest.raises in pytest-bdd "When" steps?
[英]Pytest-bdd: Importing common steps
编辑:我不再从事这个项目,但我会把这个问题悬而未决,直到有人回答它,以防它对任何人都有用。
我正在努力实施 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 *.
我试过import ui_shared.py
和from ui_shared.py import common_step
,其中common_step
是我想导入的步骤 function,我得到了错误:
StepDefinitionNotFoundError: Step definition is not found: Given "common function".
我发现了一个相关问题: Behave: How to import steps from another file? 以及其他一些,其中大部分说要将步骤导入通用步骤文件,在我的例子中是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"
]
这样,里面的所有装置或pytest-BDD步骤ui_shared.py
将提供给所有其他文件,就好像是里面conftest.py
笔记
lib必须是一个包,这意味着lib文件夹中应该有一个__init__.py
文件
你可以尝试这样的事情:
from .ui_file import *
这就是我为我的项目写的:
from .devices_steps import *
我刚刚找到了一种方法来完成这项工作,尽管它并不那么优雅。 如果您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
文件的 rest 将保持不变。
现在,我不清楚这个工作的原因,但看起来使用装饰器的语法糖导入装饰的 function 不起作用,因此只有当你显式装饰 function 时才能使用导入的步骤(没有语法糖和 @)。
编辑:在添加的给定行中更新了括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.