Reputation: 905
I'm currently working on a project whose structure is:
my_package
│ README.md
| setup.py
│
└───my_package
| | __init__.py
│ │ file1.py
│ │ file2.py
| | ...
│ └───subpackage
│ │ sub1.py
│ │ ...
│
└───test
| __init__.py
│ test_file1.py
| test_file2.py
I can run all my tests with python -m unittest discover -s test
. Most of test_x.py
files contain imports such as from my_package.file1 import Something
. Hence, the unittest
command will run all my tests against source code contained in my_package
.
On the other hand, I created a private Pypi package from this package. In my CI, I would like to run my unit tests against installed files, rather than local source code.
import my_package.file1; print(my_package.file1.__file__)
should then show a path to site-packages
.
Is there a way to do so ?
Edit: I would like to keep my test folder separate from my_package
folder as I do not intend to distribute my tests.
Upvotes: 2
Views: 1465
Reputation: 16737
To run discovery-tests against installed package do next thing:
Inside your package's directory ./test/
add file run.py
with the following content:
import os, unittest
def load_tests(loader, standard_tests, pattern):
this_dir = os.path.dirname(__file__)
pattern = pattern or "test_*.py"
top_level_dir = os.path.dirname(os.path.dirname(this_dir))
package_tests = loader.discover(
start_dir = this_dir, pattern = pattern, top_level_dir = top_level_dir,
)
standard_tests.addTests(package_tests)
return standard_tests
if __name__ == '__main__':
unittest.main()
Then running tests will be just as easy as python -m your_package.test.run
.
If you want you can place run.py
into your root directory, then just replace this_dir = os.path.dirname(__file__)
with this_dir = os.path.dirname(__file__) + '/test/'
. Then run tests through python -m your_package.run
.
Upvotes: 3