之前遇到了很多次類似的問題,即pytest加載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 otherconftest.py
files as well on yourPYTHONPATH
orsys.path
. It is thus good practice for projects to either putconftest.py
under a package scope or to never import anything from aconftest.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 yourconftest.py
file in the top level test or project root directory.
在pytest啟動時,不會遞歸的去查找子目錄下的conftest.py文件。建議將conftest.py放在測試包下面或項目根目錄
總結以上內容,有幾點注意:
1. conftest.py最好放在測試包下,測試包的命名以test開頭,不能是大寫
2. conftest.py不能放在測試包的子目錄下,比如這樣:
APP_AutoTest/ |- test_cases/ |- __init__.py |- test_login.py |- test_welcome.py |- test_demo/ |- __init__.py |- conftest.py