Question

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?

Was it helpful?

Solution

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 *
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top