Background 关键字实际上比任何东西都更像语法糖,它将 Background 中的步骤应用于功能中的每个场景。如果您只想一次性记录用户,可以尝试在上下文对象中管理它。
鉴于这种行为结构:
├── behave.ini
└── features
├── environment.py
├── login-once.feature
└── steps
└── steps.py
behave.ini:
[behave]
stdout_capture = false
stderr_capture = false
log_capture = false
login-once.feature:
Feature: User Login only actually happens once
Background: User Login
Given the user is logged in
Scenario: User clicks Home
When the user clicks the Home button
Then the Home page is shown
Scenario: User clicks About
When the user clicks the About button
Then the About page is shown
环境.py:
# Behave has an interesting page/heap structure behind the scenes
# that obfuscates what is and isn't in the context object.
# This class is instantiated in the before_all function and used
# to assign values, so that they persist across scenario tests
class Holder(object):
pass
def before_all(context):
context.holder = Holder()
def before_feature(context, feature):
context.holder.logged_in = False
steps.py
from behave import given, then, when
@given('the user is logged in')
def user_logged_in(context):
if context.holder.logged_in is True:
print("\t\tThe user is already logged in, will not log in again")
else:
print("\t\tLogging user in for the first time")
context.holder.logged_in = True
@when('the user clicks the {button} button')
def user_clicks_button(context, button):
print(f"\t\tThe user clicked the {button} button")
@then('the {page} page is shown')
def page_is_shown(context, page):
print(f"\t\tThe {page} page is being shown")
当我现在运行表现时,我得到以下输出:
$ behave -f plain
Feature: User Login only actually happens once
Background: User Login
Scenario: User clicks Home
Logging user in for the first time
Given the user is logged in ... passed in 0.000s
The user clicked the Home button
When the user clicks the Home button ... passed in 0.000s
The Home page is being shown
Then the Home page is shown ... passed in 0.000s
Scenario: User clicks About
The user is already logged in, will not log in again
Given the user is logged in ... passed in 0.000s
The user clicked the About button
When the user clicks the About button ... passed in 0.000s
The About page is being shown
Then the About page is shown ... passed in 0.000s
1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
6 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.001s