pytest 基本使用

`pytest` 是一个流行的 Python 测试框架,它简单、灵活且易于扩展。使用 `pytest`,你可以编写各种类型的测试,包括单元测试、集成测试和功能测试。以下是 `pytest` 的一些基本用法:

安装

首先,你需要安装 `pytest`。可以通过 pip(Python 包管理工具)进行安装:


pip install pytest
 

 编写测试

`pytest` 的测试文件通常以 `test_` 开头,或者以 `_test` 结尾,测试函数通常以 `test_` 开头。例如,你可以创建一个名为 `test_example.py` 的文件,并在其中编写测试函数:


# test_example.py

def add(x, y):
    return x + y

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0
 

运行测试

在命令行中,你可以使用 `pytest` 命令来运行测试:


pytest
 

这将会查找当前目录及其子目录下的所有测试文件,并执行它们。上面的例子中,`test_add` 函数将会被运行,如果 `add` 函数正确实现,测试将会通过。

参数化测试

`pytest` 支持参数化测试,允许你为测试函数提供多组输入和期望的输出。例如:


import pytest

def add(x, y):
    return x + y

@pytest.mark.parametrize("x, y, expected", [(1, 2, 3), (-1, 1, 0), (0, 0, 0)])
def test_add(x, y, expected):
    assert add(x, y) == expected
 

断言

在测试函数中,你可以使用 Python 的 `assert` 语句来验证代码的行为是否符合预期。如果 `assert` 语句失败(即条件为 `False`),测试将被标记为失败。

跳过测试

有时你可能想要跳过某些测试。可以使用 `pytest.mark.skip` 装饰器来跳过整个测试函数,或者使用 `pytest.skip()` 函数在测试函数内部跳过:


import pytest

def test_skipped_function():
    pytest.skip("Skipping this test")
 

设置和拆卸

使用 `setup` 和 `teardown` 方法或者 `@pytest.fixture` 可以进行测试前的设置工作和测试后的清理工作。


import pytest

def setup_module():
    print("Setup for the whole module")

def teardown_module():
    print("Teardown for the whole module")

def test_one():
    assert 1 == 1

def test_two():
    assert 2 == 2
 

插件和扩展

`pytest` 的强大之处在于其插件系统,它允许你扩展 `pytest` 的功能。例如,`pytest-cov` 插件可以用于测试覆盖率报告,`pytest-xdist` 插件可以并行运行测试。

这只是 `pytest` 的一些基本用法。要更深入地了解 `pytest` 的高级特性和配置,建议查阅官方文档:<https://docs.pytest.org/en/stable/>

通过不断地实践,你可以熟练掌握 `pytest`,并在项目中有效地实施测试驱动开发(TDD)或其他测试策略。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值