我想要一个单独的类来运行我的所有测试,然后从main调用该类来显示结果。不幸的是,我收到这样的错误:
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。
如果您发现我的测试结构本身也存在问题(main调用主测试类然后调用我所有其他测试类),请告诉我。我愿意接受更好的测试代码布局的建议(互联网上的例子只为你提供了使用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))
答案 0 :(得分: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)