📜  pytest 安装窗口 - Python (1)

📅  最后修改于: 2023-12-03 14:45:52.995000             🧑  作者: Mango

pytest 安装窗口 - Python

pytest是一个测试框架,可用于编写单元测试和功能测试。它是Python的一个快速,简单和易用的测试工具。

安装

可以使用pip在命令行中安装pytest:

pip install pytest
如何使用

创建一个测试文件,例如test_sample.py,并添加几个测试:

def inc(x):
    return x + 1

def test_answer():
    assert inc(4) == 5

使用命令行运行测试程序:

pytest

输出应该类似于下面的内容:

============================= test session starts ==============================
collected 1 item

test_sample.py F                                                     [100%]

=================================== FAILURES ===================================
_________________________________ test_answer __________________________________

    def test_answer():
>       assert inc(4) == 5
E       assert 5 == 5
E        +  where 5 = inc(4)

test_sample.py:5: AssertionError
=========================== short test summary info ============================
FAILED test_sample.py::test_answer - assert 5 == 5
========================= 1 failed in 0.12s ====================================

这表明我们的测试失败了。 现在让我们更改测试和功能,以便它成功:

def inc(x):
    return x + 1

def test_answer():
    assert inc(3) == 4

再次运行pytest并查看输出:

============================= test session starts ==============================
collected 1 item

test_sample.py .                                                     [100%]

============================== 1 passed in 0.12s ===============================

我们的测试现在成功了!

总结

pytest是一个易学易用的测试框架,安装很简单。它提供了丰富的功能来编写各种类型的测试。如果您想使用Python进行测试,那么pytest是一个很好的选择。