pytest库

发布时间 2023-07-19 13:05:22作者: enjoyzier

pytest官网文档地址:https//docs.pytest.org
安装pip3 install pytest

1.pytest基本使用

1.1 pytest默认测试用例规则

(1)模块名必须以test_开头或者_test结尾

(2)测试类必须以Test开头,并且不能有ini方法

(3)测试方法必须以test开头

1.2 pytest测试用例运行方式

1.2.1命令行运行

pytest [options] [file_or_dir] [file_or_dir] [...]

(1)测试搜索:pytest搜索测试文件和测试用例的过程称为测试搜索。只要遵守pytest的命名规则,pytest就能自动搜索所有待执行的测试用例。主要的命名规则:

测试文件应当命名为test_<someting>.py或者<someting)_test.py
测试函数、测试类方法应当命名为test_<something>
测试类应当命名为Test<something>
运行pytest时可以指定目录和文件。如果不指定,pytest会搜索当前目录及其子目录中以test_开头或以_test结尾的测试函数。
(2)常用命令行选项:

  • --collect-only 选项可以展示在给定的配置下哪些测试用例会被运行。
  • -k 选项允许你使用表达式指定希望运行的测试用例
  • -m 选项用于标记测试并分组,以便快速选中并运行。当需要同时运行一组测试用例时,我们可以预先使用@pytest.mark.标记名 这样的装饰器来做标记,以下例子使用标记名run_these标记分组,然后使用命令行pytest -v -m run_these,这样有相同标记run_these的测试用例便可以一起运行。
import pytest
@pytest.mark.run_these:
def test_case1():
    pass
@pytest.mark.run_these:
def test_case2():
    pass
View Code

使用-m选项可以用表达式指定多个标记名。
使用-m "mark1 and mark2"可以同时选中带有这两个标记的所有测试用例。
使用-m "mark1 and not mark2"则会选中带有mark1的测试用例,而过滤掉带有mark2的测试用例。
使用-m "mark1 or mark2"则选中带有mark1或者mark2的所有测试用