一、核心概念(对应 unittest)
| unittest | pytest | 核心用法 |
|---|
| TestCase | 测试函数/类 | 函数名以test_开头,类名以Test开头(无__init__) |
| TestSuite | 目录/标记聚合 | 命令行指定文件/目录,或用@pytest.mark标记用例 |
| TestLoader | 内置加载器 | 自动识别test_*.py/Test*/test_*,支持pytest.ini自定义规则 |
| TestRunner | 命令行运行器 | 直接执行pytest命令,搭配参数控制运行逻辑 |
| setUp/tearDown | Fixture | @pytest.fixture()装饰器,支持多作用域复用 |
二、核心语法(代码示例)
1. 测试用例
def test_demo():assert 1 == 1
class TestDemo:def test_case(self):assert "a" in "abc"
2. Fixture
import pytest
@pytest.fixture(scope="module")
def init_fixture():return {"data": [1,2,3]}
def test_use_fixture(init_fixture):assert len(init_fixture["data"]) == 3
3. 断言
def test_assert():assert 5 > 3 assert not [] assert {"k": 1} == {"k": 1} assert "test" in "pytest"
4. 参数化
import pytest
@pytest.mark.parametrize("a, b, res", [(1,2,3), (4,5,9)])
def test_param(a, b, res):assert a + b == res
5. 跳过用例
import pytest
import sys
@pytest.mark.skip(reason="暂不执行")
def test_skip():pass
@pytest.mark.skipif(sys.version_info < (3.8), reason="需Python3.8+")
def test_skipif():pass
三、常用命令
| 功能 | 命令 |
|---|
| 执行所有用例 | pytest |
| 显示详细日志 | pytest -v |
| 停止于第一个失败 | pytest -x |
| 指定文件/类/用例 | pytest 文件名.py::类名::用例名 |
| 生成HTML报告 | pytest --html=报告名.html |
| 运行指定标记用例 | pytest -m 标记名(需用@pytest.mark.标记名装饰用例) |
四、配置文件(pytest.ini)
[pytest]
python_files = test_*.py # 测试文件规则
python_classes = Test* # 测试类规则
python_functions = test_* # 测试函数规则
markers = smoke: 冒烟测试用例demo: 演示用例