Pytest - 文件执行



在本章节中,我们将学习如何执行单个测试文件和多个测试文件。我们已经创建了测试文件test_square.py。创建一个包含以下代码的新测试文件test_compare.py

def test_greater():
   num = 100
   assert num > 100

def test_greater_equal():
   num = 100
   assert num >= 100

def test_less():
   num = 100
   assert num < 200

现在,要运行所有文件中的所有测试(此处为 2 个文件),我们需要运行以下命令 −

pytest -v

上述命令将运行test_square.pytest_compare.py中的测试。输出将如下生成 −

test_compare.py::test_greater FAILED
test_compare.py::test_greater_equal PASSED
test_compare.py::test_less PASSED
test_square.py::test_sqrt PASSED
test_square.py::testsquare FAILED
================================================ FAILURES 
================================================
______________________________________________ test_greater 
______________________________________________
   def test_greater():
   num = 100
>  assert num > 100
E  assert 100 > 100

test_compare.py:3: AssertionError
_______________________________________________ testsquare 
_______________________________________________
   def testsquare():
   num = 7
>  assert 7*7 == 40
E  assert (7 * 7) == 40

test_square.py:9: AssertionError
=================================== 2 failed, 3 passed in 0.07 seconds 
===================================

要从特定文件执行测试,请使用以下语法 −

pytest <filename> -v

现在,运行以下命令 −

pytest test_compare.py -v

上述命令将仅从文件test_compare.py执行测试。我们的结果将为 −

test_compare.py::test_greater FAILED
test_compare.py::test_greater_equal PASSED
test_compare.py::test_less PASSED
============================================== FAILURES 
==============================================
____________________________________________ test_greater 
____________________________________________
   def test_greater():
   num = 100
>  assert num > 100
E  assert 100 > 100
test_compare.py:3: AssertionError
================================= 1 failed, 2 passed in 0.04 seconds 
=================================
广告