toy
toy

Reputation: 12161

How to import a class from unittest in python?

I have a very basic question about Python and unittest.

I have a directory structure like this.

Project
   |
   |-lib
      |
      |-__init__.py
      |-class.py
   |
   |-tests
      |
      |-__init__.py
      |-test_class.py

Now this is my content of test_class.py. If I import the lib.class from the root folder it's working fine. But if I import the file from somewhere else it's not working.


import unittest
from lib.class import Class

class TestClass(unittest.TestCase):
    def testClass(self):
            // do some test

def main():
    unittest.main()

if __name__ == '__main__':
    main()

When I run the test I got this error


Traceback (most recent call last):
  File "tests/test_class.py", line 2, in 
    from lib.class import Class
ImportError: No module named lib.class


Not sure how do I import the file from another folder that's not the root folder.

Upvotes: 10

Views: 10361

Answers (3)

eandersson
eandersson

Reputation: 26362

The better solution is to create a virtualenv and install the project in developer mode. This allows you to modify and execute code without having to re-install it.

virtualenv venv
source venv/bin/activate
pip install -e .

Inside the tests you would now simply include the fqdn.

from project.lib.class import Class

Keep in mind that you will need to use setuptools to properly define the project.

Upvotes: 10

Samuel LAVOINE
Samuel LAVOINE

Reputation: 1

in the setUp method of TestClass

add :

file_path = Path(__file__).parent.parent / 'lib' / 'class.py'

self.assertTrue(file_path.exists())

spec = spec_from_file_location(file_path.name, location=file_path, loader=None, submodule_search_locations=None)

self.module = module_from_spec(spec)

self.module.__spec__.loader.exec_module(self.module)

access:

aclass = self.module.AClass()

or

AClass = self.module.AClass
aclass = AClass()

Upvotes: -1

Josh Austin
Josh Austin

Reputation: 776

Modify sys.path to include the Project directory

import sys
sys.path.append('/path/to/Project')

On Linux, you could do

import sys, os
sys.path.append(os.path.abspath(sys.path[0]) + '/../')

and that should include the directory above the running Python testing script, which is the Project folder

Upvotes: 5

Related Questions