【问题标题】:Using IDLE to run Python PyUnit unit tests使用 IDLE 运行 Python PyUnit 单元测试
【发布时间】:2010-03-16 18:30:49
【问题描述】:

有没有办法在 IDLE 中直接运行 PyUnit(unittest 模块)单元测试?

我问是因为我有一个简短的测试模块,当我使用 Cygwin shell 中的 python mymodule.py 运行它时,我通过了所有测试,但是当我从 IDLE 使用 Run->Run Module 时,测试通过但我得到了异常(SystemExit: False)。

例如,这里有一个示例测试模块来重现这个:

#!/usr/bin/python

import unittest

class fooTests(unittest.TestCase):

    def setUp(self):
        self.foo = "bar"

    def testDummyTest(self):
        self.assertTrue(True)

    def testDummyTestTwo(self):
        self.assertEquals("foo", "foo")


    def tearDown(self):
        self.foo = None

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

当我使用 python fooTests.py 从 Cygwin shell 运行它时,它会产生:

$ python fooTests.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

但是当我在 IDLE 中编辑 fooTests.py 并执行 Run -> Run Module 时,IDLE 生成的新 Python Shell 会生成:

>>> ================================ RESTART ================================
>>> 
..
----------------------------------------------------------------------
Ran 2 tests in 0.031s

OK

Traceback (most recent call last):
  File "C:\Some\path\info\I\shortened\fooTests.py", line 20, in <module>
    unittest.main()
  File "C:\Python26\lib\unittest.py", line 817, in __init__
    self.runTests()
  File "C:\Python26\lib\unittest.py", line 865, in runTests
    sys.exit(not result.wasSuccessful())
SystemExit: False
>>> 

我做错了什么,产生了这个回溯,尤其是如何修复它,以便我可以在 IDLE 中执行 Run->Run Module(或 F5)来快速运行单元测试?

(这肯定是一个简单的问题,但我快速弄清楚它的尝试被证明是徒劳的。)

【问题讨论】:

    标签: python unit-testing python-idle


    【解决方案1】:

    没有人回答(我发现如果在最初的几分钟内没有任何答案,答案的可能性就会大大降低:),所以我自己一直在研究这个。

    不确定这是否是最优雅的解决方案,但正在改变:

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

    if __name__ == '__main__':
        try: unittest.main()
        except SystemExit: pass
    

    似乎成功了。

    我猜问题是(根据http://coding.derkeiler.com/Archive/Python/comp.lang.python/2003-11/0239.html)unittest 模块通过调用 sys.exit 完成,这对于 IDLE 来说显然是有问题的,因为它希望保持 Python shell 运行,而当你运行它时它不是问题从命令行,无论如何它都会将你转储到你已经运行的命令行。

    我不知道这种捕获 SystemExit 事件并忽略它的解决方案是否有问题,但它似乎适用于我检查的所有测试通过和一些测试失败的情况。

    另外:参见 StackOverFlow 帖子:What code can I use to check if Python is running in IDLE?,它提供了一个测试来查看程序是否在 IDLE 中运行。

    【讨论】:

    • try/except 可能会吃掉返回代码,因此如果代码随后在 CI 环境中进行测试,可能会导致问题。但是,信息很方便:unitest 模块调用 sys.exit,当交互式 shell 想要保持打开状态(即 IDle、Emacs python shell 等)时,会显示此异常。
    【解决方案2】:

    你也可以这样做

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

    如果您使用的是 Python >= 2.7

    【讨论】:

      【解决方案3】:

      这样的事情也应该有效:

      suite = unittest.TestLoader().loadTestsFromTestCase( fooTests )
      unittest.TextTestRunner(verbosity=2).run( suite )
      

      我找到了here,它对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多