BDD-python+behave自动化测试搭建
Behave 是一种基于行为驱动开发(Behavior-Driven Development, BDD)的 Python 测试框架。
1. BDD简介
BDD(Behavior Driven Development),即行为驱动开发。BDD是ATDD验收测试驱动开发的一种升级版,根据明确的预期行为(一组场景)来进行开发和测试。
BDD使用Gherkin
的自然语言风格来编写测试用例,文件格式为*.feature
,如一个后台登录功能,可以描述如下:
1 | Feature: 登录功能 |
以上就表示了一个完整的的测试,由于使用的是自然语言,因此这种自动化测试用例无论是从书写上,还是阅读上都是很容易的,完全可以交付给非技术类型的人去编写。
Gherkin
语法中的关键词:
1 | Feature: 特性,一般指一个功能点,如登录,添加商品,查询商品等,在测试中对应一个测试套件 |
行为驱动多用于UI层的测试。因此BDD框架的自动化一般结合Selenium使用。
2.behave基本使用
常用的BDD框架
最出名的BDD框架应该是Cucumber,使用Ruby语言,Python中常用的有behave、pytest-bdd和lettuce,其中lettuce不支持Python3。
behave是比较易用的一款BDD测试框架,github地址为:https://github.com/behave/behave
安装behave和selenium
1
2pip install behave
pip install selenium项目所需的最小目录结构
1
2
3
4
5+--features/
| +--steps/ # -- 存放测试步骤的目录
| | +-- *.py # -- 测试步骤的具体实现
| +-- *.feature # -- 测试用例
| +-- environment.py # 可选,用于自定义behave的环境变量,例如可以定义每个Scenario结束后做XXX事。编写场景文件
在features中新建一个
baidu.feature
的文件,内容如下:1
2
3
4
5
6
7Feature: 百度搜索
Scenario: 搜索关键词
Given 关键词 behave
When 打开百度页面
And 输入关键词
And 点击百度一下按钮
Then 页面标题中应包含关键词实现场景步骤
在features中新建steps目录,在steps目录中新建
baidu_steps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29from behave import given, when, then
from selenium import webdriver
from time import sleep
# 对应步骤 Given 关键词 behave, 参数放在{}中
def step_impl(context, keyword): # context是上下文对象,有参数的话,加上对应参数
context.keyword = keyword # 将参数绑定上下文对象,以便其他步骤使用
def step_impl(context):
context.driver = driver = webdriver.Chrome() # 同样绑定上下文对象
driver.implicitly_wait(10)
driver.get('https://www.baidu.com')
def step_impl(context):
context.driver.find_element('id', 'kw').send_keys(context.keyword)
def step_impl(context):
context.driver.find_element('id', 'su').click()
sleep(0.5)
def step_impl(context):
assert context.keyword in context.driver.title运行
直接在
features
同级目录执行behave
即可
3.扩展
基于behave框架,GitHub上有很多好用的第三方插件可以使用:
- behaving —基于behave的web自动化测试
- behave-http —基于behave的接口自动化测试
- behave-db —基于behave的数据库自动化测试