Tidbits | May 21, 2018

Today I Learned – Testing import file mismatch

by Frank Wiles

So over the weekend I was working on adding pytest support to django-test-plus our library which makes testing in Django easier. We of course have tests for our testing library, but have up until now used normal Unittest style tests that we're all familiar with.

Now that I'm adding full pytest support, I needed to have the tests run using pytest rather than Django's normal test runner. In switching I needed pytest itself, pytest-django, and pytest-cov so we could keep track of our test coverage. Which of these caused the problem isn't really important, but what started happening was this:

==================================== ERRORS ====================================
_____________ ERROR collecting .eggs/py-1.5.3-py2.7.egg/py/test.py _____________
import file mismatch:
imported module 'py.test' has this __file__ attribute:
which is not the same as the test file we want to collect:
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

If you don't speak fluent Python, this is just saying that because of some import magic going on the files 'pytest.py' and 'py/test.py' appear to be the same thing to pytest and it's properly bailing out of the test run so you can fix it.

Unfortunately, neither of those are my projects and I didn't have a direct way to fix this. Luckily, I thought of a way around it which was, if we don't generate the bytecode pyc files then it won't see any duplicates.

To do this I just needed to add the following to the project's tox.ini:

   .... lots of other configuration ...

setenv =

Hopefully this helps you sort out odd error message should you run into it when using Travis-CI and tox.

And more importantly, hopefully Google helps me find this page when I completely forget about this and run into it again next year!

Ran into a weird error with coverage, pytest, and Travis today and wanted to document an easy fix when you get a 'import file mistmatch' error from pip packages you do not control.

2018-05-21T09:08:19.474154 2018-05-21T09:08:19.447241 2018