我想出了另一个解决方案(behave-1.2.6):
我设法通过使用动态创建场景大纲的示例before_feature
.
给定一个特征文件(x.feature
):
Feature: Verify squared numbers
Scenario Outline: Verify square for <number>
Then the <number> squared is <result>
Examples: Static
| number | result |
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
# Use the tag to mark this outline
@dynamic
Scenario Outline: Verify square for <number>
Then the <number> squared is <result>
Examples: Dynamic
| number | result |
| . | . |
和步骤文件(steps/x.step
):
from behave import step
@step('the {number:d} squared is {result:d}')
def step_impl(context, number, result):
assert number*number == result
诀窍是使用before_feature
in environment.py
因为它已经将示例表解析为场景大纲,但尚未从大纲生成场景。
import behave
import copy
def before_feature(context, feature):
features = (s for s in feature.scenarios if type(s) == behave.model.ScenarioOutline and
'dynamic' in s.tags)
for s in features:
for e in s.examples:
orig = copy.deepcopy(e.table.rows[0])
e.table.rows = []
for num in range(1,5):
n = copy.deepcopy(orig)
# This relies on knowing that the table has two rows.
n.cells = ['{}'.format(num), '{}'.format(num*num)]
e.table.rows.append(n)
这仅适用于标记为的场景大纲@dynamic
.
结果是:
behave -k --no-capture
Feature: Verify squared numbers # features/x.feature:1
Scenario Outline: Verify square for 1 -- @1.1 Static # features/x.feature:8
Then the 1 squared is 1 # features/steps/x.py:3
Scenario Outline: Verify square for 2 -- @1.2 Static # features/x.feature:9
Then the 2 squared is 4 # features/steps/x.py:3
Scenario Outline: Verify square for 3 -- @1.3 Static # features/x.feature:10
Then the 3 squared is 9 # features/steps/x.py:3
Scenario Outline: Verify square for 4 -- @1.4 Static # features/x.feature:11
Then the 4 squared is 16 # features/steps/x.py:3
@dynamic
Scenario Outline: Verify square for 1 -- @1.1 Dynamic # features/x.feature:19
Then the 1 squared is 1 # features/steps/x.py:3
@dynamic
Scenario Outline: Verify square for 2 -- @1.2 Dynamic # features/x.feature:19
Then the 2 squared is 4 # features/steps/x.py:3
@dynamic
Scenario Outline: Verify square for 3 -- @1.3 Dynamic # features/x.feature:19
Then the 3 squared is 9 # features/steps/x.py:3
@dynamic
Scenario Outline: Verify square for 4 -- @1.4 Dynamic # features/x.feature:19
Then the 4 squared is 16 # features/steps/x.py:3
1 feature passed, 0 failed, 0 skipped
8 scenarios passed, 0 failed, 0 skipped
8 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.005s
这依赖于具有正确形状的示例表作为最终表,在我的示例中,有两行。我也不热衷于创造新的behave.model.Row
对象,我只需从表中复制一个并更新它。为了更加丑陋,如果您使用文件,您可以将文件名放在示例表中。