使用pyunit对“外部”程序进行单元测试扩展

1 投票
1 回答
821 浏览
提问于 2025-04-17 00:52

我在学习unittest的时候有点迷茫,不知道从哪里开始。我看过《Dive Into Python》的教程,也浏览过http://pyunit.sourceforge.net/

我有一个分析软件(我们叫它'prog.exe'),它使用Python来处理输入文件。我开始写一个Python模块,打算从这个输入文件中导入,以提供一些有用的功能。所以,运行其中一个分析的过程是这样的:

prog.exe inputdeck.py

其中inputdeck.py的内容是:

from mymodule import mystuff

那么我该如何设置和运行对mymodule的测试呢?上面的内容应该放在测试的setUp方法中的系统调用里,还是怎么做呢?


好的,解决方案是:

不要使用unittest.main(),因为那是命令行工具。相反,直接调用合适的unittest方法,像这样:

在命令行中运行:

prog.exe mytests.py

其中mytests.py的内容是:

import unittest
# ... code to run the analysis which we'll use for the tests ...
# ... test definitions ...
suite = unittest.TestLoader().loadTestsFromTestCase(test_cases)
unittest.TextTestRunner().run(suite)

可以参考这个例子:http://docs.python.org/release/2.6.7/library/unittest.html#unittest.TextTestRunner

1 个回答

0

Pyunit这个东西有点过时了(它是2001年的产物),现在它已经完全包含在Python的核心库里了(你可以在这里查看:http://docs.python.org/library/unittest.html)。建议你先看看这个文档,特别是基础示例部分

要测试你的模块,你需要创建一个文件,我们可以叫它mymodule_test.py,然后在里面写一些这样的内容:

import unittest
from mymodule import mystuff

class MyTestCase(unittest.TestCase):
   def test_01a(self):
      """ test mystuff"""
      self.failUnless(mystuff.do_the_right_stuff())

if __name__ == '__main__':
    unittest.main()

接着用python mymodule_test.py来运行它。

撰写回答