3

This question is similar to this one, but my directory structure is slightly different and I think that's causing the problem.

My structure is as follows:

project/
    src/
        mypackage/
            module.py
    tests/
        tests_module.py
    pyproject.toml
    setup.cfg
    etc.

The key difference being I have my package in a subdirectory under src/. I've read a few things saying this is good practice as it will essentially "force" you to install the package to test it, just like a user... but that is where I seem to be stuck.

When I try to do my unit test the following happens:

% python -m unittest tests_module
E
======================================================================
ERROR: tests_module (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests_module
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
  File "project/tests/tests_module.py", line 3, in <module>
    from mypackage.module import func
ModuleNotFoundError: No module named 'mypackage'


----------------------------------------------------------------------
Ran 1 test in 0.000s

And here is my tests_module.py file:

import unittest

from mypackage.module import func


class TestCore(unittest.TestCase):

    def test_func(self):
        """
        Test that func returns the parameter it receives
        """
        self.assertEqual(func(1), 1)


if __name__ == '__main__':
    unittest.main()

(the test file might have other problems, it's just a start, but right now I need to fix the import issue).

A few solutions I have found suggest putting something in setup.py that will install the package for this purpose, but I don't have setup.py because I seem to be under the impression that's kind of an "old" way to specify setup information, and I am trying to avoid it.

Any help or advice on best practices greatly appreciated!

Liz C.
  • 101
  • 8

1 Answers1

3

I think I may have found an answer...

I think what I needed to do was install my package in editable form (using python -m pip install -e .)

The tests ran fine after that! I think this is what people meant by "it forces you to install the package to test it."

Liz C.
  • 101
  • 8