诞生于上世纪末的测试驱动开发(TDD)已经算是很深入人心了,一定程度上来说它通过既有的约定(测试)减少了开发人员间的沟通成本。但这些测试也只是开发人员自己对需求的理解,有时候开发人员、业务人员、市场部门和用户对需求的理解是有分歧的,传统的方案是厚厚的需求说明书,从测试驱动开发引申来的行为驱动开发BDD(Behavior Driven Development)可以有效的解决这个问题。
本文也不对行为驱动开发多做赘述,那是一个很大的话题,而是向大家介绍一下Python的BDD框架behave,其中会大致讲一下行为驱动开发的各个关键概念。
Behave是一个基于Python的BDD框架,它提供一个命令行工具来进行功能的管理和测试,功能文件(feature)的语法基于Gherkin语言。
简单的pip安装
pip install behave
Gherkin是知名的Ruby的BDD框架Cucumber的功能描述语言,能够以自然语言描述一个需求,例如实现两个数字相加的需求用Gherkin语法描述为
Feature: Adding
Scenario: Adding two numbers
Given the input "2+2"
When the calculator is run
Then output should be "4"
Gherkin支持多种语言,上述的功能描述用中文表示就是
功能: 加法
场景:两个数字相加
加入输入"2+2"
当计算器运行
那么结果应该是"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"
然后在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
注意可以通过大括号指定变量名和类型,context是一个全局的字典,可以用来保存之前步骤的变量。
在features
同级目录下运行
behave
可以看到结果
Gherkin语言提供一个场景大纲的语法,可以指定多组测试条件。
Feature: Adding
Scenario Outline: Adding two numbers
Given the input "<a>+<b>"
When the calculator is run
Then output should be "<c>"
Examples:
| a | b | c |
| 1 | 2 | 3 |
| 5 | -6 | -1 |
此时的测试结果也把每一组条件都罗列出来了。
其实只是关键词的一一对应。
功能: 展示用中文描述需求的样例
场景大纲: 用中文写一个简单的需求
假如我们已经安装好behave框架
当给出一个数字 <number>
那么这个数字的后继是 <next>
例子:
| number | next |
| 1 | 2 |
| 2 | 3 |
| 4 | 5 |
测试代码也要稍加调整。
from behave import given, when, then, step_matcher
@given(u'我们已经安装好behave框架')
def step_given(context):
pass
@when(u'给出一个数字 {number:d}')
def step_when(context, number):
assert number > 0
context.number = number
@then(u'这个数字的后继是 {next:d}')
def step_impl(context, next):
assert next > 0
assert context.failed is False
assert next == context.number + 1
运行时要指定语言。
behave框架还有很多功能,大家可以从官方文档里获取相关的知识。
下次当你和项目经理或用户对某个需求有很大分歧时,不妨考虑一下使用行为驱动开发。
最后祝大家享受生活,享受代码。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。