1

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...)?

Fenikso
  • 9,251
  • 5
  • 44
  • 72

1 Answers1

0

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

Fenikso
  • 9,251
  • 5
  • 44
  • 72
Bernhard
  • 8,583
  • 4
  • 41
  • 42
  • I get `SystemError: Parent module '' not loaded, cannot perform relative import` if I try relative import. Adding to `PYTHONPATH` works, but is that common practice? – Fenikso Dec 21 '15 at 13:52
  • See http://stackoverflow.com/questions/16981921/relative-imports-in-python-3 either you set PYTHONPATH or you need to run with python -m package.tests.test_package. – Bernhard Dec 21 '15 at 14:01
  • That works. Do people expect to run tests like that? Or do people include shell script to run tests? – Fenikso Dec 21 '15 at 14:08
  • The documentation suggest to run tests with the unittest command line interface: https://docs.python.org/3/library/unittest.html#command-line-interface. Not sure if that's applicable and works with your example without further tweaks. – Bernhard Dec 21 '15 at 15:15
  • Cool! I have missed that. – Fenikso Dec 21 '15 at 16:36