如何将 pytest fixture 应用于多个文件

How to have a pytest fixture applied to multiple files

在不将夹具范围设置为 session(过于全局)的情况下将 pytest 夹具应用于多个测试文件的推荐方法是什么?

这是我希望使用的结构:

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

使用 scope='module' 为每个文件重新应用灯具。

我想要以下行为:

  1. 设置 component_1 来自 test_component_1/conftest.py
  2. 的灯具
  3. 运行 component_1 测试
  4. 拆除 component_1 个固定装置
  5. 设置 component_2 来自 test_component_2/conftest.py
  6. 的灯具
  7. 运行 component_2 测试
  8. 拆除 component_2 个固定装置

谢谢!

不使用 scope='session' 就无法将范围扩展到更多模块(文件)。无论如何,将模块的所有测试收集在一个文件中是一种很好的做法。但是如果你有充分的理由这样做,你可以通过重命名

来拆分它
test_feature_1.py --> feature_1_tests.py
test_feature_2.py --> feature_2_tests.py

并建立 test_component_1.py 从这些文件中调用测试。