Pytest 从基本测试开始


现在,我们将从我们的第一个 pytest 程序开始。我们将首先创建一个目录,从而在该目录中创建我们的测试文件。

让我们按照如下所示的步骤进行操作:

  • 创建一个名为的新目录 自动化 并导航到命令行中的目录。

  • 创建一个名为 test_square.py 并将以下代码添加到该文件中。

import math

def test_sqrt():
    num = 25
    assert math.sqrt(num) == 5

def testsquare():
    num = 7
    assert 7*7 == 40

def tesequality():
    assert 10 == 11

使用以下命令运行测试:

pytest

上面的命令会产生如下输出:

test_square.py .F
============================================== FAILURES 
==============================================
______________________________________________ testsquare 
_____________________________________________
    def testsquare():
    num=7
>  assert 7*7 == 40
E  assert (7 * 7) == 40
test_square.py使用以下命令运行测试: AssertionError
================================= 1 failed, 1 passed in 0.06 seconds 
=================================

查看结果的第一行。它显示文件名和结果。 F 代表测试失败,点 (.) 代表测试成功。

在此之下,我们可以看到失败测试的详细信息。它将显示测试失败的语句。在我们的示例中,将 7*7 与 40 进行比较,这是错误的。最后,我们可以看到测试执行摘要,1 个失败,1 个通过。

函数 tesequality 未执行,因为 pytest 不会将其视为测试,因为它的名称不是格式 test* .

现在,执行以下命令,再次查看结果:

pytest -v

-v 增加详细程度。

test_square.py::test_sqrt PASSED
test_square.py::testsquare FAILED
============================================== FAILURES 
==============================================
_____________________________________________ testsquare 
_____________________________________________
    def testsquare():
    num = 7
>  assert 7*7 == 40
E  assert (7 * 7) == 40
test_square.py使用以下命令运行测试: AssertionError
================================= 1 failed, 1 passed in 0.04 seconds 
=================================

现在结果更能说明失败的测试和通过的测试。

注意 : pytest 命令会执行所有格式的文件 test_* or *_test 在当前目录和子目录中。