目录
使用场景
- 多个.py文件调用的公共功能可抽取出来,写成配置文件形式读取confest.py的配置
代码示例
confest.py文件
# -*- coding: utf-8 -*-
# @Time : 2021/10/9
# @Author : 大海
import pytest
"""
注意以下3点:
conftest.py配置脚本名称是固定的,不能改名称
conftest.py与运行的用例要在同一个pakage下,并且有__init__.py文件
不需要import导入 conftest.py,pytest用例会自动查找
"""
@pytest.fixture()
def open_url():
print("打开网址!")
注意:
- conftest.py配置脚本名称是固定的,不能改名称
- conftest.py与运行的用例要在同一个pakage下,并且有__init__.py文件
- 不需要import导入 conftest.py,pytest用例会自动查找
test_05.py
# -*- coding: utf-8 -*-
# @Time : 2021/10/9
# @Author : 大海
import pytest
def test_login(open_url):
print('这是登录成功case')
def test_other():
print('这是未登录状态case')
if __name__ == '__main__':
pytest.main(["-s", "test_05.py"])
test_06.py
# -*- coding: utf-8 -*-
# @Time : 2021/10/9
# @Author : 大海
import pytest
def test_login(open_url):
print('这是登录成功test_06')
def test_other():
print('这是未登录状态case')
if __name__ == '__main__':
pytest.main(["-s", "test_06.py"])
说明:运行上面两个文件,都可以调用到open_url方法,这样就实现抽取公共方法
本文介绍了如何在 Pytest 中使用 conftest.py 文件来抽取公共功能,作为多个测试用例共享的配置。conftest.py 文件必须放在测试用例所在的包内,并包含 __init__.py 文件。示例中展示了如何定义一个 fixture 函数 `open_url`,该函数在 test_05.py 和 test_06.py 测试用例中被调用,实现了公共方法的复用。
3943

被折叠的 条评论
为什么被折叠?



