Max Spencer
Max Spencer

Reputation: 1719

How do I import a module from a parent directory? (unittest purposes)

I have just finished writing the core section of a project I am working on and I want to write test for it using unittest before I continue. I am aware that I should have done this before, but when I started I didn't know Python, so.. whatever..

What I would like to achieve: I have a sub-package of the main package which contains all the modules I want to test inside it. I want to put a subsubpackage inside that called 'tests' or something which then contains all of my test cases, which I'd like to be able to aggregate into a test suite from outside the package so eventually I can run all the test for the entire project in one go.

The structure is something like this:

/projectPackage
/projectPackage/package
/projectPackage/package/\__init__.py (empty)
/projectPackage/package/someModule.py
/projectPackage/package/... (more modules)
/projectPackage/package/testing.py (runs all the tests in /tests/)
/projectPackage/package/tests
/projectPackage/package/tests/\__init__.py (empty)
/projectPackage/package/tests/someModuleTests.py

Problem I am having:

someModuleTests has to import someModule from the parent package so it can test its methods. This doesn't seem to work. I get various errors like:

Attempted relative import beyond toplevel package

Anyway, I expect it's just because I am a Python noob! I have my own ideas on how I am going to do it for this project, because of course each is different, but any general advice on the structuring of medium-large python projects is also appreciated.

Upvotes: 22

Views: 19457

Answers (3)

Yan Foto
Yan Foto

Reputation: 11388

Considering that you are using command line tools to run your tests, you can follow the docs and have something like the following:

python -m unittest package.tests.someModuleTests

Upvotes: 4

Nicola Musatti
Nicola Musatti

Reputation: 18226

If you can execute your code then your PYTHONPATH should already be set correctly. What you need to do is to specify the module you want to import, e.g.

import projectPackage.package.someModule

Upvotes: 1

supakeen
supakeen

Reputation: 2924

Run the unit test from the parent directory so the directory is in your PYTHONPATH (the current working directory always is). This is done by executing the test file from your parent directory or by using something like nosetest which recursively looks for all tests in your package.

Don't use relative imports, they cause things like this. Don't hack your PYTHONPATH and/or sys.path to try and fix it either.

Upvotes: 28

Related Questions