一些基本概念
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.pyclass 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.pyfrom Rectangle import Rectangleimport unittestclass 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 suiteif __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