性能试验用模块化结构

2024-05-03 19:52:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

但是我不想搅乱路径,所以我想知道是否有更好的方法来处理行为测试特性的结构?在


Tags: 模块pytest功能目录文件夹步骤测试用例
3条回答

不需要搞乱sys.path,这与您使用的Python版本无关。这与Python2.7或Python3.x一样适用

给定以下文件结构:

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

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

我可以在两个目录中都有test_steps.py,只需执行以下操作:

^{pr2}$

并且Tests/common.py文件包含:

from behave import when, then

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

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

@when@then会自动放入文件中,这些文件表现为从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

事实上,没有其他方法能像你这样做:

您希望从某个位置导入代码。这意味着您需要让python知道这个位置。这是通过Python路径或系统路径追加(). 在

behavior(据我所知)只能在特性文件所在的“steps”目录中找到代码。如果有其他代码,则必须设置搜索路径. 在

在python>;3.3中,由于“namespace”包(pep420)可以调用

 :$ behave Tests/BehaveTest1/BehaveTest1.feature

在测试目录的父文件夹中。那你就得这么做了

^{pr2}$

在step文件中。在

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

有可能有这样的结构,步骤爱丽丝。特征以及鲍勃。特写如果我运行以下命令将运行:“behave”或“behavior--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

相关问题 更多 >