1.pytest标记
Pytest标记
1、pytest 查找测试策略
默认情况下,pytest会递归查找当前目录下所有以test开始或结尾的python脚本,并执行文件内所有以test开始或者结束的函数和方法。
2、标记测试函数
第一种,显示指定函数名,通过::标记 :test_no_mark.py::test_func1
第二种,使用模糊匹配,使用-k选项标识: pytest test_no_mark.py -k func1
第三种,使用pytest.mark在函数上进行标记: 使用pytest.mark在函数上进行标记
2.pytest显示指定函数名,通过::标记
pytest显示指定函数名,直接输入文件名、类名、方法名进行标记,执行部分测试用例。
核心:pytest.main(['-s','-v','test_mark.py::TestCase'])
例子
import pytest
@pytest.mark.ios
def test_one():
print("one")
@pytest.mark.android
def test_two():
print("two")
@pytest.mark.webtest
def test_three():
print("three")
class TestCase:
def test_four(self):
print("four")
def test_five(self):
print("five")
if __name__ == '__main__':
pytest.main(['-s','-v','test_mark.py::TestCase']) ##通过::的方式直接执行对应的类
#pytest.main(['-s','-v','test_mark.py::TestCase::test_five']) ##通过::的方式直接执行对应方法
返回结果:
test_mark.py::TestCase::test_four four
PASSED
test_mark.py::TestCase::test_five five
PASSED
3.pytest模糊匹配,参数-K标记执行部分测试用例
pytest模糊匹配,参数-k指定类名和方法名进行标记,执行部分测试用例。与::类似
核心:pytest.main(['-s','-v','test_mark.py','-k TestCase'])
import pytest
@pytest.mark.ios
def test_one():
print("one")
@pytest.mark.android
def test_two():
print("two")
@pytest.mark.webtest
def test_three():
print("three")
class TestCase:
def test_four_two(self):
print("four")
def test_five(self):
print("five")
if __name__ == '__main__':
pytest.main(['-s','-v','test_mark.py','-k TestCase or two'])
#pytest.main(['-s','-v','test_mark.py','-k two'])
#pytest.main(['-s','-v','test_mark.py','-k TestCase and two'])
返回结果:
test_mark.py::test_two two
PASSED
test_mark.py::TestCase::test_four_two four
PASSED
test_mark.py::TestCase::test_five five
PASSED
4.pytest.mark函数上标记执行部分测试用例
pytest中的mark标记功能目的是让我们可以执行部分用例。
场景:在不同的环境中,比如linux和windows,只满足测试符合一部分用例。还不如web项目有很多模块,只需要执行一部分模块的内容。或者分平台,使用webtest和andorid、ios环境进行部分用例测试。
解决:使用mark的方式,@pytest.mark.ios
执行:涉及到2个参数,一个是-s和-m参数。
-s: 输出打印所有信息。
-m: 执行自定义标记的部分用例。
核心:pytest.main(['-q','test_mark.py','-m not ios'])
#例子
pytest -s test_01.py
pytest -s test_01.py -m=ios
pytest -s test_01.py -m ios
pytest -s test_01.py -m "not ios"
实例:
执行没有标记ios的用例
import pytest
@pytest.mark.ios
def test_one():
print("one")
@pytest.mark.android
def test_two():
print("two")
@pytest.mark.webtest
def test_three():
print("three")
def test_four():
print("four")
def test_five():
print("five")
if __name__ == '__main__':
pytest.main(['-q','test_mark.py','-m not ios'])
执行结果:
4 passed, 1 deselected, 3 warnings in 0.02s