温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python pytest怎么跑用例

发布时间:2026-10-14 20:40:22 来源:亿速云 阅读:99 作者:小樊 栏目:编程语言

在 Python 中使用 pytest 跑测试用例,一般流程如下:


一、安装 pytest

pip install pytest

验证是否安装成功:

pytest --version

二、编写测试用例

1️⃣ 测试文件命名规则

pytest 默认会找以下文件:

  • test_*.py
  • *_test.py

2️⃣ 测试函数命名规则

  • 测试函数必须以 test_ 开头

示例 test_sample.py:

def test_add():
    assert 1 + 1 == 2

def test_sub():
    assert 3 - 1 == 2

三、运行 pytest

✅ 在当前目录运行所有用例

pytest

✅ 指定测试文件

pytest test_sample.py

✅ 指定某个测试函数

pytest test_sample.py::test_add

✅ 指定目录

pytest tests/

四、常用参数

参数 说明
-v 详细输出
-s 显示 print 内容
-q 安静模式
-x 第一个失败就停止
--maxfail=2 最多失败 2 个
-k "add" 只跑名字包含 add 的用例
--html=report.html 生成 HTML 报告(需插件)

示例:

pytest -v -s
pytest -k "add or sub"

五、使用断言

pytest 使用 Python 原生 assert:

def test_demo():
    assert "hello" in "hello world"

六、测试类(可选)

class TestMath:
    def test_add(self):
        assert 1 + 1 == 2

运行:

pytest test_sample.py::TestMath

七、失败重试(可选插件)

pip install pytest-rerunfailures
pytest --reruns 3

如果你有 具体项目结构 / 想跑接口测试 / UI 测试 / 并行执行,可以告诉我,我可以给你更具体的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手