【问题标题】:Python unittesting: run tests in another modulePython 单元测试:在另一个模块中运行测试
【发布时间】:2013-02-26 08:40:22
【问题描述】:

我想将我的应用程序的文件放在/Files 文件夹下,而将测试单元放在/UnitTests 中,这样我就可以清楚地将应用程序和测试分开。

为了能够使用与 mainApp.py 相同的模块路由,我在根文件夹中创建了一个 testController.py。

mainApp.py
testController.py
Files
  |__init__.py
  |Controllers
     | blabla.py
  | ...
UnitTests
  |__init__.py
  |test_something.py

因此,如果在 test_something.py 中我想测试 /Files/Controllers/blabla.py 中的一个函数,我尝试以下操作:

import unittest
import Files.Controllers.blabla as blabla


class TestMyUnit(unittest.TestCase):

    def test_stupid(self):
        self.assertTrue(blabla.some_function())


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


然后从文件 testController.py 中,我执行以下代码:

import TestUnits.test_something as my_test
my_test.unittest.main()

输出没有失败,但没有执行测试

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

OK
[Finished in 0.3s]


我尝试了一个没有依赖关系的测试,如果执行为“ma​​in”有效,但从外部调用时,输出相同:

import unittest


def tested_unit():
    return True


class TestMyUnit(unittest.TestCase):

    def test_stupid(self):
        self.assertTrue(tested_unit())


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

问题:我如何让它发挥作用?

【问题讨论】:

    标签: python unit-testing module tdd


    【解决方案1】:

    在 test_something.py 中,这样做:

    def suite():
        suite = unittest.TestSuite()
        suite.addTest(unittest.makeSuite(TestMyUnit, 'test'))
        return suite
    

    在 testController.py 中,这样做:

    from TestUnits import test_something
    
    def suite():
        suite = unittest.TestSuite()
        suite.addTest(test_something.suite())
        return suite
    
    if __name__ == '__main__':
        unittest.main(defaultTest='suite')
    

    【讨论】:

      【解决方案2】:

      unittest.main() 方法查看上下文中存在的所有 unittest.TestCase 类。 所以你只需要在你的 testController.py 文件中导入你的测试类并在这个文件的上下文中调用 unittest.main() 。

      所以你的文件 testController.py 应该看起来像这样:

      import unittest    
      from UnitTests.test_something import *
      unittest.main()
      

      【讨论】:

      • 谢谢,但它不起作用。结果是一样的:它不执行任何测试。
      • 好吧,我的错。您必须从 test_something 文件中导入所有测试用例。尝试使用 from UnitTests.test_something import TestMyUnit(或 *),它应该可以工作!
      • 太棒了兄弟!感谢您的回答。
      【解决方案3】:

      有一种使用 subprocess.call() 运行测试的解决方法,例如:

      import subprocess
      
      args = ["python", "test_something.py"]
      subprocess.call(args)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-13
        • 2011-02-10
        相关资源
        最近更新 更多