Python unittest模块用法实例分析

yipeiwu_com7年前Python基础

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

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

相关文章

Python定时发送消息的脚本:每天跟你女朋友说晚安

Python定时发送消息的脚本:每天跟你女朋友说晚安

首先 你要有个女朋友 效果: 需要安装几个包 pip install wxpy pip install wechat_sender pip install request...

Python PIL读取的图像发生自动旋转的实现方法

对于手机、相机等设备拍摄的照片,由于手持方向的不同,拍出来的照片可能是旋转0°、90°、180°和270°。即使在电脑上利用软件将其转正,他们的exif信息中还是会保留方位信息。 在用P...

pyqt 多窗口之间的相互调用方法

* 在编程开发中,一个程序不可避免的需要多窗口操作来实现具体的功能。 实现此功能的基本步骤(以三个窗口为例,使用主窗口调用其它两个窗口) # 主窗口 from PyQt5 impor...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...

python自动化测试之连接几组测试包实例

本文实例讲述了python自动化测试之连接几组测试包的方法,分享给大家供大家参考。具体方法如下: 具体代码如下: class RomanNumeralConverter(object...