OK http://catmic27.blog.51cto.com/2517040/946852
OK http://blog.csdn.net/wh62592855/article/details/6788221
http://pyunit.sourceforge.net/pyunit_cn.html
http://www.cnblogs.com/imouren/archive/2011/08/04/2127997.html
unittest是python单元测试框架,又叫做PyUnit。之所以称为框架是它代替开发人员完成了一些调用、IO等与单元测试无直接关系的支撑代码,让开发人员可以专注与测试用例的编写,简化单元测试工作。
#FileName: ut_target.py
class EqualToZero(Exception):
pass
class SplitZero(object):
def splitzero(self, num):
if num > 0:
return "num is bigger than zero"
elif num < 0:
return "num is smaller than zero"
else:
raise EqualToZero
#FileName: utest.py
from ut_target import SplitZero, EqualToZero
import unittest
class SzTestCase(unittest.TestCase):
def setUp(self):
print "test start"
def tearDown(self):
print "test stop"
def testSzBig(self):
num = 10
sz = SplitZero()
self.assertEqual(sz.splitzero(num),"num is bigger than zero")
def testSzSmall(self):
num = -10
sz = SplitZero()
self.assertEqual(sz.splitzero(num),"num is smaller than zero")
def testSzEqual(self):
num = 0
sz = SplitZero()
self.assertRaises(EqualToZero, sz.splitzero, num)
if __name__ == "__main__":
unittest.main()
[[email protected]]$python utest.py -v
testSzBig (__main__.SzTestCase) ... test start
test stop
ok
testSzEqual (__main__.SzTestCase) ... test start
test stop
ok
testSzSmall (__main__.SzTestCase) ... test start
test stop
ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
#Rectangle.py
class Rectangle:
def __init__(self,length,width):
self.length = length
self.width = width
def girth(self):
return 2*(self.length+self.width)
def area(self):
return self.length*self.width
#pytest.py
from Rectangle import Rectangle
import unittest
class RectangleTestCase(unittest.TestCase):
def setUp(self):
self.rectangle = Rectangle(10,5)
def tearDown(self):
self.rectangle = None
def testGirth(self):
self.assertEqual(self.rectangle.girth(), 30)
def testArea(self):
self.assertEqual(self.rectangle.area(), 100)
def suite():
suite = unittest.TestSuite()
suite.addTest(RectangleTestCase("testGirth"))
suite.addTest(RectangleTestCase("testArea"))
return suite
if __name__ == "__main__":
unittest.TextTestRunner().run(suite())
[[email protected]]$python pytest.py -v
.F
======================================================================
FAIL: testArea (__main__.RectangleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "pytest.py", line 17, in testArea
self.assertEqual(self.rectangle.area(), 100)
AssertionError: 50 != 100
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1)