我具有以下项目结构:(注意:这是我原始项目的示例结构。
proj1/
__init__.py
App/
__init__.py
Handlers/
__init__.py
Sum.py
Tests/
__init__.py
Handlers/
__init__.py
SumHandler.py
tests.py
我的tests.py
=>
import unittest
import Tests
def suite():
suite = unittest.TestSuite()
module = __import__('Tests.Handlers.SumHandler', fromlist=['object'])
suite.addTest(unittest.TestSuite(map(unittest.TestLoader().loadTestsFromModule, [module])))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
test_suite = suite()
result = runner.run (test_suite)
print("---- START OF TEST RESULTS")
print(result)
print("---- END OF TEST RESULTS")
我的__init__.py
=>
import sys as _sys
class Package(object):
def __init__(s, local):
import os.path
s.cache = {}
s.local = dict((k, local[k]) for k in local)
s.root = os.path.realpath(os.path.dirname(s.local["__file__"]))
def __getattr__(s, k):
if k in s.local: return s.local[k]
if k in s.cache: return s.cache[k]
path = list(s.local["_sys"].path)
s.local["_sys"].path = [s.root]
try:
module = __import__(k, globals(), locals(), ['object'], 0)
name = k[0].capitalize() + k[1:]
s.cache[k] = getattr(module, name) if hasattr(module, name) else module
finally: s.local["_sys"].path[:] = path
return s.cache[k]
_sys.modules[__name__] = Package(locals())
我的SumHandler.py
=>
import unittest
import App
class SumHandler(unittest.TestCase):
def setUp(self):
self.a = 10
self.b = 5
self.sum = App.Handlers.Sum()
def test_add(self):
self.assertEqual(self.sum.add(self.a, self.b),15)
def tearDown(self):
del(self.a, self.b)
我的Sum.py
=>
class Sum():
def add(self, x, y):
return x + y
我正在使用 unittest框架来测试我的App目录中的代码。现在,当我使用上述目录结构运行tests.py
文件时,出现以下错误=>
Traceback (most recent call last):
File "/Users/Sharvin/proj_1/Tests/Handlers/SumHandler.py", line 9, in setUp
self.sum = App.Handlers.Sum()
AttributeError: module 'App' has no attribute 'Handlers'
问题:
我正在尝试将整个App
目录导入SumHandler
中Tests/Handlers
包内,以便可以从App
目录中导入多个包。我该如何实现?