英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论