0

I'd like to have my tests on a module of its own that could be imported, but keeping them outside the src folder and at the same time sharing the namespace with the application module (something like my-module.test.unit) Is it even possible? Am I complicating it too much?

Directory structure:

root/
    src/
        my-module/
    test/
        end-to-end/
        unit/
            helper.py
            test_foo.py
    setup.py

setup.py

setup(
    # ...
    'packages'=['my-module'],
    'package_dir'={'': 'src'}
    # ...
)

Possible options I've figured:

  • Python's Namespace Packages
  • Change setup.py:

    setup(
        # ...
        'packages'=['my-module', 'my-module.test.unit'],
        'package_dir'={
            'my-module': 'src', # doesn't work in editable mode
            'my-module.test.unit': 'test/unit'
        }
        # ...
    )
    
  • Create another setup.py inside the test folder

The rationale is that I have some helper modules in the same folder than the tests (e.g. test/unit/helper.py) and they are imported using absolute imports (e.g. from helper import Helper). There's nothing necessarily wrong in this setup because it works, but hypothetically a new built-in module could shadow any of mine because they take precedence. I believe that relative imports are better because there is no room left for interpretations (explicit is better than implicit). AFAIK, if my tests were a package by themselves I could bring that modules using relative imports (e.g. from .helper import Helper).

In the end it's more a matter of good practices and correctness than a real issue and because of that practicality beats purity also applies ;)

References on this:

Community
  • 1
  • 1
  • What exactly is your motivation for keeping the tests separate? If it's testing-only dependencies that you for example don't want to install when deploying in production, consider using a `[tests`] [extra](https://pythonhosted.org/setuptools/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies). You would then only pull in those dependencies if you install your package with something like `pip install mymodule[tests]`. ([example](https://github.com/4teamwork/ftw.tika/blob/a2868b3a7bcf30ab2187413776810e2e486a2cee/setup.py#L60-L61)) – Lukas Graf Oct 08 '15 at 20:06
  • @LukasGraf I added an explanation of the reasons. I will give a try at the `extras_require` option. –  Oct 09 '15 at 13:41

0 Answers0