pytest中导入文件不匹配

时间:2018-12-24 22:25:56

标签: python pytest pytest-cov

我的包中有一个文件,文件名为'test',运行pytest时出现错误

import file mismatch:
imported module 'my_project.my_file_test' has this __file__ attribute:
  /my_project/src/my_project/build/lib/python2.7/site-packages/foo/my_file_test.py
which is not the same as the test file we want to collect:
  /my_project/src/my_project/build/private/python2.7/lib/foo/my_file_test.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

如果我从文件中删除“测试”,它可以正常工作,但是很遗憾,我无法更改它。

所以问题是如何告诉pytest忽略此文件?

3 个答案:

答案 0 :(得分:5)

就我而言,它在测试目录中缺少__init__.py文件。

答案 1 :(得分:0)

所以最后很容易,我只需要向pytest.ini文件添加测试文件模式

python_files = test_*.py

因此pytest停止了使用名称默认末尾的test结尾的文件。

答案 2 :(得分:0)

即使我的文件名与其他文件名不完全相同,我也遇到了同样的问题。

我有test_01_login_chrome.pytest_01_login_firefox.py

我得到的错误

import file mismatch:
imported module 'test_01_login_chrome.py' has this __file__ attribute:
  /Users/avicii/PycharmProjects/Omni_Sanity/TestCase/Firefox_TestCases/test_01_login_chrome.py
which is not the same as the test file we want to collect:
  /Users/avicii/PycharmProjects/Omni_Sanity/TestCase/01_Chrome_TestCases/test_01_login_chrome.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

我尝试将__init__.py添加到测试用例文件夹中,但没有用。

然后我尝试了一种解决方法。我为测试用例创建了一个python包,默认情况下会创建__init__.py,然后将测试用例移至该文件夹。

我的问题已解决。