在实际操作中,会遇到只想只想某条某些用例的场景,这时候就用到了pytest的标记函数
第一种,显式指定函数名,通过 :: 标记。
场景:执行test_01这条用例
pytest test_01.py::test_01
第二种,使用模糊匹配,使用 -k 选项标识。
场景:执行用例名称中含有“raise”的用例
pytest -k "raise" test_01.py
以上两种方法,第一种一次只能指定一个测试函数,当要进行批量测试时无能为力;第二种方法可以批量操作,但需要所有测试的函数名包含相同的模式,也不方便。
第三种,使用 pytest.mark 在函数上进行标记。
使用 mark,我们可以给每个函数打上不同的标记,测试时指定就可以允许所有被标记的函数。
一个函数可以打多个标记;多个函数也可以打相同的标记。
场景:执行带有unfinished标记的用例
pytest -m "unfinished" test_01.py
# -*- coding: utf-8 -*-
"""
@author: mily
@time: 2021/8/21 16:19
@desc:
"""
import pytest
def test_01():
print("打印结果")
assert (1, 2, 3) == (1, 2, 3)
def test_02():
print("打印结果")
assert (1, 2, 3) == (1, 2, 1)
@pytest.mark.finished
def test_raise_03():
with pytest.raises(ZeroDivisionError) as e:
res = 1 / 0
exec_meg = e.value.args[0]
print(exec_meg)
assert exec_meg == "division by zero"
@pytest.mark.unfinished
def test_raise_04():
with pytest.raises(TypeError) as e:
a = 1 + "1"
exec_msg = e.value.args[0]
print(exec_msg)
assert exec_msg == "unsupported operand type(s) for +: 'int' and 'str'"