使用Python的unittest模块时出现未绑定错误

2 投票
1 回答
3254 浏览
提问于 2025-04-16 03:10

我想要一个单独的类来运行我所有的测试,然后从主程序中调用这个类来显示结果。不过,我遇到了这样的错误:

Traceback (most recent call last):
  File "/home/dhatt/workspace/pyqt_DALA_ServiceTracker/src/Main.py", line 21, in <module>
    allsuite = unittest.TestLoader.loadTestsFromModule(TestAllSuite)
TypeError: unbound method loadTestsFromModule() must be called with TestLoader instance as first argument (got type instance instead)

我该如何修改我的代码,以便能够运行我的测试呢?

我使用的是 Python 2.6.5。

如果你觉得我的测试结构本身也有问题(比如主程序调用主要的测试类,然后这个类再调用我其他的测试类),请告诉我。我很乐意接受关于如何更好地组织我的测试代码的建议(网上的例子通常只给出使用 unittest 的基本用法)。

这是我从 TestAllClass 中的代码(它在调用其他测试类):

import unittest
from TestSettings import TestSettings
from TestConnectDB import TestConnectDB


class TestAllSuite(unittest.TestCase):

    def testsuite(self):
        suite_settings = TestSettings.suite()
        suite_connectDB = TestConnectDB.suite()
        alltests = unittest.TestSuite([suite_settings, suite_connectDB])
        return alltests

这是我主程序的一部分,它调用了 TestAllClass:

if __name__ == '__main__':
    allsuite = unittest.TestLoader.loadTestsFromModule(TestAllSuite)
    unittest.TextTestRunner(verbosity=2).run(allsuite)

这是我的一个测试类的示例(如果有帮助的话):

from Settings import Settings
import unittest


class TestSettings(unittest.TestCase):
    def suite(self):
        suite = unittest.TestSuite()
        tests = ['test_confirm_ip', 'test_valid_conn','test_correct_location']
        return unittest.TestSuite(map(suite, tests))

    def setUp(self):
        self._test_settings = Settings('/home/dhatt/ServiceTrackerSettings.ini')
        self.ip_add, self.conn, self.digby =    self._test_settings._get_config_variables()

    def tearDown(self):
        self._test_settings = None
        self.ip_add = None
        self.conn = None
        self.digby = None

    def test_confirm_ip(self):
        self.assertEqual((str(self.ip_add)), ('142.176.195.250'))

    def test _confirm_conn(self):
        self.assertEqual((str(self.conn)), ('conn1'))

    def test_confirm_location(self):
        self.assertEqual((self.digby), (True))

1 个回答

4

传给 loadTestsFromModule 的参数(在你的例子中是 TestAllSuite),应该是一个模块,而不是 unittest.TestCase 的子类:

allsuite = unittest.TestLoader.loadTestsFromModule(TestAllSuite)

比如,这里有一个简单的脚本,它会运行所有在文件名格式为 test_*.py 的文件中找到的单元测试:

import unittest
import sys
import os

__usage__='''
%prog      # Searches CWD
%prog DIR   
'''

if __name__=='__main__':
    if len(sys.argv)>1:
        unit_dir=sys.argv[1]
    else:
        unit_dir='.'
    test_modules=[filename.replace('.py','') for filename in os.listdir(unit_dir)
                  if filename.endswith('.py') and filename.startswith('test_')]
    map(__import__,test_modules)

    suite = unittest.TestSuite()
    for mod in [sys.modules[modname] for modname in test_modules]:
        suite.addTest(unittest.TestLoader().loadTestsFromModule(mod))
    unittest.TextTestRunner(verbosity=2).run(suite)

撰写回答