Reputation: 941
My folder tree:
project/
app/
__init__.py
models.py
dir/test1.py
dir/__init__.py
run.py
dir/test2.py
dir/__init__.py
If I want to do a
from app.models import Whatever
from test1
and test2
the only thing that works is to manually sys.path.append
something like
os.path.join(os.path.dirname(__file__), "../..")
However there are a ton of answers on SO saying messing up with sys.path
will give me troubles down the line (why?); Sadly, after 1+ hour of googling I still haven't figured out the right way to do import stuff and I'm getting really confused.
Upvotes: 0
Views: 1146
Reputation: 22483
It is enormously better to test than not test, so if you need to append paths to sys.path
to make it work--and in this directory configuration, you will--that's a reasonable and pragmatic step.
However, in general it is better not to fiddle with module load paths manually. It assumes that your code will will always be loaded in a directory right outside your test folder, which might not always be true. But "you will run into problems down the line" is pretty weak tea.
The bigger issue is that you cannot use that little path-patch to accomplish the kind of automated testing and test management you will ultimately want/need. Much better is to learn to use a real test harness / test runner such as pytest or nose. Even better if you also use a macro test runner such as tox. The combination will automatically install your software (including any declared dependencies) in a completely new, pristine virtual environment. This will help you test not just the normal operability of your module, but also its installability. It will also help you easily run tests across different versions of Python with very little additional effort. (I currently test across a range of 2.6, 2.7, 3.2, 3.3, 3.4, 3.5, and several versions of PyPy, for example--not because I use all those versions, but because it doesn't cost me anything extra to make sure my software runs across a large swath of the entire Python universe.)
Fair warning: Setting up your testing environment is a bit of a pill the first time out, requiring a fair amount of effort and learning of "mechanic" skills. But this is a one-time investment that will pay dividends across all of your Python work.
So long story short, patching sys.path
is a fair place to start. But you'll ultimately need more generality, breadth, depth, test fixtures, and automation in your testing--and path patching can't help you with those. Upgrading to real testing tools can.
Upvotes: 1