Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytests import fails after renaming project folder

Tags:

python

pytest

I've been struggling for a while with renaming a project folder of a Python project. It was called Foo and I want it to rename it to Bar.

Foo/
   /src
        __init__.py
        x.py
   /test
        __init__.py
        x_test.py
   __init__.py

became

Bar/
   /src
        __init__.py
        x.py
   /test
        __init__.py
        x_test.py
    __init__.py

When the project folder was named Foo all my tests passed, but after renaming it to Bar my tests don't work anymore. All imports will raise an ImportError: no module src.x.

I can import the module when I'm using the python console:

$ python
>>> import src.x

When I then rename Bar back to Foo and run the test I'll get this error:

import file mismatch:
imported module 'test.x' has this __file__ attribute:
  /home/orangetux/projects/Foo/test/x_test.py
which is not the same as the test file we want to collect:
  /home/orangetux/projects/Bar/test/x_test.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

I can fix this by removing all __pycache__ folders. But now I'm back at the start. A folder named Foo with working test. How do I rename the project folder to Bar and keep working tests?

like image 934
OrangeTux Avatar asked Jul 31 '13 11:07

OrangeTux


People also ask

Why can't Python find my import?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

How to import Python module from another directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.


1 Answers

Delete the python cache (__pycache__) and all "compiled" files (ie: *.pyc, *.pyo).

Make sure that your __init.py__ files are not referring to any folder or path.

like image 165
Efren Avatar answered Oct 03 '22 02:10

Efren