如何将 pytest 夹具应用于多个文件

Luc*_*cas 5 python fixtures pytest

pytest将固定装置应用于多个测试文件而不将固定装置范围设置为session(太全局化)的推荐方法是什么?

这是我希望使用的结构:

test_component_1/conftest.py
test_component_1/test_feature_1.py
test_component_1/test_feature_2.py

test_component_2/conftest.py
test_component_2/test_feature_1.py
test_component_2/test_feature_2.py
Run Code Online (Sandbox Code Playgroud)

使用scope='module'重新应用每个文件的装置。

我想要以下行为:

  1. 设置 component_1 夹具test_component_1/conftest.py
  2. 运行 component_1 测试
  3. 拆除 component_1 固定装置
  4. 设置 component_2 夹具test_component_2/conftest.py
  5. 运行 component_2 测试
  6. 拆掉 component_2 固定装置

谢谢!

小智 2

如果不使用scope='session'. 无论如何,将模块的所有测试收集在一个文件中是一个很好的做法。但如果你有充分的理由这样做,你可以通过重命名来分割它

test_feature_1.py --> feature_1_tests.py
test_feature_2.py --> feature_2_tests.py
Run Code Online (Sandbox Code Playgroud)

并确定test_component_1.py哪个从这些文件中调用测试。