可以将conftest.py文件放在pytest的测试包旁边的另一个包中吗?

时间:2020-06-08 12:38:34

标签: python pytest

问题:
是否可以将 conftest.py 文件放入如下所示结构的测试包旁边的另一个包中?

说明
项目结构如下:
--------------------------------------

GUI_pytest
  - C_lib
      --__init__.py
      -- conftest.py
  - G_test<br/>
      --__init__.py
      -- test_2.py

Source_Root: GUI_pytest
conftest.py: GUI_pytest/C_lib(package)
test_2.py(测试文件): GUI_pytest/G_test(package)

GUI_pytest/C_lib/conftest.py
灯具功能为 def a()

测试用例:GUI_pytest/G_test/test_2.py使用灯具作为 def test_2(a)

我想将conftest.pytest_case().py分为 C_lib package G_test package
< / p>

但是pytest似乎无法拾取conftest.py文件 找不到由 a

使用的灯具功能 def test_2(a) 时出错

先谢谢您
作为初学者,欢迎任何帮助。

1 个答案:

答案 0 :(得分:2)

答案是否定的,没有解决方法是不可能的,我对此建议。

如果使用框架,则应使用框架提供的约定-这使用法更容易,并且不会因框架不期望的某些用法而遇到问题。这里所说的框架是指pytest,它不仅是可执行文件,还因为它提供(并期望)某种基础结构(当然可以更好地进行记录……)。例如,您可以在SO问题In pytest, what is the use of conftest.py files?的答案中找到更多信息。

pytest使用conftest.py文件以分级方式提供测试的固定装置,插件和挂钩。
因此,假设您具有以下结构:

tests
   test_a
       test_a1.py
       test_a2.py
   test_b
       test_b1.py
       test_b2.py   

其中test_a中的测试使用夹具local_fixturetest_b中的测试使用另一个夹具local_fixture,并且所有测试都使用通用夹具common_fixture 。最简单的方法如下:

tests
   conftest.py -> contains common_fixture
   test_a
       conftest.py -> contains local_fixture for test_a...
       test_a1.py
       test_a2.py
   test_b
       conftest.py -> contains local_fixture for test_b...
       test_b1.py
       test_b2.py   

其他模块提供的插件中也可能有conftest.py个文件,您无需导入即可使用所有这些固定装置,也可以做一些PYTHONPATH魔术。您只需遵循通用约定,而不必使用自己的约定才能使用该功能。