python内部自带了一个单元测试的模块,pyUnit也就是我们说的:unittest

1、介绍下unittest的基本使用方法:

1)import unittest

2)定义一个继承自unittest.TestCase的测试用例类

3)定义setUp和tearDown,在每个测试用例前后做一些辅助工作。

4)定义测试用例,名字以test开头。

5)一个测试用例应该只测试一个方面,测试目的和测试内容应很明确。主要是调用assertEqual、assertRaises等断言方法判断程序执行结果和预期值是否相符。

6)调用unittest.main()启动测试

7)如果测试未通过,会输出相应的错误提示。如果测试全部通过则不显示任何东西,这时可以添加-v参数显示详细信息。

2、 下面是unittest模块的常用方法:

assertEqual(a, b)     a == b

assertNotEqual(a, b)     a != b

assertTrue(x)     bool(x) is True

assertFalse(x)     bool(x) is False

assertIs(a, b)     a is b     2.7

assertIsNot(a, b)     a is not b     2.7

assertIsNone(x)     x is None     2.7

assertIsNotNone(x)     x is not None     2.7

assertIn(a, b)     a in b     2.7

assertNotIn(a, b)     a not in b     2.7

assertIsInstance(a, b)     isinstance(a, b)     2.7

assertNotIsInstance(a, b)     not isinstance(a, b)     2.7

下面看具体的代码应用:

首先写了一个简单应用:

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 inself.seq)

def test_error(self):

element = random.choice(self.seq)

self.assertTrue(element not in self.seq)

if __name__ == '__main__':

unittest.main()

下面是写了一个简单的应用,测试下面4个网址返回的状态码是否是200。

import unittest
import urllib

class TestUrlHttpcode(unittest.TestCase):
   def setUp(self):
       urlinfo = ['http://www.baidu.com','http://www.163.com','http://www.sohu.com','http://www.cnpythoner.com']
       self.checkurl = urlinfo

def test_ok(self):
       for m in
self.checkurl:
           httpcode = urllib.urlopen(m).getcode()
           self.assertEqual(httpcode,200)

if __name__ == '__main__':
   unittest.main()

如果有的网址打不开,返回404的话,测试则会报错

如果有的网址打不开,返回404的话,测试则会报错

ERROR: test_ok (__main__.TestUrlHttpcode)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "jay.py", line 12, in test_ok
    httpcode = urllib.urlopen(m).getcode()
  File "/usr/lib/python2.7/urllib.py", line 86, in urlopen
    return opener.open(url)
  File "/usr/lib/python2.7/urllib.py", line 207, in open
    return getattr(self, name)(url)
  File "/usr/lib/python2.7/urllib.py", line 462, in open_file
    return self.open_local_file(url)
  File "/usr/lib/python2.7/urllib.py", line 476, in
open_local_file
    raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] No such file or directory: 'fewfe.com'

----------------------------------------------------------------------
Ran 1 test in 1.425s

FAILED (errors=1)

3也有其他的unittest方法,用于执行更具体的检查,如:

Method     Checks that     New in
assertAlmostEqual(a, b)     round(a-b, 7) == 0
     
assertNotAlmostEqual(a, b)     round(a-b, 7) != 0
     
assertGreater(a, b)     a > b     2.7
assertGreaterEqual(a, b)     a >= b     2.7
assertLess(a, b)     a < b     2.7
assertLessEqual(a, b)     a <= b     2.7
assertRegexpMatches(s, re)     regex.search(s)
    2.7
assertNotRegexpMatches(s, re)     not regex.search(s)
    2.7
assertItemsEqual(a, b)     sorted(a) == sorted(b) and works with
unhashable objs     2.7
assertDictContainsSubset(a, b)     all the key/value pairs in a
exist in b     2.7
assertMultiLineEqual(a, b)     strings     2.7
assertSequenceEqual(a, b)     sequences     2.7
assertListEqual(a, b)     lists     2.7
assertTupleEqual(a, b)     tuples     2.7
assertSetEqual(a, b)     sets or frozensets    
2.7
assertDictEqual(a, b)     dicts     2.7
assertMultiLineEqual(a, b)     strings     2.7
assertSequenceEqual(a, b)     sequences     2.7
assertListEqual(a, b)     lists     2.7
assertTupleEqual(a, b)     tuples     2.7
assertSetEqual(a, b)     sets or frozensets    
2.7
assertDictEqual(a, b)     dicts     2.7

你可以用unittest模块的更多方法来做自己的单元测试。

python unittest基本介绍的更多相关文章

  1. python+unittest 搭建简易的接口测试框架

    主要介绍如何使用python+unittest快速搭建一个接口测试的框架 1.安装python  unittest 2.新建一个python项目ApiTest 在setUp和setDown里设置一些需 ...

  2. python strip()函数 介绍

    python strip()函数 介绍,需要的朋友可以参考一下   函数原型 声明:s为字符串,rm为要删除的字符序列 s.strip(rm)        删除s字符串中开头.结尾处,位于 rm删除 ...

  3. 从python run 和python unittest两种eclipse运行方式深入理解if __name__ == "__main__"

    在写一个简单的python测试程序的时候,发现eclipse中Run as "Python run 和 Python unittest”结果不一样?为什么会不一样? 先贴一下代码段: # - ...

  4. Python 科学计算-介绍

    Python 科学计算 作者 J.R. Johansson (robert@riken.jp) http://dml.riken.jp/~rob/ 最新版本的 IPython notebook 课程文 ...

  5. Python 基于python操纵zookeeper介绍

    基于python操纵zookeeper介绍 by:授客  QQ:1033553122 测试环境 Win7 64位 Python 3.3.4 kazoo-2.6.1-py2.py3-none-any.w ...

  6. Python redis 简单介绍

    Python redis 简单介绍 1.安装 终端输入: pip(or)pip3.6 install redis 安装成功 2.哈哈,发现我并没有redis服务可以访问,所以到这里,在本机安装了red ...

  7. 自动化测试神器 之 python unittest 断言

    自动化测试的最后一步需要判断结果是否正确,而正确设置断言可以帮助判断测试用例的执行结果,从而提高自动化测试的效率,python unittest  提供了一个比较完整的断言方法.unittest框架测 ...

  8. 第二种方式,修改python unittest的执行顺序,使用猴子补丁

    1.按照测试用例的上下顺序,而不是按方法的名称的字母顺序来执行测试用例. 之前的文章链接 python修改python unittest的运行顺序 之前写的,不是猴子补丁,而是要把Test用例的类名传 ...

  9. python 函数参数介绍

    python 函数参数介绍 python 使用过程总,总会遇到 *args,**kw形式的参数,总是一头雾水,而且网上介绍的或是叫法不一,为此专门深入实践进而了解了函数参数的使用 具体请看代码 #-* ...

随机推荐

  1. Ubuntu 修改用户密码与启动root账号

    passwd sban 修改当前帐号 sudo passwd root 修改root帐号 修改/etc/ssh/sshd_config,改: PermitRootLogin without-passw ...

  2. iOS进阶学习-CoreData

    一.CoreData数据库框架的优势 1.CoreData数据持久化框架是Cocoa API的一部分,首次在iOS5版本的系统中出现,它允许按照实体-属性-值模型组织数据,并以XML.二进制文件或者S ...

  3. Android -- 浮动组建

    在开发Android应用时,加新功能是必不可少的,我们加入了新的功能,有的一看界面就可以看出来,但是有的新功能就比较隐蔽,也就是用户很难知道你添加了这个新功能,这个时候就需要用户在打开我们的应用时给出 ...

  4. java并发编程:进程和线程

    java并发编程涉及到很多内容,当然也包括多线程,再次补充点相关概念 原文地址:http://www.cnblogs.com/dolphin0520/p/3910667.html 一.操作系统中为什么 ...

  5. Careercup - Microsoft面试题 - 6282862240202752

    2014-05-11 03:56 题目链接 原题: Given an integer array. Perform circular right shift by n. Give the best s ...

  6. 本地wordpress博客系统安装搭建实践

    我们按步骤来, (1)安装XAMPP集成软件包 wordpress 的运行要求是在 php + MySQL + Apache的服务器环境,所以要先搭建该环境,我用的是XAMPP软件包,安装很方便. 下 ...

  7. HDU 5763 Another Meaning KMP+DP

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5763 Another Meaning Time Limit: 2000/1000 MS (Java/ ...

  8. 【CentOS】Eclipse中svn插件使用

    目录: 1.安装 2.使用 3.错误 1.安装 svn插件地址: Subclipse 1.6.x Update Site - http://subclipse.tigris.org/update_1. ...

  9. hdu 2426 Interesting Housing Problem 最大权匹配KM算法

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2426 For any school, it is hard to find a feasible ac ...

  10. poj 3009 Curling 2.0

    题目来源:http://poj.org/problem?id=3009 一道深搜题目,与一般搜索不同的是,目标得一直往一个方向走,直到出界或者遇到阻碍才换方向. 1 #include<iostr ...