Python import from parent directory
Python import from parent directory
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001
--
Chapters
00:00 Question
02:36 Accepted answer (Score 29)
03:23 Answer 2 (Score 5)
03:39 Answer 3 (Score 2)
04:05 Answer 4 (Score 2)
04:32 Thank you
--
Full question
https://stackoverflow.com/questions/1966...
Question links:
[SO Question1]: https://stackoverflow.com/questions/8951...
[SO Question2]: https://stackoverflow.com/questions/3265...
[Every Other SO Question]: https://stackoverflow.com/search?
Accepted answer links:
[py.test]: http://pytest.org/latest/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 29
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. ;))
ANSWER 2
Score 5
It's better to insert your relative path at the begening of sys.pathlike this:
import sys
sys.path.insert(0, '../')
ANSWER 3
Score 2
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
ANSWER 4
Score 2
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); \
)