您的位置:首页 > 编程语言 > Python开发

PYTHON单元测试模块unittest

2011-09-18 22:43 796 查看
一些基本概念

test fixture

    A test fixture represents the preparation needed to perform one or moretests, and any associate cleanup actions. This may involve, for example,creating temporary or proxy databases, directories, or starting a serverprocess.

test case

    A test case is the smallest unit of testing. It checks for a specificresponse to a particular set of inputs. unittest provides a base class,TestCase, which may be used to create new test cases.

test suite

    A test suite is a collection of test cases, test suites, or both. It isused to aggregate tests that should be executed together.

test runner
    A test runner is a component which orchestrates the execution of testsand provides the outcome to the user. The runner may use a graphical interface,a textual interface, or return a special value to indicate the results ofexecuting the tests.

下面是简单的一个例子

#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())

运行结果如下

joe@joe:/mnt/share$ python pytest.py

.F

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

FAIL: testArea (__main__.RectangleTestCase)

----------------------------------------------------------------------

Traceback (most recent call last):

  File "pytest.py", line 15, in testArea

    self.assertEqual(self.rectangle.area(), 100)

AssertionError: 50 != 100

----------------------------------------------------------------------

Ran 2 tests in 0.007s

FAILED (failures=1)

可以看到提示有一个失败,因为在算面积的时候不正确,应该是50才对,把pytest.py的内容改一下

def testArea(self):
self.assertEqual(self.rectangle.area(), 50)再跑一遍试试
joe@joe:/mnt/share$ python pytest.py

..

----------------------------------------------------------------------

Ran 2 tests in 0.000s

这下就OK了,没有错误。

下面是一些相关资料:

PYTHON官方文档

Python Unit Testing Framework
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息