pytest框架介绍(一)

本文介绍了Python的pytest测试框架,它简单灵活、支持参数化,可用于多种测试类型,还有丰富第三方插件。文中给出安装方法和编写测试样例规则,还介绍了5种常用运行模式,包括生成测试报告、运行指定case、多进程运行、重试运行及显示print内容,且多种模式可叠加执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pytest 官方文档:https://docs.pytest.org/en/latest/

python通用测试框架大多数人用的是unittest+HTMLTestRunner,这段时间看到了pytest文档,发现这个框架和丰富的plugins很好用,所以来学习下pytest.

image.png

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

安装pytest:

pip install -U pytest

验证安装的版本:

pytest --version

几个pytest documentation中的例子:

例子1:

import pytest

# content of test_sample.py
def func(x):
    return x + 1
def test_answer():
    assert func(3) == 5

命令行切换到文件所在目录,执行测试(也可以直接在IDE中运行):

 

image.png

这个测试返回一个失败报告,因为func(3)不返回5。

例子2:
当需要编写多个测试样例的时候,我们可以将其放到一个测试类当中,如:

class TestClass:  
    def test_one(self):  
        x = "this"  
        assert 'h' in x  
  
    def test_two(self):  
        x = "hello"  
        assert hasattr(x, 'check') 

运行以上例子:

 

image.png

从测试结果中可以看到,该测试共执行了两个测试样例,一个失败一个成功。同样,我们也看到失败样例的详细信息,和执行过程中的中间结果。-q即-quiet,作用是减少冗长,具体就是不再展示pytest的版本信息。

如何编写pytest测试样例

通过上面2个实例,我们发现编写pytest测试样例非常简单,只需要按照下面的规则:

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 init 方法
  • 测试函数以test_开头
  • 断言使用基本的assert即可

运行模式

   Pytest的多种运行模式,让测试和调试变得更加得心应手,下面介绍5种常用的模式。在介绍之前需要提醒一句,运行pytest时会找当前目录及其子目录中的所有test_*.py 或 *_test.py格式的文件以及以test开头的方法或者class,不然就会提示找不到可以运行的case了。

1.运行后生成测试报告(htmlReport)

安装pytest-html:

pip install -U pytest-html

运行模式:

pytest --html=report.html

报告效果:

 

image.png

 

在以上报告中可以清晰的看到测试结果和错误原因,定位问题很容易。

2.运行指定的case

  当我们写了较多的cases时,如果每次都要全部运行一遍,无疑是很浪费时间的,通过指定case来运行就很方便了。

例子代码:

class TestClassOne(object):
    def test_one(self):
        x = "this"
        assert 't'in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')


class TestClassTwo(object):
    def test_one(self):
        x = "iphone"
        assert 'p'in x

    def test_two(self):
        x = "apple"
        assert hasattr(x, 'check')

运行模式:

模式1:直接运行test_se.py文件中的所有cases:

pytest test_se.py

模式2:运行test_se.py文件中的TestClassOne这个class下的两个cases:

pytest test_se.py::TestClassOne

模式3:运行test_se.py文件中的TestClassTwo这个class下的test_one:

pytest test_se.py::TestClassTwo::test_one

注意:定义class时,需要以T开头,不然pytest是不会去运行该class的。

3.多进程运行cases

  当cases量很多时,运行时间也会变的很长,如果想缩短脚本运行的时长,就可以用多进程来运行。

安装pytest-xdist:

pip install -U pytest-xdist

运行模式:

pytest test_se.py -n NUM

其中NUM填写并发的进程数。

4.重试运行cases

  在做接口测试时,有事会遇到503或短时的网络波动,导致case运行失败,而这并非是我们期望的结果,此时可以就可以通过重试运行cases的方式来解决。

安装pytest-rerunfailures:

pip install -U pytest-rerunfailures

运行模式:

pytest test_se.py --reruns NUM

NUM填写重试的次数。

5.显示print内容

  在运行测试脚本时,为了调试或打印一些内容,我们会在代码中加一些print内容,但是在运行pytest时,这些内容不会显示出来。如果带上-s,就可以显示了。

运行模式:

pytest test_se.py -s

  另外,pytest的多种运行模式是可以叠加执行的,比如说,你想同时运行4个进程,又想打印出print的内容。可以用:

pytest test_se.py -s -n 4



作者:呆呆冬
链接:https://www.jianshu.com/p/932a4d9f78f8
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

### Pytest Framework Detailed Introduction and Overview Pytest is an advanced feature-rich library that makes it easy to write simple and scalable test cases for database applications or web services[^1]. The simplicity of writing unit tests using pytest represents just one aspect; indeed, software testing encompasses multiple dimensions such as integration testing, acceptance testing, and regression testing. #### Key Features of Pytest - **Simplicity**: Writing tests becomes straightforward without requiring boilerplate code. - **Scalability**: Supports both small-scale projects and large systems by providing tools like fixtures which allow setup/teardown operations before running individual tests or groups thereof. - **Extensibility via Plugins**: A rich ecosystem exists around pytest through plugins extending its core functionality. For instance, `pytest-django` integrates seamlessly into Django-based workflows while others support specific databases or reporting formats. ```python import pytest def add(a, b): return a + b @pytest.mark.parametrize( 'a,b,output', [ (2, 3, 5), (-1, 1, 0), (7, -8, -1) ] ) def test_addition_functionality(a, b, output): assert add(a, b) == output ``` This example demonstrates how parametrization allows executing the same function against different inputs efficiently within pytest's framework structure. #### Beyond Unit Tests While starting with basic units provides foundational skills necessary when learning about automated checks in programming languages like Python—it barely scratches surface-level capabilities offered today. Exploring further reveals more sophisticated forms beyond mere verification at method level alone: - Integration Testing ensures components work together correctly after being combined. - Acceptance Testing focuses on validating end-to-end scenarios from user perspective ensuring requirements met satisfactorily. - Regression Testing guarantees changes do not break existing functionalities unexpectedly during development cycles. To deepen understanding regarding these topics specifically tailored towards pythonic implementations consider exploring resources dedicated entirely toward mastering this domain.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值