博客
关于我
pytest文档25-conftest.py作用范围
阅读量:800 次
发布时间:2023-03-05

本文共 1951 字,大约阅读时间需要 6 分钟。

conftest.py在测试工程中的应用与层级关系优化

在测试工程中,一个根目录下的 conftest.py 文件通常起到全局作用。为了更灵活地管理测试用例和 fixtures,建议在不同测试子目录中也放置 conftest.py 文件。这种做法的核心原则是,子目录下的 conftest.py 文件只在该层级及以下目录中生效。

conftest层级关系示例

假设我们有一个主项目 web_conf_py,其中包含两个子项目 baidublog。每个子项目下都放置了一个 conftest.py 文件和一个 __init__.py 文件(为了确保每个包都有初始化文件)。结构如下:

web_conf_py├── baidu│   ├── conftest.py│   ├── test_1_baidu.py│   └── __init__.py└── blog    ├── conftest.py    ├── test_2_blog.py    └── __init__.py

##案例分析

web_conf_py根目录下的 conftest.py

# web_conf_py/conftest.pyimport pytest@pytest.fixture(scope="session")def start():    print("\n打开首页")

baidu目录下的 conftest.pytest_1_baidu.py

# web_conf_py/baidu/conftest.pyimport pytest@pytest.fixture(scope="session")def open_baidu():    print("打开百度页面_session")
# web_conf_py/baidu/test_1_baidu.pyimport pytestdef test_01(start, open_baidu):    print("测试用例test_01")    assert 1def test_02(start, open_baidu):    print("测试用例test_02")    assert 1if __name__ == "__main__":    pytest.main(["-s", "test_1_baidu.py"])

blog目录下的 conftest.pytest_2_blog.py

# web_conf_py/blog/conftest.pyimport pytest@pytest.fixture(scope="function")def open_blog():    print("打开blog页面_function")
# web_conf_py/blog/test_2_blog.pyimport pytestdef test_03(start, open_blog):    print("测试用例test_03")    assert 1def test_04(start, open_blog):    print("测试用例test_04")    assert 1def test_05(start, open_baidu):    '''跨模块调用baidu模块下的conftest'''    print("测试用例test_05, 跨模块调用baidu")    assert 1if __name__ == "__main__":    pytest.main(["-s", "test_2_blog.py"])

测试结果分析

  • baidu 目录下,startopen_baidu 是 session 级别的 fixture,只会在整个测试会话中运行一次。运行 test_1_baidu.py 可以看到,两个测试用例都顺利通过。

  • blog 目录下,open_blog 是 function 级别的 fixture,每个测试用例都会单独调用一次。test_03test_04 可以正常通过。但 test_05 由于尝试跨模块调用 baidu 模块下的 open_baidu fixture 导致 fixture 未找到,测试用例会失败。

pytest与selenium自动化结合实践

如需进一步了解 pytest 与 selenium 的结合使用,可以参考相关技术文档或实践案例。通过合理配置 fixtures 和 test cases,可以实现更复杂的自动化测试场景。

关注与购买

如需获取更详细的技术内容或实践指南,可以关注我的个人公众号或技术博客,获取更多专业技术资讯。

转载地址:http://znafk.baihongyu.com/

你可能感兴趣的文章
pytest简介及jenkins集成
查看>>
Pytest自动化框架运行全局配置文件pytest.ini
查看>>
pytest自动化测试-Git中的测试用例运行
查看>>
Pytest自动化测试-简易入门教程(01)
查看>>
Pytest自动化测试-简易入门教程(02)
查看>>
Pytest自动化测试-简易入门教程(03)
查看>>
Pytest自动化测试指定执行测试用例
查看>>
Pytest自动化测试框架 fixture 传参实战
查看>>
pytest自动化测试框架pytest.ini配置文件详细
查看>>
Pytest自动化测试框架介绍
查看>>
Pytest自动化测试框架,建议收藏。
查看>>
Pytest自动化测试框架:mark用法---测试用例分组执行
查看>>
PyTorch 1.0 中文官方教程:强化学习 (DQN) 教程
查看>>
pytest:4种方法实现 - 重复执行用例 - 展示迭代次数
查看>>
Pytest:一个卓有成效的测试工具
查看>>
python
查看>>
Python "HTTP Error 403: Forbidden"
查看>>
python %ns的作用
查看>>
Python + Appium 之 APP 自动化测试,坑点汇总!(建议收藏)
查看>>
Python + Appium 自动化操作微信入门(超详细)
查看>>