2

I have the following directory structure:

.
├── Project
│   ├── __init__.py
│   ├── Project.py
└── tests
    ├── bootstrap.py
    ├── __init__.py
    └── unit
        └── test_utils.py

From the root of my Project I am running $ python tests/bootstrap.py but I am getting an error ValueError: Attempted relative import beyond toplevel package.

This is the contents of test_utils.py.

import unittest
import sys

from ... Project.Project import *

class TestUtils (unittest.TestCase):

    def test_file_changes (self):
        # some_function lives in Project.py
        var = some_function()
        self.assertEqual(200, var)

The bootstrap.py file does not have anything special going on, just loads the tests.

import unittest
from unit.utils import TestUtils

def main ():
    utils= unittest.TestLoader().loadTestsFromTestCase(TestUtils)
    unittest.TestSuite([utils])
    unittest.main(verbosity=2)

if __name__ == '__main__':
    main()

Can anyone see a problem here?

1 Answer 1

4

Import hierarchy (when importing from local directories as in your case) see the packages and modules from the directory, you run the program, not from importing file location.

So follow these rules:

  1. plan running your test always from root of your project
  2. put your testing code into test directory
  3. All your test suite shall import as if living in root of the project.

In your case just change

from ... Project.Project import *

to

from Project.Project import *
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the help! I made the change but now I get the error: ImportError: No module named Project.Project. Any ideas?
@JenZhang Make sure, you are not in directory tests but one directory higher ($ cd ..), if you do ls, you shall see "Project" and "tests" as your subdirectories, that is what I call project root and what I understood from your description you really do. If still having problems, try to import from python console (iPython is the best). There you can do various experiments and reach the point, you are able to import at least on console. You shall be able to >>> import Project.Project or >>> from Project.Project import *

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.