博客
关于我
pytest文档25-conftest.py作用范围
阅读量:799 次
发布时间: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/

你可能感兴趣的文章
PyInstaller 构建的 Windows EXE 因多处理而失败
查看>>
Pyinstaller--Windowed或--noconsole.exe不允许打开chromedriver
查看>>
Pyinstaller依赖项的许可证
查看>>
PyInstaller可执行文件找不到包含的flASK-COMPRESS
查看>>
Pyinstaller和海运
查看>>
PyInstaller图标选项在Mac上不起作用
查看>>
pyinstaller的使用
查看>>
pyinstaller超级加密 (加壳和转c)
查看>>
pyinstaller错误:OSError:找不到Python库:libpython3.4mu.so.1.0、libpython3.4m.so.1.0、libpython3.4.so.1.0
查看>>
Pyinstaller:‘;Fiona‘;没有属性‘;_loading‘;(很可能是由于循环导入)
查看>>
pyinstaller:更改应用程序图标
查看>>
Pylint“未解决的导入“;Visual Studio 代码中的错误
查看>>
pyLoad远程代码执行漏洞复现(CVE-2023-0297)
查看>>
pymongo update_one(),upsert=True,不使用$运算符
查看>>
pymongo 中的快速或批量更新
查看>>
pymongo删除操作
查看>>
PyMongo按多个关键点分组
查看>>
Pympress:强大的双屏PDF阅读器
查看>>
pymysql.err.InternalError: (1054, "Unknown column '27D24A3B' in 'where clause'")之错误解决
查看>>
pymysql.err.OperationalError: (1364, “Field ‘id‘ doesn‘t have a default value“)
查看>>