前言
上一篇简单的介绍了Pytest的安装和运行,我们这篇将介绍Pytes的执行用例的方式和异常。
调用方式
Pytest 调用测试用例执行有多种方式,下面我们就一一介绍:
1.执行指定模块的中的测试用例。
pytest 模块名
1.执行指定目录下所有的测试用例。
pytest 目录名
1.执行文件名、类名或者函数名中包含特定关键字的测试用例。
pytest -k "_class and not two" .
上面的代码就是执行当前目录下,名字包含_class但不包含two的测试用例。
1.执行指定的nodeid的测试用例 pytest为每一个收集到的测试用例指定一个唯一的nodeid。其由模块名+说明符构成,中间以::间隔。其中,说明符可以是类名、函数名以及由parametrize标记赋予的参数。示例如下:有test_node.py文件:
import pytestdef test_one(): print('test_one') assert 1class TestNodeId: def test_one(self): print('TestNodeId::test_one') assert 1 @pytest.mark.parametrize('x,y', [(1, 1), (3, 4)]) def test_two(self, x, y): print(f'TestNodeId::test_two::{x} == {y}') assert x == y
•指定函数名执行
pytest -q -s test_node.py::test_onetest_one.1 passed in 0.02s--------------------------------------------------------------
•指定类名 + 函数名 执行
ytest -q -s test_node.py::TestNodeId::test_oneTestNodeId::test_one.1 passed in 0.03s--------------------------------------------------------------
•指定由parametrize标记赋予的参数执行 (后面章节会会说明parametrize)
pytest -q -s test_node.py::TestNodeId::test_two[1-3]TestNodeId::test_two::1 == 1.1 passed in 0.03s
异常
1.assertpytest允许你使用python标准的assert表达式写断言 如上面例子所示. 同时你也可以为断言指定了一条说明信息,用于失败时的情况说明
def testa(): assert func(5) ==7 , "hahahahahahahahha"test_2.py:5: AssertionError====================================================== short test summary info =======================================================FAILED test_2.py::testa - AssertionError: hahahahahahahahha1 failed in 0.22s
1.pytest.raises()可以使用pytest.raises()作为上下文管理器,来编写一个触发期望异常的断言:(我就预期这里会抛出一个xxx 异常,如果不抛出,还就是不正常的)
import pytestdef myfunc(): raise ValueError("Exception 123 raised")def test_match(): with pytest.raises(ValueError): myfunc()
当用例没有返回ValueError或者没有异常返回时,断言判断失败;ps: 上下文管理器的作用域中,raises代码(myfunc())必须是最后一行,否则,其后面的代码将不会执行
1.不同数据结构比较时的优化
def test_set_comparison(): set1 = set('1308') set2 = set('8035') assert set1 == set2def test_long_str_comparison(): str1 = 'show me codes' str2 = 'show me money' assert str1 == str2def test_dict_comparison(): dict1 = { 'x': 1, 'y': 2, } dict2 = { 'x': 1, 'y': 1, } assert dict1 == dict2
针对一些特殊的数据结构间的比较,pytest对结果的显示做了一些优化:
•集合、列表等:标记出第一个不同的元素•字符串:标记出不同的部分•字典:标记出不同的条目
网友评论