Python unittest模块用法实例分析

时间:2022-10-06 08:51:56

本文实例讲述了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代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#coding=utf-8
import random
import unittest
class 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程序设计有所帮助。

原文链接:http://canlynet.iteye.com/blog/1671750