8

Python と unittest について非常に基本的な質問があります。

このようなディレクトリ構造があります。

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

これがtest_class.pyの内容です。ルート フォルダから lib.class をインポートすると、正常に動作します。しかし、別の場所からファイルをインポートすると、機能しません。


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()

テストを実行すると、このエラーが発生しました


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


ルート フォルダーではない別のフォルダーからファイルをインポートする方法がわかりません。

4

3 に答える 3

-1

TestClass の setUp メソッドで

追加 :

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)

アクセス:

aclass = self.module.AClass()

また

AClass = self.module.AClass
aclass = AClass()
于 2018-10-30T07:44:12.860 に答える