我正在尝试为我的扭曲应用程序编写一些使用试用版的单元测试,我编写了我的第一个“空”试用单元测试类,但是当我尝试运行它时,我得到 ImportError 用于导入我的应用程序模块。
这是我怀疑的,因为试用更改了当前工作目录,并且当我尝试使用要进行单元测试的对象类导入模块时,它失败了。
我将我的应用程序模块保存在我自己设置的单个目录中,它不在 PYTHONPATH 或其他已知的任何目录中,在我的应用程序中,模块导入其他模块,因为它们都在同一个目录中。
代码看起来与此类似:
from twisted.trial import unittest
from twisted.spread import pb
from twisted.internet import reactor, protocol
from MyModule import MyTestSubject
class MyTestSubjectTest(unittest.TestCase):
def setUp(self):
print('\nset up')
def test_startConsoleServer(self):
ts = MyTestSubject()
.... # here goes the body of the test
def tearDown(self):
print('\ntear down')
所以错误消息看起来像这样:
exceptions.ImportError: No module named MyModule
也许这不是使用试用版或部署 python 应用程序的标准方式。
更新:我刚刚想出了一个解决方法,只需将 app 目录附加到 sys.path 中,导入部分将如下所示:
from twisted.trial import unittest
from twisted.spread import pb
from twisted.internet import reactor, protocol
import sys, os; sys.path.append(os.path.abspath(os.path.curdir))
from MyModule import MyTestSubject