pytest框架入门01

Pytest框架介绍:

Python测试框架之前一直用的是unittest+HTMLTestRunner,听到有人说pytest很好用,所以这段时间就看了看pytest文档,在这里做个记录。

pytest是一个非常成熟的全功能的Python测试框架,主要有以下几个特点:

  • 简单灵活,容易上手
  • 支持参数化
  • 能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests)
  • pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等
  • 测试用例的skip和xfail处理
  • 可以很好的和jenkins集成
  • report框架----allure 也支持了pytest

详细介绍可参考:https://blog.csdn.net/lovedingd/article/details/98952868

pytest环境安装:

#由于我是用的conda包管理,所以直接使用conda命令安装就可以了(通过终端方式执行)
conda install pytest

#安装三方测试报告模板 conda install pytest
-html

#验证安装
pytest --version

在pytest框架中,有如下约束:

所有的单测文件名都需要满足test_*.py格式或*_test.py格式。
在单测文件中,测试类以Test开头,并且不能带有 init 方法(注意:定义class时,需要以T开头,不然pytest是不会去运行该class的)
在单测类中,可以包含一个或多个test_开头的函数。
此时,在执行pytest命令时,会自动从当前目录及子目录中寻找符合上述约束的测试函数来执行。

实例:

 1 #-*-coding:utf-8-*-
 2 
 3 import pytest
 4 
 5 class Test_Case01:
 6     def setup(self):
 7         print ("---->setup method")
 8     
 9     def test_a(self):
10         print ("---->hello")
11         assert 1
12     
13     def test_b(self):
14         print ("---->hehe")
15         assert 0
16 
17     def teardown(self):
18         print ("---->teardown method")
19 
20 if __name__ =="__main__":
21     pytest.main(["-s","test_demo01.py"])    #传参用列表或元组方式,否则会报错

执行结果:

PS F:SNQU_ATDemo_AT> pytest
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.6, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: F:SNQU_ATDemo_AT
plugins: html-2.1.1, metadata-1.10.0
collected 2 items                                                                                                                                                                                                                      

testcases	est_demo01.py .F                                                                                                                                                                                                      [100%]

============================================================================================================== FAILURES ===============================================================================================================
_________________________________________________________________________________________________________ Test_Case01.test_b __________________________________________________________________________________________________________

self = <test_demo01.Test_Case01 object at 0x00000251C5B1C208>

    def test_b(self):
        print ("---->hehe")
>       assert 0
E       assert 0

testcases	est_demo01.py:15: AssertionError
-------------------------------------------------------------------------------------------------------- Captured stdout setup --------------------------------------------------------------------------------------------------------
---->setup method
-------------------------------------------------------------------------------------------------------- Captured stdout call ---------------------------------------------------------------------------------------------------------
---->hehe
------------------------------------------------------------------------------------------------------ Captured stdout teardown -------------------------------------------------------------------------------------------------------
---->teardown method
======================================================================================================= short test summary info =======================================================================================================
FAILED testcases/test_demo01.py::Test_Case01::test_b - assert 0
===================================================================================================== 1 failed, 1 passed in 0.12s =====================================================================================================
PS F:SNQU_ATDemo_AT>

Pytest测试报告:

pytest-HTML是一个插件,pytest用于生成测试结果的HTML报告。兼容Python 2.7,3.6

安装方式:pip install pytest-html

通过命令行方式,生成xml/html格式的测试报告,存储于用户指定路径。插件名称:pytest-html

使用方法: 
命令行格式:pytest --html=用户路径/report.html

如:
pytest testcases --html=Report/testreport.html --self-contained-html

生成的报告如下图所示:

 实例:

#-*-coding:utf-8-*-
'''
V2ex-API接口测试练习
Date:2020-10-10
'''

import requests

class Test_V2ex:
    def setup(self):
        self.base_url = 'https://www.v2ex.com/api'
        self.headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) 
            AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}

    #获取社区信息
    def test_v2ex_info(self):
        self.url =self.base_url + '/site/info.json' 
        response = requests.request('GET',url=self.url,headers=self.headers)
        #断言
        assert response.status_code == 200
    
    #获取热点主题信息
    def test_v2ex_hot(self):
        self.url2 = self.base_url + '/topics/hot.json'
        response2 = requests.request('Get',url=self.url2,headers = self.headers) 
        #断言
        assert response2.status_code == 200
        assert len(response2.json())> 1

    def teardown(self):
        print ("ok")
        

 终端中执行:pytest -s -k Test_V2ex

=========================================================================================================== test session starts ===========================================================================================================
platform win32 -- Python 3.7.1, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: C:UsersAdministratorDesktopHelloworld, configfile: pytest.ini
plugins: allure-pytest-2.8.18, arraydiff-0.3, doctestplus-0.2.0, html-2.1.1, metadata-1.10.0, openfiles-0.3.1, remotedata-0.3.1
collecting ... {'k1': 'v1'}
<class 'dict'>
collected 8 items / 6 deselected / 2 selected                                                                                                                                                                                              

testcases	est_case04.py .ok
.ok
View Code
原文地址:https://www.cnblogs.com/yu2000/p/13852900.html