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. SQL-ALTER-change和modify区别

      ALTER 对于列的应用:   1.更改列名      格式:CHANGE old_col_name new_col_name column_definition      保留old和new列名 ...

  2. Oracle sql plus中常用的几个命令

    1.set linesize 300(表示一行为300个字符) set linesize可以设置一行显示的字符数,默认情况下为80个字符 2.l(list) 可以显示缓冲区中的最后执行的内容 3.ru ...

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

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

  4. 使用C语言扩展Python提供性能

    python底层是用c写的,c本身是一个非常底层的语言,所以它做某些事情的效率肯定会比上层语言高一些. 比如有些自动化测试用的python库,会对系统的UI进行一些捕获,点击之类的操作,这必然要用到c ...

  5. [BZOJ1257]余数之和

    Description 给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 + … + k mod n的值 其中k mod i表示k除以i的余数. 例如j(5 ...

  6. SpringBoot2.0之整合ElasticSearch

    就类比数据库到时候去实现 服务器端配置 集群名字  与yml名字一致 pom: <project xmlns="http://maven.apache.org/POM/4.0.0&qu ...

  7. [CTSC2008]祭祀river

    Description 在遥远的东方,有一个神秘的民族,自称Y族.他们世代居住在水面上,奉龙王为神.每逢重大庆典, Y族都 会在水面上举办盛大的祭祀活动.我们可以把Y族居住地水系看成一个由岔口和河道组 ...

  8. PAT1051. Pop Sequence (25)

    #include <iostream> #include <stack> using namespace std; int sizeMax,n,k; stack<int& ...

  9. 从互信息的角度来理解tf-idf

    先介绍tf idf 在一份给定的文件里,词频(term frequency,tf)指的是某一个给定的词语在该文件中出现的频率.这个数字是对词数(term count)的归一化,以防止它偏向长的文件.( ...

  10. Mongodb笔记(三)user && aggregate && mapReduce

    版本:mongodb3.4. User: mongodb使用验证登录:默认不开启,mongod中使用--auth开启:  mongod -port=3000 --auth  : 基本方法: db.cr ...