4

现在我有以下测试功能目录:

Tests/
--BehaveTest1/
----BehaveTest1.feature
----steps/
------test_steps.py
--BehaveTest2/
----BehaveTest2.feature
----steps/
------test_steps.py

由于 BehaveTest1 和 BehaveTest2 的测试步骤很常见,我想实现一个通用模块,两个测试用例都可以在需要时调用它。目前,我在 Tests/ 文件夹中创建了一个 common/ 目录,并通过以下方式导入它(在每个测试功能的 test_steps.py 文件中):

import sys, os
sys.path.append('../common')
import common

但是我不想弄乱路径,所以我想知道是否有更好的方法来使用行为测试功能的结构来做到这一点?

4

4 回答 4

9

没有必要弄乱sys.path,这与您使用的 Python 版本无关。这同样适用于 Python 2.7 或 Python 3.x。

给定以下文件结构:

Tests/
├── BehaveTest1
│   ├── BehaveTest1.feature
│   └── steps
│       └── test_steps.py
├── BehaveTest2
│   ├── BehaveTest2.feature
│   └── steps
│       └── test_steps.py
├── common.py
├── __init__.py

__init__.py目录中的存在Tests是关键。它是一个空文件,但没有它,Python 将无法加载该模块,因为它Tests不会被视为一个包。

我可以test_steps.py在两个目录中都这样做:

import Tests.common

Tests/common.py文件包含:

from behave import when, then

@when("foo")
def foo(context):
    pass

@then("bar")
def bar(context):
    pass

@when@then自动放入 Behave 从steps/子目录加载的文件中,而不是从您使用import.

然后,我可以使用调用中定义的步骤的假功能文件来运行它common.py

$ behave Tests/BehaveTest*
Feature: BehaveTest1 # Tests/BehaveTest1/BehaveTest1.feature:1

  Scenario: foo  # Tests/BehaveTest1/BehaveTest1.feature:3
    When foo     # Tests/common.py:3 0.000s
    Then bar     # Tests/common.py:7 0.000s

Feature: BehaveTest2 # Tests/BehaveTest2/BehaveTest2.feature:1

  Scenario: foo  # Tests/BehaveTest2/BehaveTest2.feature:3
    When foo     # Tests/common.py:3 0.000s
    Then bar     # Tests/common.py:7 0.000s

2 features passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
4 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.000s
于 2016-05-25T10:50:54.847 回答
0

实际上,没有其他方法可以像您这样做:

您想从某个位置导入代码。这意味着你需要让 python 知道这个位置。这是通过 PYTHONPATH 或 sys.path.append() 完成的。

Behave(据我所知)只能在功能文件所在的“steps”目录中找到代码。如果您有其他代码,则必须设置 sys.path。

在 python > 3.3 中它可以更容易一些,因为“命名空间”包(pep420)可以调用

 :$ behave Tests/BehaveTest1/BehaveTest1.feature

在 Tests 目录的父文件夹中。那么你将不得不做

import Tests.common

在您的步骤文件中。

那是因为 Tests、BehaveTests1 和 BehaveTests2 将成为一个 python 包。

于 2016-05-24T15:37:01.517 回答
0

可以有这样的结构,如果我运行以下命令,来自 alice.features 和 bob.features 的步骤将运行:“behave”或“behave --tags @”

DIRECTORY STRUCTURE:
+-- features/
     +-- steps/   (optional, common steps)
        +-- alice.features/
         |     +-- steps/   (specific steps for alice sub features, can use common steps)
         |     +-- *.feature
        +-- bob.features/
             +-- steps/
             +-- *.feature
      +-- environment.py
于 2019-05-24T07:47:00.637 回答
-3

对我来说最灵活的方法是在我的步骤文件夹中创建我的类的文件夹:

features/test.feature
test_steps/
test_steps/classes
test_environment.py
于 2016-06-21T03:11:22.013 回答