之前遇到了很多次类似的问题,即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 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开头,不能是大写
2. conftest.py不能放在测试包的子目录下,比如这样:
APP_AutoTest/
|- test_cases/
|- __init__.py
|- test_login.py
|- test_welcome.py
|- test_demo/
|- __init__.py
|- conftest.py