首页 > 编程 > Python > 正文

Python unittest模块用法实例分析

2019-11-25 14:40:39
字体:
来源:转载
供稿:网友

本文实例讲述了Python unittest模块用法。分享给大家供大家参考,具体如下:

python的unittest模块提供了一个测试框架,只要我们写一个继承unittest.TestCase的类,类中用setUp做初始化,用tearDown做清理。

主要用到的函数有:

failedinfo表示不成立打印信息failedinfo,为可选参数
self.fail([msg])会无条件的导致测试失败,不推荐使用。
self.assertEqual(value1, value2, failedinfo) # 断言value1 == value2
self.assertTrue(表达式, failedinfo) # 断言value为真
self.assertFalse(表达式, failedinfo) # 断言value为假
# 断言肯定发生异常,如果没发生异常,则为测试失败。
# 参数1为异常,参数二为抛出异常的调用对象,剩余参数为传递给可调用对象的参数。
self.assertRaises(ValueError, self.widget.resize, -1, -1)
调用时机的加self,如self.assertEqual(self.seq, range(10)),self.assertTrue(value > 100)

更详细的教程见:http://pyunit.sourceforge.net/pyunit_cn.html

Python代码:

#coding=utf-8import randomimport unittestclass TestSequenceFunctions(unittest.TestCase):  def setUp(self):    self.seq = range(10)  def test_shuffle(self):    # make sure the shuffled sequence does not lose any elements    random.shuffle(self.seq)    self.seq.sort()    self.assertEqual(self.seq, range(10))    # should raise an exception for an immutable sequence    self.assertRaises(TypeError, random.shuffle, (1,2,3))  def test_choice(self):    element = random.choice(self.seq)    self.assertTrue(element in self.seq)  def test_sample(self):    with self.assertRaises(ValueError):      random.sample(self.seq, 20)    for element in random.sample(self.seq, 5):      self.assertTrue(element in self.seq)results_fields = [  ("username", unicode),  ("showid", unicode),  ("total_pv", int),  ("pubdate", unicode),  ("tags", list),  ("showname", unicode),  ("pg", int),  ("ext", str),]results_fields_map = dict(results_fields)class TestDictValueFormatFunctions(unittest.TestCase):  def setUp(self):    self.results = [{      "username": u"疯狂豆花",      "showid": u"130e28f0fe0811e0a046",      "total_pv": 14503214,      "pubdate": u"2012-07-07 01:22:47",      "tags": [        "轩辕剑",        "天之痕"        ],      "showname" : u"轩辕剑之天之痕",      "pg" : 1,      "ext" : "mp4"    }    ]  def test_format(self):    self.assertTrue(isinstance(self.results, list), "self.results's type must be dict but got {0}".format(type(self.results)))    for r in self.results:      for f in results_fields_map:        value = r.get(f, None)        self.assertTrue(isinstance(value, results_fields_map[f]), u"{0}'s type must be {1} but got {2}".format(value, results_fields_map[f], type(value)))        #self.assertTrue(isinstance(value, results_fields_map[f]))  def test_value(self):    for r in self.results:      self.assertEqual(r["pg"], 1)      self.assertEqual(r["ext"], u"mp4")if __name__ == '__main__':  # unittest.main() # 用这个是最简单的,下面的用法可以同时测试多个类  # unittest.TextTestRunner(verbosity=2).run(suite1) # 这个等价于上述但可设置verbosity=2,省去了运行时加-v  suite1 = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)  suite2 = unittest.TestLoader().loadTestsFromTestCase(TestDictValueFormatFunctions)  suite = unittest.TestSuite([suite1, suite2])  unittest.TextTestRunner(verbosity=2).run(suite)

运行结果:

test_choice (__main__.TestSequenceFunctions) ... ok
test_sample (__main__.TestSequenceFunctions) ... ok
test_shuffle (__main__.TestSequenceFunctions) ... ok
test_format (__main__.TestDictValueFormatFunctions) ... ok
test_value (__main__.TestDictValueFormatFunctions) ... ok

----------------------------------------------------------------------
Ran 5 tests in 0.013s

OK

更多Python相关内容感兴趣的读者可查看本站专题:《Python入门与进阶经典教程》、《Python字符串操作技巧汇总》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表