import file mismatch in pytest

Question:

I’ve got a file in the package with ‘test’ in its name and when I run pytest I got an error

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

If I remove ‘test’ from the file it works fine but unfortunately I can’t change it.

So the question is how to tell pytest to ignore this file?

Asked By: vZ10

||

Answers:

So finally it was easy, I just had to add test file pattern to the pytest.ini file:

python_files = test_*.py

so pytest stopped looking for files with test in the end of the name what it did by default.

Answered By: vZ10

In my case, it was missing __init__.py file in tests directory.

Answered By: Mateusz

I was facing the same issue even though my file name was not exactly same as other.

I had test_01_login_chrome.py and test_01_login_firefox.py

Error I was getting

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

I tried adding __init__.py to the test cases folder and it did not work.

Then I tried a workaround. I created a python package for my test cases, which created __init__.py by default and then moved my test cases to that folder.

And my issue was resolved.

Answered By: Yatin Bahri

A small variation of this case using the _pytester_ plugin included with _pytest_ (that yields the same error.)

There is a feature of the plugin that allows placement of example tests in your project root (outside of the package), and those tests can be copied into a test temp directory via _pytester.copy_example()_.

This feature can be used as a test loader, and also as a way to test examples.

If you use this feature, you will also want to put an __init__.py into the source directory for your examples.

E.g.: if copying the example from the examples directory:

pytester.copy_example("examples/test_zfs.py")

To avoid the import file mismatch error:

$ touch examples/__init__.py
Answered By: rnickle
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.