【问题标题】:Run unittests from a different file从不同的文件运行单元测试
【发布时间】:2015-07-22 09:42:25
【问题描述】:

我有一个包含单元测试的文件TestProtocol.py。我可以运行该脚本并按预期获得 30 次测试的测试结果。现在我想从位于同一目录中的另一个文件tester.py 运行这些测试。在tester.py 内部我尝试了import TestProtocol,但它运行了0 个测试。

然后我发现文档说我应该这样做:

suite = unittest.TestLoader().discover(".", pattern = "*")
unittest.run(suite)

这应该遍历当前目录. 中与模式* 匹配的所有文件,因此所有文件中的所有测试。不幸的是,它再次运行 0 次测试。

有一个related QA 建议这样做

import TestProtocol
suite = unittest.findTestCases(TestProtocol)
unittest.run(suite)

但这也没有找到任何测试。

如何导入和运行我的测试?

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:

    你可以试试下面的

    # preferred module name would be test_protol as CamelCase convention are used for class name
    import TestProtocol
    
    # try to load all testcases from given module, hope your testcases are extending from unittest.TestCase
    suite = unittest.TestLoader().loadTestsFromModule(TestProtocol)
    # run all tests with verbosity 
    unittest.TextTestRunner(verbosity=2).run(suite)
    

    这是一个完整的例子

    文件 1:test_me.py

    # file 1: test_me.py 
    import unittest
    
    class TestMe(unittest.TestCase):
        def test_upper(self):
            self.assertEqual('foo'.upper(), 'FOO')
    
    if __name__ == '__main__':
        unittest.main()
    

    文件2:test_other.py,放在同一目录下

    # file 2: test_other.py, put this under same directory
    import unittest
    import test_me
    
    suite = unittest.TestLoader().loadTestsFromModule(test_me)
    unittest.TextTestRunner(verbosity=2).run(suite)
    

    运行每个文件,它会显示相同的结果

    # python test_me.py - Ran 1 test in 0.000s
    # python test_other.py - Ran 1 test in 0.000s
    

    【讨论】:

    • 不幸的是,这也给了我Ran 0 tests in 0.000s OK
    • @nwp 我已经用一个工作示例更新了我的答案,希望这会有所帮助
    • 它正在工作。之前它对我不起作用的原因是我在test_me.py 中有unittest.main()(没有if __name__ == '__main__'),这导致无法找到测试。
    • @Shaikhul 非常好,谢谢分享。您将如何收到状态码?
    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 2021-08-23
    • 2016-11-18
    • 2019-01-14
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多