Reputation: 2129
I have a project structured like this:
|tools/
|-- test/
| |-- __init__.py
| |-- test_class1.py
| |-- test_class2.py
|
|-- tools/
|-- __init__.py
| |-- class1.py
| |-- class2.py
|
|-- test_runner (Python script that calls unittest.TestLoader().discover('test'))
|-- README.md
I want to run test_runner
and have it execute all the tests in the test
folder. My individual tests would have a line like this: from test_class import TestClass
to test the appropriate class.
test_runner
looks like this:
#!/usr/bin/env python
import unittest
import sys
import os
sys.path.append(os.path.realpath(__file__) + '/tools')
suite = unittest.TestLoader().discover('test')
results = unittest.TextTestRunner(verbosity=2).run(suite)
if len(results.errors) > 0 or len(results.failures) > 0:
sys.exit(1)
sys.exit()
Right now this isn't working, my test files aren't able to import their corresponding classes. I can get it to work if I do export PYTHONPATH=/path/to/file
but I want to get this working through a script.
I also tried sys.path.insert(0, os.path.dirname(__file__) + '/tools')
but that doesn't work because file returns nothing when I use sys.path.insert
.
Upvotes: 1
Views: 3618
Reputation: 386
Just make sure you use absolute imports, by specifying your package name ("tools" in your case). You don't have to modify your system path at all.
For example, with this project structure and by running main.py:
project
main.py
package1
__init__.py
module1.py
package2
__init__.py
module2.py
In module1.py, you should use
from package2 import module2
or
from package2.module2 import myclass
This is absolute import. No need for system path modification
Upvotes: 7