【问题标题】:Running unittest.main() from a module?从模块运行 unittest.main()?
【发布时间】:2009-05-15 15:57:58
【问题描述】:

我写了一个动态定义 unittest.TestCase 类的小函数(下面是简单的版本)。

当我将它从同一个源文件移到它自己的模块中时,我不知道如何让 unittest 发现新类。从任一文件调用 unittest.main() 都不会执行任何测试。

factory.py:

import unittest

_testnum = 0
def test_factory(a, b):

    global _testnum

    testname = 'dyntest' + str(_testnum)

    globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)})

    _testnum += 1


def finish():
    unittest.main()

someotherfile.py:

from factory import test_factory, finish


test_factory(1, 1)
test_factory(1, 2)


if __name__ == '__main__':
    finish()

输出:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

所以它不执行任何测试。

请注意,将所有内容保存在同一个文件中可以按预期工作:

import unittest

_testnum = 0
def test_factory(a, b):

    global _testnum

    testname = 'dyntest' + str(_testnum)

    globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)})

    _testnum += 1


test_factory(1, 1)
test_factory(1, 2)

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

输出(如预期):

.F
======================================================================
FAIL: testme (__main__.dyntest1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "partb.py", line 11, in <lambda>
    globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)})
AssertionError: 1 != 2

----------------------------------------------------------------------
Ran 2 tests in 0.008s

FAILED (failures=1)

如何使用我的 test_factory() 函数,以便我可以从单独的源文件执行它定义的所有 TestCase 对象?

【问题讨论】:

    标签: python unit-testing


    【解决方案1】:

    总体思路(unittest.main 为您做什么)是:

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

    根据 http://docs.python.org/library/unittest.html?highlight=unittest#module-unittest 。您的测试用例通过test_factory 函数隐藏在globals() 中,因此只需执行dir(),找到作为unittest.TestCase 实例的全局变量(或名称以'dyntest' 开头的全局变量等),然后以这种方式构建您的套件并运行它。

    【讨论】:

      【解决方案2】:

      默认情况下,unittest.main() 在主模块中查找单元 TestCase 对象。 test_factory 在自己的模块中创建 TestCase 对象。这就是为什么将它移到主模块之外会导致您看到的行为。

      试试:

      def finish():
          unittest.main(module=__name__)
      

      【讨论】:

        猜你喜欢
        • 2018-10-19
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        • 2013-06-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多