python中的单元测试pyUnit
 
在Python中进行单元测试时需要用到PyUnit模块,Python 2.1及其以后的版本都将PyUnit作为一个标准模块,但如果你使用的是较老版本的Python,那就要自已动手安装了。在PyUnit的网站(http://sourceforge.net/projects/pyunit)上可以下载到PyUnit最新的源码包,此处使用的是pyunit-1.4.1.tar.gz。
PyUnit跟Junit很相似,甚至连一些基本的函数名都一样。例如测试类必须是TestCase的子类,且初始函数为setUp(self), 清理函数tearDown(self)。
 
将被测试的文件:widget.py
# 将要被测试的类
class Widget:
def __init__(self, size = (40, 40)):
self._size = size
def getSize(self):
return self._size
def resize(self, width, height):
if width < 0 or height < 0:
raise ValueError, "illegal size"
self._size = (width, height)
def dispose(self):
pass

测试文件:widgetTest.py

# 执行测试的类
from widget import Widget
import unittest
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
def tearDown(self):
self.widget.dispose()
self.widget = None
def testSize(self):
self.assertEqual(self.widget.getSize(), (40, 40))
def testResize(self):
self.widget.resize(100, 100)
self.assertEqual(self.widget.getSize(), (100, 100)) # 测试
if __name__ == "__main__":
# 构造测试集
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
suite.addTest(WidgetTestCase("testResize"))
# 执行测试
runner = unittest.TextTestRunner()
runner.run(suite)

执行测试代码,测试完的结果:

C:\App\py_test\test>python diwgetTest.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s OK C:\App\py_test\test>

可以分几步进行, 首先我们的测试类要继承于unittest.TestCase. 如果采用动态测试的方法可以为每个需要测试的方法编写测试方法,使用assertEqual( , ). 然后把我们的测试都放到unittest.TestSuite()容器中,最后使用 unittest.TextTestRunner().run(suite)方法自动测试。

参考:
http://www.ibm.com/developerworks/cn/linux/l-pyunit/index.htmlhttp://www.cnblogs.com/ysisl/archive/2009/08/17/1548054.html

================================================================================

python 单元测试 使用摘要
主要步骤:
1。编写完备的单元测试用例
2。根据测试用例测试点编写程序
3。每编写完一个功能,执行测试用例,然后修改代码,直到该点涉及用例全部通过
4。所有用例通过测试,停止编码
5。发现新bug和开发新版本时,及时更新测试用例

编写用例

使用方法
    python自带unittest模块,编写的测试用例类继承unittest.TestCase类,所有测试函数以test开头,执行时,执行unittest.main(),所有测试类中以test开头的函数自动执行
    保存文件:testproject.py,简单例子如下:

import unittest
#import testproject
class mytestproject1(unittest.TestCase):
def testcase1(self):
#等于运算
self.assertEquals(7/2,3)
def testcase2(self):
#等于运算
self.assertEquals("".join(['a','b','c']),"abc") class mytestproject2(unittest.TestCase):
def testException(self):
#出现异常
self.assertRaises(ZeroDivisionError,lambda x:3/x,0) def testcase2(self):
#不等于运算
self.assertNotEqual("".join(['a','b','c']),"abcd") if __name__ == '__main__':
unittest.main()

执行后,会报告每个函数执行情况

测试用例的编写
1。针对性
        每个用例,即test函数,必须只解决一个问题,这样定位问题会很简单
2。独立性
        每个用例之间没有影响,一个的输出不会影响到另外一个的执行
3。完备性
        每个用例所挑选的例子应该有代表性,尽可能增加覆盖度
4。顺序
        对于每个功能点来说,可能涉及到不同的方面,这些用例最好用一个类组织起来,并按照一定的逻辑顺序排列,这个对开发是有指导作用的
        
从测试对象来讲,测试用例应该具备以下条件:
1。功能性用例
        做什么的问题
2。反面用例
        不能做什么的问题,对处理对象的限定
3。适应性,健壮性用例
        其他的输入,达到安全性,可知性
        
unittest的接口:
主要用到unittest.TestCase中的接口,基本的是equal系列和raises系列。具体格式参见 help('unittest')

具体的assert的使用,可参看:python assert使用说明

unittest帮助文档,可参看:unittest文档翻译

=============================================================

Why unit test?

  • You're already doing it!

Speaker's notes:

You're probably already doing at least ad hoc testing at the interactive prompt. Why not get the most mileage out of that effort? Imagine if every little test that you already perform during development were somehow kept and could be rerun easily.

  • Testing helps you find errors in your code.

Speaker's notes:

Of course, you only find errors if you have written a test that exercises the particular functionality that's broken, but once you start writing unit tests, you may be surprised by how many errors you find. As you write test cases, you'll think, "Gee, I wonder whether I handle this case correctly," or, "Hm. I don't think that I handle this error correctly." When you're using a testing framework, you can simply add more test cases. The ease of adding new tests and running them encourages more thorough testing. Try it for a week, and you'll see what I mean. Many developers who have gotten in the habit of unit testing find programming without writing unit tests to be difficult and somewhat frightening. Programming is to driving like unit tests are to seat belts.

  • Testing helps you write better code.

Speaker's notes:

In addition to finding errors in your code, unit testing can help you during the initial development of your class or module's public interface. Unit tests force you to think about how another developer will want to use your code while you're writing that code. This shift in focus can help you present a smaller, cleaner interface to your classes and modules. This benefit is most often associated with test-driven development.

  • Writing test cases will save you time later.

Speaker's notes:

Imagine that you don't write test cases in code. You finish some module, and you start testing it at the interactive prompt. You realize that there's a tricky case your code doesn't handle correctly. A quick test reveals that you're right. You fix the module and move on. Later, you decide to rework the implementation of your module. Are you sure you didn't forget that tricky case? Can the new code handle it? If you had written test cases, you could just rerun the same set of tests (as long as the interface didn't change). As an added bonus, you can run your tests often so that you may find a bug after you've only written a few dozen lines of code. If a test suddenly fails, you know that it was introduced in the little bit of code you just changed. Not only is it easier to detect when you've introduced an error, but it is also easier to find the code that causes the error, reducing the time spent debugging.

  • Unit tests provide immediate feedback on your code.

Speaker's notes:

When you're writing code deep in a library or in a server side module for a user interface, a unit test gives you feedback as you work. You don't have to wait until after code in a separate part of the application is written before you can test and know whether your code works. Those little "throw-away" programs you may be writing to test your code become reusable unit tests attached to a consistent testing framework.

  • Test cases document intent.

Speaker's notes:

Test cases provide minimal documentation about what you think your code should do. Tests don't necessarily explain why your code should behave the way shown, but they can explain how it should behave. In fact, some developers write their tests before they write their code. The tests define how the unit should behave. In this case, tests always fail at first. The programmer writes code until all of the tests are passing again. This style of programming called test-first programming or test-driven programming. Test-driven development also ensures that you have unit tests for all of your code since all of the code was developed to satisfy a test.

Why unit test?

  • You're already doing it!

Speaker's notes:

You're probably already doing at least ad hoc testing at the interactive prompt. Why not get the most mileage out of that effort? Imagine if every little test that you already perform during development were somehow kept and could be rerun easily.

  • Testing helps you find errors in your code.

Speaker's notes:

Of course, you only find errors if you have written a test that exercises the particular functionality that's broken, but once you start writing unit tests, you may be surprised by how many errors you find. As you write test cases, you'll think, "Gee, I wonder whether I handle this case correctly," or, "Hm. I don't think that I handle this error correctly." When you're using a testing framework, you can simply add more test cases. The ease of adding new tests and running them encourages more thorough testing. Try it for a week, and you'll see what I mean. Many developers who have gotten in the habit of unit testing find programming without writing unit tests to be difficult and somewhat frightening. Programming is to driving like unit tests are to seat belts.

  • Testing helps you write better code.

Speaker's notes:

In addition to finding errors in your code, unit testing can help you during the initial development of your class or module's public interface. Unit tests force you to think about how another developer will want to use your code while you're writing that code. This shift in focus can help you present a smaller, cleaner interface to your classes and modules. This benefit is most often associated with test-driven development.

  • Writing test cases will save you time later.

Speaker's notes:

Imagine that you don't write test cases in code. You finish some module, and you start testing it at the interactive prompt. You realize that there's a tricky case your code doesn't handle correctly. A quick test reveals that you're right. You fix the module and move on. Later, you decide to rework the implementation of your module. Are you sure you didn't forget that tricky case? Can the new code handle it? If you had written test cases, you could just rerun the same set of tests (as long as the interface didn't change). As an added bonus, you can run your tests often so that you may find a bug after you've only written a few dozen lines of code. If a test suddenly fails, you know that it was introduced in the little bit of code you just changed. Not only is it easier to detect when you've introduced an error, but it is also easier to find the code that causes the error, reducing the time spent debugging.

  • Unit tests provide immediate feedback on your code.

Speaker's notes:

When you're writing code deep in a library or in a server side module for a user interface, a unit test gives you feedback as you work. You don't have to wait until after code in a separate part of the application is written before you can test and know whether your code works. Those little "throw-away" programs you may be writing to test your code become reusable unit tests attached to a consistent testing framework.

  • Test cases document intent.

Speaker's notes:

Test cases provide minimal documentation about what you think your code should do. Tests don't necessarily explain why your code should behave the way shown, but they can explain how it should behave. In fact, some developers write their tests before they write their code. The tests define how the unit should behave. In this case, tests always fail at first. The programmer writes code until all of the tests are passing again. This style of programming called test-first programming or test-driven programming. Test-driven development also ensures that you have unit tests for all of your code since all of the code was developed to satisfy a test.

Why unit test? (cont'd)

  • Test cases provide a sample use of your code. That is, programmers who want to use your code can read your unit tests to see how you expect client code to use it.

Speaker's notes:

If you are distributing Free Software or Open Source code, you can ship your unit tests to show others how to use your classes and modules. Even with code written for "internal use," unit tests provide simple examples of how you expect clients to interact with a unit. That way, you may be able to avoid writing separate sample programs for other programmers who need to use your code. They can just read the unit tests.

  • In a very dynamic language like Python, unit tests provide added safety. Unit tests make up for some of the compile time checks that you lose.

Speaker's notes:

For those who have never programmed in a less dynamic language, such as C++ or Java, you may not realize how important some developers feel compile-time checks are. In these languages, code is written to push as much error detection as possible to compile time so that errors won't be discovered by QA or customers at run time. In the absence of compile time checks, thorough unit testing is even more important because it can catch many simple bugs (NameErrors and such) that may only be detectable at runtime in Python.

We need a unit testing framework!

  • Testing without a framework is difficult to reproduce

Speaker's notes:

Testing without a framework is often ad hoc. The tests may not be expressed in code at all. If they are, they are often not written in a way that they can be run again in the future. If they are, the way they are written and reproduced may be different for each unit. If they are consistent, then congratulations, you've written your own framework. :-)

  • Reproducible tests that don't use a standard framework may be more difficult for other developers to understand.

Speaker's notes:

For example, the unittest (PyUnit) module implements a unit testing framework that is already implemented and used in many other programming languages. Even if a developer hasn't used the Python version of this framework, he may be familiar with it from another programming language.

  • A unit testing framework provides
    • A mechanism to organize and group multiple tests
    • A simple way to invoke tests
    • Clear indication of which tests passed/failed
    • A standard way to write tests and specify expected results.

Speaker's notes:

Of course, we still have to write the test code and specify the expected results. Even with a framework, that task can be challenging. Thus, you probably don't want to combine the challenge of writing tests with the difficulty of creating your own testing framework.

出处:http://www.cnblogs.com/dkblog/archive/2011/07/10/2102610.html

python中的单元测试pyUnit的更多相关文章

  1. Python中的单元测试模块Unittest快速入门

    前言 为什么需要单元测试? 如果没有单元测试,我们会遇到这种情况:已有的健康运行的代码在经过改动之后,我们无法得知改动之后是否引入了Bug.如果有单元测试的话,只要单元测试全部通过,我们就可以保证没有 ...

  2. Python 中 unittest 单元测试框架中需要知识点

    现在正在使用 unittest 框架,我们来记录下这个框架的知识点: unittest 框架:我们在写接口用例的时候,会继承 unittest 当中的 TestCase 的类和方法,私有方法除外,来识 ...

  3. python中的单元测试模块unittest

    unittest的属性: 该文以思维导图的形式描述unittest的重要属性. 其中前四个是unittest最核心的三个属性. testcase:测试用例: testsuite:测试套件,多个测试用例 ...

  4. 在Python中进行自动化单元测试的教程

    From: https://www.jb51.net/article/64119.htm 一.软件测试 大型软件系统的开发是一个很复杂的过程,其中因为人的因素而所产生的错误非常多,因此软件在开发过程必 ...

  5. Python项目中的单元测试

    引入 单元测试负责对最小的软件设计单元(模块)进行验证,unittest是Python自带的单元测试框架. 单元测试与功能测试都是日常开发中必不可少的部分,本文演示了Python中unittest单元 ...

  6. Python单元测试简介及Django中的单元测试

    Python单元测试简介及Django中的单元测试 单元测试负责对最小的软件设计单元(模块)进行验证,unittest是Python自带的单元测试框架. 单元测试与功能测试都是日常开发中必不可少的部分 ...

  7. Python之自动单元测试之一(unittest使用实例)

    软件的测试是一件非常乏味的事情,在测试别人编写的软件时尤其如此,程序员通常都只对编写代码感兴趣,而不喜欢文档编写和软件测试这类"没有创新"的工作.既然如此,为什么不让程序员在编写软 ...

  8. python之uinttest单元测试框架

    unittest,是python中针对单元测试的一个测试框架 相当于python版的junit 简单举个例子: 如图,使用时,测试类需要继承单元测试TestCase这个类 必须要有setUp()和te ...

  9. python中错误、调试、单元测试、文档测试

    错误分为程序的错误和由用户错误的输入引起的错误,此外还有因为各种各样意外的情况导致的错误,比如在磁盘满的时候写入.从网络爬取东西的时候,网络断了.这类错误称为异常 错误处理 普通的错误处理机制就是在出 ...

随机推荐

  1. 联合体union

    1.一般而言,共用体类型实际占用存储空间为其最长的成员所占的存储空间: //4*7==282.若是该最长的存储空间对其他成员的元类型(如果是数组,取其类型的数据长度,例int a[5]为4)不满足整除 ...

  2. zabbix安装配置agent程序之agent配置文件详解

    安装zabbix-agent http://repo.zabbix.com/zabbix/3.2/rhel/6/x86_64/ 下载:zabbix-agent-3.2.0-1.el6.x86_64.r ...

  3. H3C交换机配置镜像端口

    配置步骤 进入配置模式:system-view: 创建本地镜像组:mirroring-group 1 local 为镜像组配置源端口:mirroring-group 1 mirroring-port ...

  4. Linux下解压分包文件zip(zip/z01/z02)【转】

    本文转载自:https://www.cnblogs.com/EasonJim/p/7227109.html?utm_source=itdadao&utm_medium=referral Lin ...

  5. Linux系统故障-Repair filesystem

    fsck /dev/hddn (代表根目录所在的区) fsck -A -y 重启系统可以进去了:- ) fsck命令的主要选项如下: -A 检查所有列在etc/fstab文件中的文件系统.带有这个选项 ...

  6. Record and accumulation

    最近有同学在准备校招的问题,问我几个问题,我觉得有必要把大家的问题汇总下: 1.在设计变量的while指挥时候,可以利用弹栈的特性以及Java传值 只是传递的副本  去控制 : https://www ...

  7. AppWidget源码分析---updateAppWidget过程分析

    转[原文] 前面一篇文章,分析了AppWidgetProvider和RemoteView的源码,从中我们可以知道它们的实现原理,AppWidgetProvider是一个BroadcastReceive ...

  8. RemoveDuplicatesFromSortedArrayI II,移除有序数组里的重复元素以及移除数组里的某个元素

    RemoveDuplicatesFromSortedArrayI: 问题描述:给定一个有序数组,去掉其中重复的元素.并返回新数组的长度.不能使用新的空间. [1,1,2,3] -> [1,2,3 ...

  9. oracle 子查询详解 in和exists的区别

    sql允许多层嵌套,子查询是嵌套在其他查询中的查询.我们可以把子查询当做一张表来看到,即外层语句可以把内嵌的查询结果当做一张表使用. 子查询查询结果有三种情况 不返回查询记录.若子查询不返回记录则主查 ...

  10. jQuery中hover和blur使用代理delegate无效的解决方法

    今天就遇到了这样的小问题: $(document).ready(function(){ $('.status_on').hover(function(){ $(this).html('点击禁用'); ...