使用pytest单元测试框架执行单元测试

Pytest 是一个功能强大且灵活的 Python 单元测试框架,它使编写、组织和运行测试变得更加简单。以下是 Pytest 的一些主要特点和优点:

简单易用:Pytest 提供了简洁而直观的语法,使编写测试用例变得非常容易。它支持使用 assert 语句进行断言,并提供了丰富的断言方法来验证测试结果。

自动发现测试用例:Pytest 能够自动发现和执行目录中的测试文件和测试函数。只需将测试文件命名为以 test_ 开头的文件,Pytest 就能够识别并执行其中的测试用例。

丰富的插件生态系统:Pytest 拥有丰富的插件生态系统,可以通过插件扩展其功能。这些插件可以用于生成报告、测试覆盖率、参数化测试等方面。

参数化测试:Pytest 支持使用 @pytest.mark.parametrize 装饰器来实现参数化测试,使得可以在一个测试函数中运行多个测试案例。

支持夹具(fixtures):夹具是一种在测试之前或之后执行的代码片段,用于准备测试环境或清理测试后的状态。Pytest 提供了强大的夹具功能,可以通过函数级别或模块级别来使用。

丰富的报告输出:Pytest 生成详细的测试报告,包括测试用例的结果、失败原因、执行时间等信息。这些报告可以帮助开发人员更轻松地诊断和修复问题。

Pytest 是一个灵活、简单且功能丰富的单元测试框架,适用于各种规模的项目,并且具有广泛的社区支持和文档资源。

下午我们举5个简单的pytest框架进行测试的实际案例:

1.测试一个简单的函数

复制代码
# 文件名:test_example.py

def add(x, y):
    return x + y

def test_add():
    assert add(1, 2) == 3
    assert add(5, 5) == 10

2.测试一个类的方法

复制代码
# 文件名:test_calculation.py

class Calculator:
    def add(self, x, y):
        return x + y

def test_calculator_add():
    calc = Calculator()
    assert calc.add(2, 3) == 5
    assert calc.add(5, 5) == 10

3.测试一个模块的功能

复制代码
# 文件名:test_strings.py

def test_uppercase():
    assert 'hello'.upper() == 'HELLO'

def test_split():
    s = 'hello world'
    assert s.split() == ['hello', 'world']

4.测试异常情况

复制代码
# 文件名:test_exceptions.py

def divide(x, y):
    if y == 0:
        raise ValueError("Cannot divide by zero")
    return x / y

def test_divide():
    with pytest.raises(ValueError):
        divide(10, 0)

5.测试使用参数化

复制代码
# 文件名:test_parametrize.py
import pytest

def add(x, y):
    return x + y

@pytest.mark.parametrize("x, y, expected", [(1, 2, 3), (5, 5, 10), (10, -5, 5)])
def test_add(x, y, expected):
    assert add(x, y) == expected

把以上几个程序文件分别存到指定的目录下,cmd进入到此目录,然后执行pytest即可执行这5个测试文件。测试结果如下:

希望以上的实例可以让大家对pytest单元测试框架有个基本的理解。

相关推荐
2601_962078192 小时前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
ChampaignWolf1 天前
Joule Unit Test 深度集成:ABAP 单元测试的 AI 六件套全解析
人工智能·单元测试·sap·abap·joule·单元测试ai
川石课堂软件测试1 天前
涨薪技术|Prometheus之HTTP API中使用PromQL
网络协议·测试工具·jmeter·http·单元测试·postman·prometheus
2601_962284502 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962300812 天前
基于pytest的接口自动化测试:使用requests模块的实战项目与接口关联方法详解
接口自动化测试·测试用例·pytest·接口关联·requests模块
半亩码田2 天前
C#转Python第4.5篇:单元测试:pytest vs xUnit/NUnit
python·单元测试·c#
2601_962300812 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
AINative软件工程2 天前
LLM 应用的测试替身工程实践:用 Fake/Stub/Mock 让 AI 代码真正跑起来 CI
单元测试·llm·ai编程
Java小白笔记2 天前
Java 单元测试怎么写:JUnit 5、Mockito 与 Spring Boot 方法级实战
java·junit·单元测试
11路没有终点3 天前
Pytest 安装、版本与第一个测试用例
测试用例·pytest