扭曲的试验单元测试得到了重视

2024-04-29 05:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的twisted应用程序编写一些单元测试, 我写了我的第一个“空的”试用unittest类,但当我试图运行它时,我发现导入我的应用程序模块时会有严重错误。在

这是我怀疑的,因为试用改变了当前的工作目录 当我试图导入我的模块和我想要的unittest对象类时 它失败了。在

我把我的应用程序模块放在我自己建立的一个目录中,它不在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')

所以错误消息如下:
例外。重要:没有名为MyModule的模块

也许这不是使用试用版或部署python应用程序的标准方式。在

更新:我刚刚想出了一个解决方法,只需将app目录附加到搜索路径 所以进口部分如下所示:

^{pr2}$

Tags: 模块thefromtestimportself目录应用程序
1条回答
网友
1楼 · 发布于 2024-04-29 05:24:55

你的模块/软件包是如何组织的?也许可以尝试以下结构,这样就不需要进行任何路径黑客攻击:

$ 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包目录的正上方运行测试:

^{pr2}$

内部文件测试_我的模块.py公司名称:

from twisted.trial import unittest

from mypackage.mymodule import MyTestSubject

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

相关问题 更多 >