python behave自动化测试框架(1)- 初探BDD,,一,什么是BDD  


一,什么是BDD

  BDD全称Behavior Driven Development,译作"行为驱动开发",是基于TDD(Test Driven Development 测试驱动开发)的软件开发过程和方法。

  BDD可以让项目成员(甚至是不懂编程的)使用自然语言来描述系统功能和场景,从而根据这些描述步骤进行系统自动化的测试。

二,常用BDD框架介绍

目前常用的BDD测试框架有Ruby中的Cucumber,Python中的Behave、Lettuce及Freshen等。

基本的流程如下图所示(Lettuce官方图):

技术图片

简单来说就是"写用例->跑测试->看结果->写实现->看结果"这样的一个循环。

本教程选择behave来介绍PythonBDD自动化测试框架。

三,behave实例

1,behave安装

pip install behave # 全新安装pip install -U behave # 更新

2,Gherkin语法

上文提到的几种BDD框架均使用Gherkin语法,这是一种简单易懂的语言,使用关键字来定义系统特征和测试。

使用Gherkin语法编写的feature文件基本结构如下:

Title (one line describing the story/feature)     As a     [role]    I want   [feature]    So that  [benefit]     Scenario: Title1 (for Behaviour 1)         Given  [context or setup]        And   [some more context]...        When  [event occurs]        Then  [expected outcome]        And   [another outcome]...     Scenario: Title2 (for Behaviour 2)        ... 

并且Gherkin语法还支持中文

3,目录结构

Behave项目的目录格式如下:

$PROJECT/+-- features/                   -- Contains all feature files.|       +-- steps/|       |     +-- step_*.py     -- Step definitions for features.|       +-- environment.py      -- Environment for global setup...|       +-- tutorial*.feature   -- Feature files.

下面简单说一下.feature和.py文件:

1) .feature文件是用于编写测试场,你可以把各种场景和数据写在里面,支持中文;

2) .py文件就是根据你写的测试场景和数据来执行测试。

3) 最好.feature文件与.py文件一一对应。

4,使用behave

  描述功能

  在工作目录新建文件夹features,在文件夹中新建adding.feature

Feature: Adding    Scenario: Adding two numbers        Given the input "2+2"        When the calculator is run        Then output should be "4"

  Scenario: Adding two numbers        Given the input "3+3"        When the calculator is run        Then output should be "6"

一个.feature文件里可以写多个Scenario,下面对这些关键词做一些简单的解析:

1) Feature:功能名称

2) Scenario:场景名称

3) Given:给出测试前提条件;

4) when:相当我们的测试步骤;

5) Then:给出期望结果

  编写测试

  然后在features目录下建立文件夹steps,在steps目录下新建adding_steps.py

from behave import given, when, then, step_matcher@given(u‘the input "{a:d}+{b:d}"‘)def step_given(context, a, b):    context.a = a    context.b = b@when(u‘the calculator is run‘)def step_when(context):    pass@then(u‘output should be "{c:d}"‘)def step_then(context, c):    assert context.a + context.b == c

在features同级目录下cmd运行behave 即可

python behave自动化测试框架(1)- 初探BDD

评论关闭