本文共 1951 字,大约阅读时间需要 6 分钟。
在测试工程中,一个根目录下的 conftest.py 文件通常起到全局作用。为了更灵活地管理测试用例和 fixtures,建议在不同测试子目录中也放置 conftest.py 文件。这种做法的核心原则是,子目录下的 conftest.py 文件只在该层级及以下目录中生效。
假设我们有一个主项目 web_conf_py,其中包含两个子项目 baidu 和 blog。每个子项目下都放置了一个 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
##案例分析
conftest.py# web_conf_py/conftest.pyimport pytest@pytest.fixture(scope="session")def start(): print("\n打开首页") conftest.py 和 test_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"]) conftest.py 和 test_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 目录下,start 和 open_baidu 是 session 级别的 fixture,只会在整个测试会话中运行一次。运行 test_1_baidu.py 可以看到,两个测试用例都顺利通过。
在 blog 目录下,open_blog 是 function 级别的 fixture,每个测试用例都会单独调用一次。test_03 和 test_04 可以正常通过。但 test_05 由于尝试跨模块调用 baidu 模块下的 open_baidu fixture 导致 fixture 未找到,测试用例会失败。
如需进一步了解 pytest 与 selenium 的结合使用,可以参考相关技术文档或实践案例。通过合理配置 fixtures 和 test cases,可以实现更复杂的自动化测试场景。
如需获取更详细的技术内容或实践指南,可以关注我的个人公众号或技术博客,获取更多专业技术资讯。
转载地址:http://znafk.baihongyu.com/