Python测试框架pytest介绍

一、Pytest简介

Pytest is a mature full-featured Python testing tool that helps you write better programs.The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.

通过官方网站介绍我们可以了解到,Pytest是一个非常成熟的全功能的python测试框架,主要有以下几个特点:

  • 简单灵活易上手
  • 支持参数化
  • 支持简单的单元测试和复杂的功能测试,还可以用来做自动化测试
  • 具有很多第三方插件,并且可以自定义扩展
  • 测试用例的skip和xfail处理
  • 可以很好的和Jenkins集成
  • 支持运行由Nose、UnitTest编写的测试用例

二、Pytest安装

1.直接使用pip命令安装:

1

pip install -U pytest    # -U是如果已安装会自动升级最新版本

2.验证安装结果:

1

2

3

4

pytest --version    # 展示当前安装版本

C:\Users\edison>pytest --version

pytest 6.2.5

3.在pytest测试框架中,要遵循以下约束:

测试文件名要符合test_.py或_test.py格式(例如test_min.py)

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

在单个测试类中,可以包含一个或多个test_开头的函数

三、Pytest测试执行

pytest进行测试比较简单,我们来看一个实例:

1

2

3

4

5

6

7

8

9

10

import pytest    # 导入pytest包

def test_001():    # 函数以test_开头

    print("test_01")

def test_002():

    print("test_02")

if __name__ == '__main__':

    pytest.main(["-v","test_1214.py"])    # 调用pytest的main函数执行测试

这里我们定义了两个测试函数,直接打印出结果,下面执行测试:

1

2

3

4

5

6

7

8

9

10

11

12

============================= test session starts =============================

platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe

cachedir: .pytest_cache

rootdir: D:\Code

collecting ... collected 2 items

test_1214.py::test_001 PASSED                                            [ 50%]

test_1214.py::test_002 PASSED                                            [100%]

============================== 2 passed in 0.11s ==============================

Process finished with exit code 0

输出结果中显示执行了多少条案例、对应的测试模块、通过条数以及执行耗时。

四、测试类主函数

1

pytest.main(["-v","test_1214.py"])

通过python代码执行pytest.main():

直接执行pytest.main() 【自动查找当前目录下,以test_开头的文件或者以_test结尾的py文件】;

设置pytest的执行参数 pytest.main([’–html=./report.html’,‘test_login.py’])【执行test_login.py文件,并生成html格式的报告】。

main()括号内可传入执行参数和插件参数,通过[]进行分割,[]内的多个参数通过‘逗号,’进行分割:

运行目录及子包下的所有用例 pytest.main([‘目录名’])

运行指定模块所有用例 pytest.main([‘test_reg.py’])

运行指定模块指定类指定用例pytest.main([‘test_reg.py::TestClass::test_method’]) 冒号分割

  • -m=xxx: 运行打标签的用例
  • -reruns=xxx:失败重新运行
  • -q: 安静模式, 不输出环境信息
  • -v: 丰富信息模式, 输出更详细的用例执行信息
  • -s: 显示程序中的print/logging输出

–resultlog=./log.txt 生成log

–junitxml=./log.xml 生成xml报告

五、断言方法

pytest断言主要使用Python原生断言方法,主要有以下几种:

  • == 内容和类型必须同时满足相等
  • in 实际结果包含预期结果
  • is 断言前后两个值相等

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import pytest    # 导入pytest包

def add(x,y):    # 定义以test_开头函数

    return x + y

def test_add():

    assert add(1,2) == 3    # 断言成功

str1 = "Python,Java,Ruby"

def test_in():

    assert "PHP" in str1    # 断言失败

if __name__ == '__main__':

    pytest.main(["-v","test_pytest.py"])    # 调用main函数执行测试

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

============================= test session starts =============================

platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe

cachedir: .pytest_cache

rootdir: D:\Code

collecting ... collected 2 items

test_pytest.py::test_add PASSED                                          [ 50%]

test_pytest.py::test_in FAILED                                           [100%]

================================== FAILURES ===================================

___________________________________ test_in ___________________________________

    def test_in():

>       assert "PHP" in str1

E       AssertionError: assert 'PHP' in 'Python,Java,Ruby'

test_pytest.py:11: AssertionError

=========================== short test summary info ===========================

FAILED test_pytest.py::test_in - AssertionError: assert 'PHP' in 'Python,Java...

========================= 1 failed, 1 passed in 0.18s =========================

Process finished with exit code 0

可以看到运行结果中明确指出了错误原因是“AssertionError”,因为PHP不在str1中。

六、常用命令详解

1.运行指定案例:

1

2

if __name__ == '__main__':

    pytest.main(["-v","-s","test_1214.py"])

2.运行当前文件夹包括子文件夹所有用例:

1

2

if __name__ == '__main__':

    pytest.main(["-v","-s","./"])

3.运行指定文件夹(code目录下所有用例):

1

2

if __name__ == '__main__':

    pytest.main(["-v","-s","code/"])

4.运行模块中指定用例(运行模块中test_add用例):

1

2

if __name__ == '__main__':

    pytest.main(["-v","-s","test_pytest.py::test_add"])

5.执行失败的最大次数

使用表达式"–maxfail=num"来实现(注意:表达式中间不能存在空格),表示用例失败总数等于num 时停止运行。

6.错误信息在一行展示。

在实际项目中如果有很多用例执行失败,查看报错信息将会很麻烦。使用"–tb=line"命令,可以很好解决这个问题。

七、接口调用

本地写一个查询用户信息的接口,通过pytest来调用,并进行接口断言。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

 # -*- coding: utf-8 -*-

 import pytest

 import requests

  

 def test_agent():

     r = requests.post(

         url="http://127.0.0.1:9000/get_user",

         data={

             "name": "吴磊",

            "sex": 1

        },

        headers={"Content-Type": "application/json"}

    )

    print(r.text)

    assert r.json()['data']['retCode'] == "00" and r.json()['data']['retMsg'] == "调用成功"

if __name__ == "__main__":

    pytest.main(["-v","test_api.py"]) 

​现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:485187702【暗号:csdn11】

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】

  • 21
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python测试框架pytest是一个功能强大且易于使用的测试工具。它可以帮助我们编写和运行测试用例,并提供了丰富的功能和灵活的配置选项。根据引用\[1\]和引用\[2\]的内容,我们可以看到pytest的一些基本用法和规则。 首先,我们可以在一个.py文件中定义多个测试用例类,每个类中可以包含多个测试方法。测试方法以test_开头,并且可以使用assert语句来断言测试结果是否符合预期。例如,引用\[1\]中的示例代码定义了一个TestClass类,其中包含了三个测试方法test_one、test_two和test_a。 其次,pytest可以自动发现和执行测试用例。根据引用\[3\]的内容,pytest会在以test_开头的py文件中查找以test_开头的函数和以Test开头的类,并执行其中以test_开头的方法。我们可以使用pytest命令来运行测试用例,例如pytest test.py可以执行test.py文件中的所有测试用例。 此外,pytest还提供了fixture机制,可以用于在测试用例之前或之后执行一些准备工作或清理工作。fixture可以在测试方法中通过参数的方式进行使用。具体的fixture用法可以参考pytest的官方文档。 综上所述,pytest是一个功能强大且易于使用的Python测试框架,可以帮助我们编写和运行测试用例。它具有灵活的配置选项和丰富的功能,可以满足不同的测试需求。如果你想学习更多关于pytest的内容,可以查阅官方文档或参考相关教程。 #### 引用[.reference_title] - *1* *2* *3* [python pytest测试框架(一)](https://blog.csdn.net/yxxxiao/article/details/94591174)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值