没有必要弄乱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