Behave - 钩子函数



Behave 的设置和拆卸函数在一个名为 environment.py 的文件中实现,该文件与包含步骤文件夹的同一目录中。

设置函数包括:打开浏览器、数据库连接、配置等等。

拆卸函数包括:关闭浏览器、终止数据库连接、撤销更改等等。

  • environment.py 文件包含以下函数:

  • before_feature(context, feature) - 在每个特性之前执行。

  • before_scenario(context, scenario) - 在每个场景之前执行。

  • before_step(context, step) - 在每个步骤之前执行。

  • before_tag(context, tag) - 在每个标签之前执行。

  • before_all(context) - 在所有内容之前执行。

  • after_feature(context, feature) - 在每个特性之后执行。

  • after_scenario(context, scenario) - 在每个场景之后执行。

  • after_step(context, step) - 在每个步骤之后执行。

  • after_tag(context, tag) - 在每个标签之后执行。

after_all(context) - 在所有内容之后执行。

Project Structure

以上函数在 Behave 中用作钩子函数。项目结构应如下所示:

包含钩子函数的特性文件 (Payment.feature)

Feature − Payment Process
Scenario − Verify transactions
         Given user makes a payment of 100 INR And user makes a payment of 10 Dollar

包含 Payment.feature 钩子函数的特性文件如下:

包含钩子函数的特性文件 (Payment1.feature)

Feature − Administration Process
Scenario − Verify admin transactions
         Given user is on admin screen

Payment1.feature 的包含钩子函数的特性文件如下:

相应的步骤实现文件

from behave import *
from parse_type import TypeBuilder
parse_amt = TypeBuilder.make_choice(["100", "10"])
register_type(Amt=parse_amt)
parse_curr = TypeBuilder.make_choice(["INR", "Dollar"])
register_type(Curn=parse_curr)
@given("user makes a payment of {n:Amt} {t:Curn}")
def step_payment(context, n, t):
   pass
@given('user is on admin screen')
def step_admin(context):
   pass

步骤实现文件如下:

步骤 4 - environment.py 文件中的钩子函数

# before all
def before_all(context):
   print('Before all executed')
# before every scenario
def before_scenario(scenario, context):
   print('Before scenario executed')
# after every feature
def after_feature(scenario, context):
   print('After feature executed')
# after all
def after_all(context):
   print('After all executed')

environment.py 文件中的钩子函数如下:

输出

Hooks
打印页面
© . All rights reserved.