本章目标
- 完成Python、PyCharm、behave和allure的安装
- 创建并执行测试用例,并生成报告,了解behave的基本用法
软件安装
Python安装
首先参考下面链接完成Python安装:
https://zhuanlan.zhihu.com/p/111168324
Git安装
参考下面链接完成Git安装:
https://zhuanlan.zhihu.com/p/443527549
PyCharm安装
建议选择PyCharm专业版,因为它支持behave的文件识别和调试等。如果不方便,您可以使用社区版。请参考下面链接完成安装:
https://zhuanlan.zhihu.com/p/159394831
专业版的激活我是在淘宝买的,大家也可以参考网上的激活教程。
创建PyCharm项目
1 创建项目文件夹
2 打开PyCharm,并选择该目录作为项目路径
3 配置项目的Python解释器,选择File->Settings,按下图所示操作。
4 右键项目文件夹,然后按下图顺序,创建第一个python文件
5 在右侧代码区空白处右键,运行创建的Python代码。如果出现如下结果,则表示安装成功:
behave安装
在PyCharm中安装behave和allure-behave,参考下图所示。
安装完成后的状态如下:
allure安装
allure的安装可参考下面链接:
https://blog.csdn.net/J_____Q/article/details/120597351
behave使用简介
简要步骤
1 创建features文件夹和tutorial.feature文件,如下图所示
tutorial.feature:
Feature: showing off behave
Scenario: run a simple test
Given we have behave installed
When we implement a test
Then behave will test it for us!
2 在features文件夹创建steps文件夹,并创建tutorial.py,如下图所示。
tutorial.py:
from behave import *
@given('we have behave installed')
def step_impl(context):
pass
@when('we implement a test')
def step_impl(context):
assert True is not False
@then('behave will test it for us!')
def step_impl(context):
assert context.failed is False
3 在PyCharm的Terminal中输入"behave",即可执行测试,然后就可以看到Terminal中输出了测试运行的结果。
总结
在测试自动化流程中,behave是一个非常有用的工具,可以帮助开发人员和测试人员快速编写、运行和维护测试用例。
以下是我理解的behave测试用例的运行过程:
- 打开Terminal并输入behave命令,调用的是Python安装路径(如:D:\Program Files\Python\Python310\Scripts)下的behave.exe;
- behave.exe开始执行,在执行behave命令时的目录(D:\11_projects\21_demo\09_auto_test)中寻找features文件夹,并在其中找到tutorial.feature文件;
- behave.exe读取tutorial.feature文件中的测试用例步骤,并在features目录下的steps目录中查找相应的步骤实现代码,然后执行这些代码;
- behave.exe运行所有的feature文件中的测试用例,并输出运行结果。
本文中提到的例子就是behave网站上的例子,各位可以参照behave网站进行进一步的学习,学习时可先从tutorial开始。
生成allure报告并查看
- 在PyCharm的Terminal中输入如下命令:用来运行behave,并以allure格式生成报告,最终的数据文件放到allure_result文件夹中。
behave -f allure_behave.formatter:AllureFormatter -o allure_result
此命令会在当前目录下生成名为allure_result的文件夹,并将测试结果以allure格式保存在其中。
- 接下来,在Terminal中输入以下命令,将自动打开浏览器,并显示测试报告:
allure serve .\allure_result
behave命令
命令 | 功能 |
---|---|
behave -f allure_behave.formatter:AllureFormatter -o allure_result | 执行behave,并生成allure格式的结果 |
behave -t=tag1 -t=tag2 | 执行标签有"tag1"且有"tag2"的测试用例 |
behave -t=tag1,tag2 | 执行标签有"tag1"或者有"tag2"的测试用例 |
behave -t=-tag1 | 执行标签没有"tag1"的测试用例 |
allure命令
命令 | 功能 |
---|---|
allure serve .\allure_result | 生成并打开测试报告(相当于下面两条命令) |
allure generate .\allure_result -o .\allure_report --clean | 生成报告 |
allure open .\allure_report | 打开测试报告 |