Python单元测试框架使用unittestpyUnit

本文介绍如何使用Pyunit框架进行基本的测试,包括整数乘法和浮点数乘法的验证。

使用Pyunit框架的简单测试

'''
Created on 2014-4-15

@author: Administrator
'''
import unittest,my_math


class Test(unittest.TestCase):

    def testIntegers(self):
        for x in xrange(-10,10):
            for y in xrange(-10,10):
                p = my_math.product(x,y)
                self.failUnless(p == x*y,'Integer multiplication faild')
    def testFloat(self):
        for x in  xrange(-10,10):
            for y in xrange(-10,10):
                x = x/10.0
                y = y/10.0
                p = my_math.product(x,y)
                self.failUnless(p == x*y,'Float multiplication faild')
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()
my_math.py

'''
Created on 2014-4-15

@author: Administrator
'''
def square(x):
    '''
    Squares a number and return the result.
    
    >>>square(2)
    4
    >>>square(3)
    9
    '''
    return x*x

def product(x,y):
    if x == 7 and y ==9:
        return 'bug'
    else:
        return x * y
    #return x*y

'''
if __name__ == '__main__':
    import doctest, my_math 
    doctest.testmod(my_math) 
'''

unittest.main函数负责运行测试。它会实例化所有TestCase的子类,运行所有名字以test开头的方法。

如果定义了叫做setUp和tearDown的方法,他们就会运行在每个测试方法之前和之后执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值