1
votes

I am confused how to structure a project containing a package and a unittest.

I have this directory structure:

TestProject/
├── package
│   ├── constants.py
│   ├── __init__.py
│   ├── package.py
│   └── tests
│       └── test_package.py
└── usage.py

constants.py

A = 1

__init__.py

from .package import give_A

package.py

from .constants import *

def give_A():
    return A

usage.py

from package import give_A

print(give_A())

test_package.py

import unittest
from package import give_A

class Test_package(unittest.TestCase):
    def test_simple(self):
        self.assertEqual(give_A(), 1)

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

Everything works until I try to run the test_package.py module, which understandably cannot import package:

~/Python/TestProject/package/tests $ python3 test_package.py 
Traceback (most recent call last):
  File "test_package.py", line 3, in <module>
    from package import give_A
ImportError: No module named 'package'

However, this seems to be preferred structure of package / tests. How can I make it work? Or should I do it completely differently (structure, directories, imports, test execution...)?

1
try from package.package import give_A? - Holloway
ImportError: No module named package.package. There is no reason why it should work, as package is not in PYTHONPATH, right? - Fenikso
Where are you trying to run the script from? - Holloway
Try running it from the package directory python3 tests/test_package.py - Holloway
from .constants import * ... SystemError: Parent module '' not loaded, cannot perform relative import - Fenikso

1 Answers

0
votes

Either:

  1. Setup your PYTHONPATH such that TestProject is in it.

  2. Run tests using unittest like this:

    ~/Python/TestProject $ python3 -m package.tests.test_package

  3. Use unittest commendline interface:

    ~/Python/TestProject $ python3 -m unittest package/tests/test_package.py

For more information see: https://docs.python.org/3/library/unittest.html#command-line-interface