How to publish my unit tests with my python package

Viewed 76

How can I publish my tests along with my package? I want to keep my tests separate from src, as below.

mypackage/
    src/
        mypackage/
            __init__.py
            hello.py
    tests/
        test_hello.py

And the content of my setup.cfg is:

[metadata]
name = mypackage
version = 1.5.0
author = John Henckel
url = https://test.com
[options]
package_dir =
    = src
packages = find:
[options.packages.find]
where = src

However when I do build + twine the tests are not included. Is there a way to include the tests in the tar and wheel?

2 Answers

It appears people put the tests/ folder inside the module directory when they want to distribute them along with the code.

Related SO question.

You can see the project structure they use here.

Edit: This link suggests that you just have to list the directories in your setup.py

    packages=['an_example_pypi_project', 'tests'],

I cannot find anything about setup.cfg though I would imagine it should be the same.

This isn't really a solution, but as a hack I have decided to just copy the tests directory into the src/mypackage (temporarily, just before the build) as part of the continuous integration pipeline. My build pipeline script looks like this:

git clone https://.../mypackage
cd mypackage
pip install pytest -r requirements.txt
pytest
pip install build twine
cp -R tests src/mypackage
python -m build --wheel
twine upload ... dist/*.whl

and this works just fine. After this I can pip install mypackage and run the tests by navigating to the package root (under site-packages) and running pytest.

The pytest documentation says I should also be able to do pytest --pyargs mypackage. But that does not work. I don't know why. Bug in pytest?

Related