Pytest测试框架学习笔记

Pytest测试框架学习笔记:从入门到精通

一、Pytest简介

Pytest是Python中最流行的测试框架之一,相比Python自带的unittest框架,Pytest具有以下优势:

特性 unittest pytest
安装方式 无需安装 手动安装
版本管理 无法改变版本 可以指定版本
代码风格 Java语言 Python语言
插件生态 几个插件 1400+插件
维护 Python官方 完全兼容unittest

二、快速上手Pytest

1. 安装与升级

bash

pip install pytest    # 安装
pip install pytest -U # 升级到最新版

2. 启动方式

  1. 命令行:pytest

  2. 代码中:pytest.main()

  3. 通过PyCharm运行(不推荐)

3. 测试结果解读

Pytest测试结果使用简洁的符号表示:

缩写 含义
. 通过(passed)
F 失败(failed)
E 出错(error)
s 跳过(skipped)
X 预期外的通过(xpassed)
x 预期内的失败(xfailed)

三、Pytest用例规则

1. 用例发现规则

  1. 遍历目录(排除venv和.开头的目录)

  2. 查找test_开头或_test结尾的Python文件

  3. 查找Test开头的类

  4. 收集test_开头的函数或方法

2. 用例内容规则

  1. 必须是可调用的(函数、方法、类、对象)

  2. 名称以test_开头

  3. 没有参数(参数有特殊含义)

  4. 没有返回值(默认为None)

3. 示例测试用例

python

def add(a, b):
    return a + b

class TestAdd:
    def test_int(self):
        res = add(1, 3)
        assert res == 4
        
    def test_str(self):
        res = add("1", "3")
        assert res == "13"
        
    def test_list(self):
        res = add([1], [2, 3, 4])
        assert res == [1, 2, 3, 4]

四、Pytest配置

1. 常用命令行参数

  • -v:增加详细程度

  • -s:允许用例中的输入输出

  • -x:遇到失败用例时停止执行

  • -m:用例筛选

2. 配置文件

创建pytest.ini文件进行配置:

ini

[pytest]
addopts = -v -s

五、标记(Mark)的使用

1. 自定义标记

python

@pytest.mark.api
def test_int(self):
    res = add(1, 3)
    assert res == 4

注册标记(在pytest.ini中):

ini

[pytest]
markers =
    api: API测试
    ui: UI测试
    pay: 支付测试

2. 内置标记

  • @pytest.mark.skip:无条件跳过

  • @pytest.mark.skipif:有条件跳过

  • @pytest.mark.xfail:预期失败

  • @pytest.mark.parametrize:参数化

  • @pytest.mark.usefixtures:使用fixtures

六、数据驱动测试

使用参数化实现数据驱动测试:

python

@pytest.mark.ddt
@pytest.mark.parametrize("a,b,c", [
    (1, 1, 2),
    (2, 3, 5),
    (3, 3, 6),
    (4, 4, 8)
])
def test_ddt(self, a, b, c):
    res = add(a, b)
    assert res == c

也可以从外部文件读取测试数据:

python

import csv

def read_csv(file_path):
    with open(file_path) as f:
        return list(csv.reader(f))
        
@pytest.mark.parametrize("a,b,c", read_csv("data.csv"))
def test_csv_data(a, b, c):
    res = add(int(a), int(b))
    assert res == int(c)

总结

Pytest作为Python生态中最强大的测试框架,通过简洁的语法和丰富的插件系统,可以满足从单元测试到复杂集成测试的各种需求。本文介绍了Pytest的基本使用方法,包括安装配置、用例编写、标记系统和数据驱动测试等核心功能。掌握这些内容后,可以大大提高Python项目的测试效率和代码质量。

你可能感兴趣的:(python,pytest)