How to import a class from unittest in python?

I have a very simple question about Python and unittest.

I have such a directory structure.

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

Now this is my test_class.py content. If I import lib.class from the root folder, it works fine. But if I import the file from another place, it does not work.


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


I don’t know how to import a file from another folder, and not to the root folder.

+5
source share
2 answers

I do not think that this is the most effective or safe way to handle this, but this is how I add libraries to my own unittesting.

import unittest, os, sys
sys.path.append(os.path.abspath('..'))
from lib.class import Class

This would significantly add the previous folder to the list of available resources, and then use it to include the parent folder lib.

, , - import .. from lib.class. .

+8

sys.path,

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

Linux

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

Python script,

+1

All Articles