Pytests import fails after renaming project folder

pytest, python

Solution

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.

Problem

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?

Original source