Python之PyUnit单元测试实例

yipeiwu_com6年前Python基础

本文实例讲述了Python之PyUnit单元测试,与erlang eunit单元测试很像,分享给大家供大家参考。具体方法如下:

1.widget.py文件如下:

复制代码 代码如下:
#!/usr/bin/python
# Filename: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):
passDefaultTestCase

2. auto.py文件如下:

复制代码 代码如下:
#!/usr/bin/python
# Filename:auto.py
 
import unittest
from widget import Widget
 
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
 
def tearDown(self):
self.widget = None
 
def testSize(self):
self.assertEqual(self.widget.getSize(), (50, 40))
 
def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
return suite
 
if __name__ == "__main__":
unittest.main(defaultTest = 'suite')

3.执行结果如下:

[code]jobin@jobin-desktop:~/work/python/py_unit$ python auto.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
 
OK
jobin@jobin-desktop:~/work/python/py_unit$ python auto.py
F
======================================================================
FAIL: testSize (__main__.WidgetTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "auto.py", line 15, in testSize
self.assertEqual(self.widget.getSize(), (50, 40))
AssertionError: (40, 40) != (50, 40)
 
----------------------------------------------------------------------
Ran 1 test in 0.000s
 
FAILED (failures=1)
jobin@jobin-desktop:~/work/python/py_unit$[/code]

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

相关文章

python3实现猜数字游戏

python3实现猜数字游戏

本文实例为大家分享了python3实现猜数字游戏的具体代码,供大家参考,具体内容如下 需求目标: 需求:猜数字游戏 1: 开始游戏产生一个1~100随机数 2: 用户输入,游戏根据输入...

详解使用python的logging模块在stdout输出的两种方法

详解使用python的logging模块在stdout输出 前言:   使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志...

详解python使用递归、尾递归、循环三种方式实现斐波那契数列

详解python使用递归、尾递归、循环三种方式实现斐波那契数列

在最开始的时候所有的斐波那契代码都是使用递归的方式来写的,递归有很多的缺点,执行效率低下,浪费资源,还有可能会造成栈溢出,而递归的程序的优点也是很明显的,就是结构层次很清晰,易于理解 可...

基于Python函数和变量名解析

基于Python函数和变量名解析

1、Python函数 函数是Python为了代码最大程度的重用和最小化代码冗余而提供的基本程序结构,用于将相关功能打包并参数化 Python中可以创建4种函数: 1)、全局函数:定义在...

Python编程中的文件操作攻略

Python编程中的文件操作攻略

open函数 你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的辅助方法才可以调用它进行读写。 语法: file object = open(f...