如何在behave中控制全局计数器?

huangapple go评论71阅读模式
英文:

How to control a global counter in behave?

问题

我尝试在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始终获取相同的值。我该如何解决这个问题?

英文:

I am trying to use environment file functions in behave to maintain a counter variable. My implementation looks like this:

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

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

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

I have a .feature file with multiple scenario. But always getting the same value for each scenario. How can I solve it?

答案1

得分: 1

在Behave中,短答案很简单:你无法在执行期间修改的值在连续的场景中保持不变。

解释一下:这是一个非常危险的想法,因为你正在创建依赖性场景。你总是必须设计独立的场景,这样你可以以任何顺序执行它们。

我给你举个例子:你有两个连续的依赖性场景:

场景1:
 假设我获得值为-1的计数器
 当我向计数器加1
 那么计数器的值为0

场景2:
 当我再次向计数器加1
 那么计数器的值为1

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

场景1:
 假设我获得值为-1的计数器
 当我向计数器加1
 那么计数器的值为0

场景2:
 假设我获得值为-1的计数器
 并且我向计数器加1
 当我再次向计数器加1
 那么计数器的值为1

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

英文:

The short answer is simple: you can't do that in Behave, the values modified during a execution are no persistent over successive Scenarios.

The explanation: that is a very dangerous idea because you are creating dependent scenarios. You always have to design independent scenarios so you can execute any of them in any order.

I'll give you an example: you have two consecutive Scenarios which are dependent:

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

You have a very dangerous dependency here, hence you must always execute the Scenario 1 before Scenario 2. You should change the implementation as the following:

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

As you see, I've repeated some steps from Scenario 1 in Scenario 2, but in that way I achieve the independence of both Scenarios.

huangapple
  • 本文由 发表于 2023年5月13日 08:05:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76240535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定