twisted trial 单元测试出现 ImportError

0 投票
1 回答
1559 浏览
提问于 2025-04-16 16:32

我正在为我的twisted应用写一些单元测试,使用的是trial。我写了第一个“空”的trial单元测试类,但当我尝试运行它时,出现了导入错误,无法导入我的应用模块。

我猜这可能是因为trial改变了当前的工作目录,当我尝试导入我想要测试的对象类时,它就失败了。

我把应用模块放在一个我自己设置的单独目录里,这个目录不在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

也许这不是使用trial或部署Python应用的标准方式。

更新:我刚找到一个解决办法,只需将应用目录添加到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

1 个回答

0

你的模块或包是怎么组织的呢?可以试试下面这种结构,这样你就不需要搞什么路径上的小把戏了:

$ ls -R mypackage
mypackage:
__init__.py  __init__.pyc  mymodule.py  mymodule.pyc  test

mypackage/test:
__init__.py  __init__.pyc  test_mymodule.py  test_mymodule.pyc

从mypackage包目录的上一级运行测试:

$ trial mypackage
mypackage.test.test_mymodule
  MyModuleTestCase
    test_something ...                                                     [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.002s

PASSED (successes=1)

在文件test_mymodule.py里面:

from twisted.trial import unittest

from mypackage.mymodule import MyTestSubject

class MyModuleTestCase(unittest.TestCase):
    def test_something(self):
        pass

撰写回答