I have the following:
ModuleFolder
|
|-->. ModuleFile.py .
|
\'-->. TestsFolder .
Make your test folder a module (by adding __init__.py).
Then you can use run python -m tests.test_name
or use the following Makefile in your project home:
TEST_FILES = $(wildcard tests/test_*.py)
TESTS = $(subst .py,,$(subst /,.,$(TEST_FILES)))
all.PHONY: test
test:
@- $(foreach TEST,$(TESTS), \
echo === Running test: $(TEST); \
python -m $(TEST); \
)
You can also make symlink of the module path which you want to import and then use that symlink to import. Create a symlink in the python dist-packages.
To create a symlink:
ln -s "/path/to/ModuleFolder" "/path/to/python/dist/packages/module_symlink_name"
To import module in the script:
from module_symlink_name import ModuleFile
No need to export python path or modifying sys path.
Don't run the test from the tests folder. Run it from the root of your project, which is the module folder. You should very rarely need to muck with either sys.path
or PYTHONPATH
, and when you do, you're either causing bugs for other libraries down the road or making life harder on your users.
python -m TestsFolder.UnitTest1
If you use a test runner like py.test, you can just run py.test
from the root of your checkout and it'll find the tests for you. (Assuming you name your tests something more like test_unit1.py
. Your current naming scheme is a little unorthodox. ;))
It's better to insert your relative path at the begening of sys.path
like this:
import sys
sys.path.insert(0, '../')
My suggestion is:
Don't try to be clever, do what you're supposed to do. I.e. make sure that your modules and packages are somewhere in your Python path.
The simplest way is to set the environment variable PYTHONPATH in the shell that you use to execute your scripts:
$ export PYTHONPATH=/the/directory/where/your/modules/and/packages/are
$ cd /the/directory/where/your/unit/tests/are
$ python test1.py