python-3.x 如何在行为中控制全局计数器?

vs3odd8k  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(284)

我尝试在behave中使用环境文件函数来维护计数器变量。我的实现看起来像这样:

def before_all(context):
    context.counter = -1

def before_scenario(context, scenario):
    print(context.counter)

def after_scenario(context, scenario):
    context.counter += 1

我有一个包含多个scenario.feature文件。但是对于每个scenario总是得到相同的值。我该怎么解决呢?

brccelvz

brccelvz1#

简短的答案很简单:你不能在Behave中这样做,在执行过程中修改的值在连续的场景中是不持久的。
解释:这是一个非常危险的想法,因为你正在创建依赖的场景。你总是必须设计独立的场景,这样你就可以以任何顺序执行它们中的任何一个。
我给予你举个例子:您有两个相互依赖的连续方案:

Scenario 1:
 Given I get the counter with value -1
 When I sum 1 to the counter
 Then The counter's value is 0

Scenario 2:
 When I sum 1 to the counter again
 Then The counter's value is 1

这里有一个非常危险的依赖项,因此必须在场景2之前执行场景1。您应该按以下方式更改实现:

Scenario 1:
 Given I get the counter with value -1
 When I sum 1 to the counter
 Then The counter's value is 0

Scenario 2:
 Given I get the counter with value -1
 And I sum 1 to the counter
 When I sum 1 to the counter again
 Then The counter's value is 1

如您所见,我在场景2中重复了场景1中的一些步骤,但这样我就实现了两个场景的独立性。

相关问题