Python unittest parametrized test cases

来源:互联网 发布:linux培训上海 编辑:程序博客网 时间:2024/05/21 22:30

参考网址:http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases

方法1:

import unittestclass ParametrizedTestCase(unittest.TestCase):    """ TestCase classes that want to be parametrized should        inherit from this class.    """    def __init__(self, methodName='runTest', param=None):        super(ParametrizedTestCase, self).__init__(methodName)        self.param = param    @staticmethod    def parametrize(testcase_klass, param=None):        """ Create a suite containing all tests taken from the given            subclass, passing them the parameter 'param'.        """        testloader = unittest.TestLoader()        testnames = testloader.getTestCaseNames(testcase_klass)        suite = unittest.TestSuite()        for name in testnames:            suite.addTest(testcase_klass(name, param=param))        return suiteclass TestOne(ParametrizedTestCase):    def test_something(self):        print 'param =', self.param        self.assertEqual(1, 1)    def test_something_else(self):        self.assertEqual(2, 2)if __name__ == '__main__':    suite = unittest.TestSuite()    suite.addTest(ParametrizedTestCase.parametrize(TestOne, param=42))    suite.addTest(ParametrizedTestCase.parametrize(TestOne, param=13))    unittest.TextTestRunner(verbosity=2).run(suite)

方法2:

import unittestimport helpspotclass TestHelpSpot(unittest.TestCase):    "A few simple tests for HelpSpot"    def __init__(self, testname, path, user, pword):        super(TestHelpSpot, self).__init__(testname)        self.hs = helpspot.HelpSpot(path, user, pword)    def test_version(self):        a = self.hs.version()        b = self.hs.private_version()        self.assertEqual(a, b)    def test_get_with_param(self):        a = self.hs.filter_get(xFilter=1)    def test_unknown_method(self):        self.assertRaises(helpspot.HelpSpotError, self.hs.private_wuggienorple)if __name__ == '__main__':    import sys    user = sys.argv[1]    pword = sys.argv[2]    path = sys.argv[3]    suite = unittest.TestSuite()    suite.addTest(TestHelpSpot("test_version", path, user, pword))    suite.addTest(TestHelpSpot("test_get_with_param", path, user, pword))    suite.addTest(TestHelpSpot("test_unknown_method", path, user, pword))    unittest.TextTestRunner().run(suite)


0 0
原创粉丝点击