运行方式
命令行模式
命令行中执行 pytest -s test_login.py
主函数模式
在 test_login.py 文件中增加主函数
if __name__ == '__main__':
pytest.main(["-s", "login.py"]
-s 支持控制台打印
setup和teardown
函数级别
import pytest
class TestLogin:
# 函数级开始
def setup(self):
print("------->setup_method")
# 函数级结束
def teardown(self):
print("------->teardown_method")
def test_a(self):
print("------->test_a")
def test_b(self):
print("------->test_b")
scripts/test_login.py ------->setup_method # 第一次 setup()
------->test_a .
------->teardown_method # 第一次 teardown()
------->setup_method # 第二次 setup()
------->test_b .
------->teardown_method # 第二次 teardown()
类级别
class TestLogin:
# 测试类级开始
def setup_class(self):
print("------->setup_class")
# 测试类级结束
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
def test_b(self):
print("------->test_b")
scripts/test_login.py
------->setup_class # 第一次 setup_class()
------->test_a .
------->test_b .
------->teardown_class # 第一次 teardown_class()
配置文件
[pytest]
# 添加命令行参数
addopts = -s
# 文件搜索路径
testpaths = ./scripts
# 文件名称
python_files = test_*.py
# 类名称
python_classes = Test*
# 方法名称
python_functions = test_*
# 测试报告
addopts = -s --html=report/report.html
addopts = -s
表示命令行参数
testpaths,python_files,python_classes,python_functions
表示 哪一个文件夹 下的 哪一个文件 下的 哪一个类 下的 哪一个函数
表示执行 scripts 文件夹下的 test 开头 .py 结尾的文件下的 Test 开头的类下的 test开头的函
数
控制参数执行顺序
1. 标记于被测试函数,@pytest.mark.run(order=x)
2. 根据order传入的参数来解决运行顺序
3. order值全为正数或全为负数时,运行顺序:值越小,优先级越高
4. 正数和负数同时存在:正数优先级高
import pytest
class TestLogin:
def test_hello_001(self):
print("test_hello_001")
@pytest.mark.run(order=1)
def test_hello_002(self):
print("test_hello_002")
@pytest.mark.run(order=2)
def test_hello_003(self):
print("test_hello_003")
scripts/test_login.py
test_hello_002 # 先运行2
.test_hello_003 # 再运行3
.test_hello_001
失败重试
addopts = -s --reruns 3
跳过测试
import pytest
class TestLogin:
def test_a(self):
# test开头的测试函数
print("------->test_a")
assert 1 # 断言成功
@pytest.mark.skipif(condition=True, reason="xxx")
def test_b(self):
print("------->test_b")
assert 0 # 断言失败
scripts/test_login.py ------->test_a .s
数据参数化
import pytest
class TestLogin:
@pytest.mark.parametrize("name", ["xiaoming", "xiaohong"])
def test_a(self, name):
print(name) assert 1