pytest 使用教程(一):入门与基础规则

前言

pytest 是 Python 生态中最流行的测试框架之一,相比内置的 unittest,它语法更简洁、插件生态丰富、报错信息清晰。本系列教程将从零开始,带你系统掌握 pytest 的核心用法。


pytest 基本规则

pytest 通过约定优于配置的方式自动发现测试,遵守以下命名规则即可:

对象 命名规则 示例
测试文件 test_ 开头 或 _test 结尾 test_login.py
测试类 Test 开头,且不能有 __init__ 方法 class TestLogin:
测试函数 test_ 开头 def test_login_success():

注意:测试类不需要继承任何基类,这是 pytest 与 unittest 的重要区别之一。


第一个 pytest 示例

# test_demo.py

class TestCase001:
    def sum(self, x):
        """辅助方法:将输入值加 3"""
        return x + 3

    def test_001(self):
        """测试 sum(1) 应等于 4"""
        assert self.sum(1) == 4

    def test_002(self):
        """测试 sum(2) 应等于 5"""
        assert self.sum(2) == 5
运行方式
方式一:IDE 右键运行
在 PyCharm 中,右键点击测试文件或测试方法,选择 Run 'pytest in ...' 即可。

方式二:main 方法运行
import pytest

if __name__ == "__main__":
    # 运行指定文件,-v 详细输出,-s 显示 print/logging
    pytest.main(["-v", "-s", "./test_demo.py"])

    # 运行指定模块
    pytest.main(["./TestCase/test_demo.py"])

    # 运行类中的指定用例
    pytest.main(["./TestCase/test_demo.py::TestCase001::test_001"])

    # 匹配包含关键词的用例(-k 参数)
    pytest.main(["-k", "001", "./TestCase/test_demo.py"])
方式三:命令行运行
# 基础运行
pytest test_demo.py

# 详细输出 + 显示 print
pytest -s -v test_demo.py

# 只运行包含关键词的用例
pytest -k "001" test_demo.py
常用命令与插件
# 只收集用例,不执行
pytest --collect-only

# 只重跑上次失败的用例(无失败则全跑)
pytest --last-failed

# 失败重跑 N 次(需安装 pytest-rerunfailures)
pip install pytest-rerunfailures
pytest test_demo.py --reruns 2

# 多进程并行运行(需安装 pytest-xdist)
pip install pytest-xdist
pytest test_demo.py -n 2

# 循环运行用例 N 次(需安装 pytest-repeat)
pip install pytest-repeat
pytest test_demo.py -s --count=2

# 循环运行,遇到失败立即停止
pytest test_demo.py -s --count=2 -x

# 按 mark 标记运行(下一章详细介绍)
pytest test_demo.py -m "smoke"
小结
本章介绍了 pytest 的基本命名规则、第一个测试示例以及三种运行方式。下一章将介绍 pytest 的 fixture 机制,这是 pytest 最强大的特性之一。
posted @ 2021-08-08 13:27  老猎人-note  阅读(119)  评论(0)    收藏  举报