【问题标题】:Pytest-bdd: Importing common stepsPytest-bdd:导入常用步骤
【发布时间】:2018-09-10 21:18:17
【问题描述】:

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

我正在实施 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.pyfrom ui_shared.py import common_step,其中common_step 是我要导入的阶跃函数,我得到了错误:

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 的常用步骤?

【问题讨论】:

  • from ui_file import context, common_step?
  • @EPo 我也试过了,它返回相同的错误StepDefinitionNotFoundError: Step definition is not found: Given "common function".
  • 也许您可能需要创建一个最小示例(其他文件的相关内容),以允许复制错误并将其发布到问题中。拥有它后,您还可以在项目 github 存储库中提出问题,并从维护人员和其他用户那里获得建议。
  • github 上已经有一些 StepDefinitionNotFoundError 问题,但它们有些不同。
  • @EPo 我用其他相关文件的内容编辑了我的问题,希望你能重现错误。我也会看看他们的 git repo,谢谢你的建议!

标签: python bdd


【解决方案1】:

conftest.py 中添加以下行

pytest_plugins = [
   "lib.ui_shared"
]

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

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

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    from .ui_file import *
    

    这是我为我的项目写的:

    from .devices_steps import *
    

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 1970-01-01
      • 2021-07-27
      • 2021-07-27
      • 2021-10-13
      • 2022-09-27
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      相关资源
      最近更新 更多