python自动化测试自学网_Python自动化测试pytest+Allure

Python自动化报告美化pytest+Allure初体验

image

报告接触过不少,Java自动化测试集成Allure美化报告,将其应用到python中。

既然要生成报告,那我们首先需要引入测试框架,pytest是python的第三方测试框架,是基于unittest的扩展框架。

根据pytest的官方网站介绍,它具有如下特点:

1、简单灵活,容易上手,文档丰富;

2、支持参数化,可以细粒度地控制要测试的测试用例;

3、能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);

4、pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等;

5、测试用例的skip和xfail处理;

6、可以很好的和CI工具结合,例如jenkins

首先我们需要在python环境上安装pytest库,这里建议通过pip安装:pip install pytest

image

然后编写一个简单的pytest测试用例,这里我们需要满足以下条件

测试文件以test_开头(以_test结尾也可以)

测试类以Test开头,并且不能带有 init 方法

测试函数以test_开头

断言使用基本的assert即可

编写简单代码如下,test_sample.py

import pytest

class TestClass(object):

@pytest.fixture(scope='function')

def setup_function(request):

def teardown_function():

print("teardown_function called.")

request.addfinalizer(teardown_function) # 此内嵌函数做teardown工作

print('setup_function called.')

@pytest.fixture(scope='module')

def setup_module(request):

def teardown_module():

print("teardown_module called.")

request.addfinalizer(teardown_module)

print('setup_module called.')

@pytest.mark.website

def test_1(setup_function):

print('Test_1 called.')

def test_2(setup_module):

print('Test_2 called.')

def test_3(setup_module):

print('Test_3 called.')

assert 2==1+1 # 通过assert断言确认测试结果是否符合预期

调用pytest,只需要在命令行里定位到测试文件所在路径,然后运行pytest即可

image

接下来,我们引入Allure 来生成漂亮的报告。

同样,也是通过pip来安装allure插件:

pip install allure-pytest

image

接着下载allure:2.7.0版本

解压之后,将allure/bin目录添加到环境变量path中:

image

接着,在测试脚本中,添加allure特性,直接看下面的脚本,我通过在脚本中添加注释的方式给大家解释allure特性的用途。

import pytest

import allure

@allure.feature('测试用例功能') # feature定义功能

class TestClass(object):

@pytest.fixture(scope='function')

def setup_function(request):

def teardown_function():

print("teardown_function called.")

request.addfinalizer(teardown_function) # 此内嵌函数做teardown工作

print('setup_function called.')

@pytest.fixture(scope='module')

def setup_module(request):

def teardown_module():

print("teardown_module called.")

request.addfinalizer(teardown_module)

print('setup_module called.')

@allure.story('功能测试用例1') # story定义用户场景

@pytest.mark.website

def test_1(setup_function):

print('Test_1 called.')

@allure.story('功能测试用例2') # story定义用户场景

def test_2(setup_module):

print('Test_2 called.')

@allure.story('功能测试用例3') # story定义用户场景

def test_3(setup_module):

print('Test_3 called.')

assert 2==1+1 # 通过assert断言确认测试结果是否符合预期

运行pytest --alluredir ./result/去生成测试结果

image

该目录下为测试结果

image

接下来,用allure generate ./result/ -o ./report/ --clean命令将测试结果生成测试报告

image

该目录下为测试报告所在,直接打开该报告有点问题,我们需要在pycharm中通过右键点击用浏览器打开

image

image

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值