在 Python 的 behave 中库,我可以编写一个带有参数化场景大纲的功能文件,如下所示(改编自 this tutorial ):
# feature file
Feature: Scenario Outline Example
Scenario Outline: Use Blender with <thing>
Given I put "<thing>" in a blender
When I switch the blender on
Then it should transform into "<other thing>"
Examples: Amphibians
| thing | other thing |
| Red Tree Frog | mush |
| apples | apple juice |
相应的步骤定义如下所示:
# steps file
from behave import given, when, then
from hamcrest import assert_that, equal_to
from blender import Blender
@given('I put "{thing}" in a blender')
def step_given_put_thing_into_blender(context, thing):
context.blender = Blender()
context.blender.add(thing)
@when('I switch the blender on')
def step_when_switch_blender_on(context):
context.blender.switch_on()
@then('it should transform into "{other_thing}"')
def step_then_should_transform_into(context, other_thing):
assert_that(context.blender.result, equal_to(other_thing))
可以看出,将特征文件中的参数传递到步骤函数中的方法是
- 在尖括号中的特征文件中明确提及它们
- 然后在 step 函数的装饰器中包含用大括号括起来的相同单词(为什么不用尖括号?!)
- 最后插入这些词作为step函数的函数参数。
但是,给定一个包含很多列的更大的示例表,这很快就会让读写变得烦人:
# feature file
Feature: Large Table Example
Scenario Outline: Use Blender with a lot of things
Given I put "<first_thing>", "<second_thing>", "<third_thing>", "<fourth_thing>", "<fifth_thing>", "<sixth_thing>", "<seventh_thing>" in a blender
When I switch the blender on
Then it should transform into "<other thing>"
Examples: Things
| first thing | second thing | third thing | fourth thing | fifth thing | sixth thing | seventh thing |
| a | b | c | d | e | f | g | h |
| i | j | k | l | m | n | o | p |
# steps file
@given('I put "{first_thing}", "{second_thing}", "{third_thing}", "{fourth_thing}", "{fifth_thing}", "{sixth_thing}", "{seventh_thing}", in a blender')
def step_given_put_thing_into_blender(context, first_thing, second_thing, third_thing, fourth_thing, fifth_thing, sixth_thing, seventh_thing):
context.blender = Blender()
context.blender.add(thing)
...
我觉得问题很明显了。是否有可能将示例从大表转移到步骤定义中而不必明确提及所有示例?例如,它们是否保存在上下文变量中的某处,即使没有在文本中提及它们(还无法在那里找到它们)?
请您参考如下方法:
除了考虑是否真的需要使用大型场景大纲表(参见另一个答案)之外,确实可以访问当前表行而无需通过 context.active_outline (which is a bit hidden in the appendix of the documentation) 明确提及给定/何时/然后步骤中的所有参数.
context.active_outline 返回一个 behave.model.row 对象,可以通过以下方式访问:
-
context.active_outline.headings返回表头列表,无论当前迭代的行是什么(问题示例中的first_thing、second_thing 等) -
context.active_outline.cells返回当前迭代行的单元格值列表(示例中的a、b、c 等)问题) - 基于索引的访问,例如
context.active_outline[0],返回第一列(无论标题如何)的单元格值等。 - 基于命名的访问(如
context.active_outline['first_thing'])返回带有 first_thing 标题的列的单元格值,无论其索引如何
作为 context.active_outline.headings 和 context.active_outline.cells 返回列表,我们还可以做一些有用的事情,比如 for heading, cell in zip(context.active_outline.headings, context.active_outline.cells) 来迭代标题值对等。
