Some Basic Concepts
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 particle 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 shocould 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.
The following is a simple example.
#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())
The running result is as follows:
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.007 s
Failed (failures = 1)
We can see that there is a failure prompt, because it is incorrect when calculating the area, it should be 50, change the content of pytest. py
def testArea(self): self.assertEqual(self.rectangle.area(), 50)
Try again
Joe @ Joe:/mnt/share $ Python pytest. py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000 s
This is OK, no error.
The following are some related materials:
Python official documentation
Python unit testing framework