Skip to content

第 4 课:Pytest——自动化用例就该这么写

fixture + parametrize

一、安装

bash
pip install pytest

二、第一个用例

python
# test_demo.py
def test_true():
    assert True

def test_fail():
    assert 1 == 2  # 这条会失败

运行:pytest test_demo.py -v

pytest 自动发现 test_ 开头的文件和函数。

三、assert 断言

python
assert resp.status_code == 200
assert "成功" in resp.text
assert result["code"] == 200
assert len(items) > 0

四、fixture——前置后置

python
import pytest

@pytest.fixture
def login_token():
    token = login("admin", "123456")
    yield token            # 传给测试函数
    # yield 之后是清理代码

def test_profile(login_token):
    assert login_token is not None

五、parametrize——数据驱动

python
test_data = [
    ("admin", "123456", True),
    ("admin", "wrong", False),
]

@pytest.mark.parametrize("user,pwd,expect", test_data)
def test_login(user, pwd, expect):
    result = login(user, pwd)
    assert result == expect

一条函数自动生成多条用例。

六、常用命令

bash
pytest -v          # 详细
pytest -s          # 显示 print
pytest -x          # 失败就停
pytest -k "login"  # 只跑 login 相关
💬 给清秀留言