天天看點

解決:ImportError while loading conftest 'e:\virtual_workshop\app_autotest\testcases\conftest.py

之前遇到了很多次類似的問題,即pytest加載conftest.py的時候報如下的錯誤

解決:ImportError while loading conftest 'e:\virtual_workshop\app_autotest\testcases\conftest.py

我的目錄結構是這樣的:

APP_AutoTest/
 |- TestCases/
     |- __init__.py
     |- conftest.py
     |- test_login.py
     |- test_welcome.py      

後來将目錄名改成test_cases,可以正常運作了。testcases也可以,就是不能大寫

pytest官方文檔聲明了conftest.py的存放位置,在我看來有點歧義

​​conftest.py: local per-directory plugins​​中說:

Note

If you have ​

​conftest.py​

​ files which do not reside in a python package directory (i.e. one containing an ​

​__init__.py​

​) then “import conftest” can be ambiguous because there might be other ​

​conftest.py​

​ files as well on your ​

​PYTHONPATH​

​ or ​

​sys.path​

​. It is thus good practice for projects to either put ​

​conftest.py​

​ under a package scope or to never import anything from a ​

​conftest.py​

​ file.

大意是,如果conftest.py放在包的外面,那麼導入conftest的時候可能會産生歧義,因為PYTHONPATH或sys上可能還有别的conftest.py。比如你在test_cases包内定義了一個conftest.py,又在工程目錄下定義了一個conftest.py。是以對項目而言,做好的做法是将conftest.py放在包内或從不導入任何的conftest.py檔案

在​​Plugin discovery order at tool startup​​中說:

Note that pytest does not find ​

​conftest.py​

​ files in deeper nested sub directories at tool startup. It is usually a good idea to keep your ​

​conftest.py​

​ file in the top level test or project root directory.

在pytest啟動時,不會遞歸的去查找子目錄下的conftest.py檔案。建議将conftest.py放在測試包下面或項目根目錄

總結以上内容,有幾點注意:

1. conftest.py最好放在測試包下,測試包的命名以test開頭,不能是大寫

APP_AutoTest/
 |- test_cases/
     |- __init__.py
     |- test_login.py
     |- test_welcome.py
     |- test_demo/
         |- __init__.py
         |- conftest.py