1 Fixture 概念
Fixture是测试中的概念:
- Fixture 指的是测试中依赖的数据和条件等等
- Python的 unittest 库提供了对 fixture的一些支持
- 每个TestCase 应该在setUp中, 自己负责资源的创建, 例如
class MyTestCase(unittest.TestCase): def my_fixture_setup(self): pass def setUp(self): super(MyTestCase, self).setUp() self.my_fixture_setup()
- 每个TestCase 应该新建一个函数, 负责资源的销毁. 并把这个新的函数加入到TestCase的cleanup列表当中
class MyTestCase(unittest.TestCase): def my_fixture_cleanup(self): print("++++ my_cleanup") def setUp(self): super(MyTestCase, self).setUp() self.addCleanup(self.my_fixture_cleanup)
以下是完整的代码
from __future__ import print_function import unittest class MyTestCase(unittest.TestCase): def my_fixture_setup(self): pass def my_fixture_cleanup(self): print("++++ my_cleanup") def setUp(self): super(MyTestCase, self).setUp() self.my_fixture_setup() self.addCleanup(self.my_fixture_cleanup) def tearDown(self): super(MyTestCase, self).tearDown() print("++++ tearDown") def my_cleanup(self): print("++++ my_cleanup") def test_case_1(self): print("++++ test case 1")
2 Python 中的 Fixtures 包
Fixtures(复数)是Python中的一个包, 提供了一些工具包来快速创建/销毁 fixture
https://pypi.python.org/pypi/fixtures
- Test Case需要派生于 testtools.TestCase 类
- 如果需要自定义Fixtures, 需要派生于 fixtures.Fixture类, 并覆写父类的setUp/cleanUp方法
一个自定义Fixtures类的例子如下
from __future__ import print_function import fixtures import testtools class MyFixture(fixtures.Fixture): def setUp(self): super(MyFixture,self).setUp() self.frobnozzle = 42 print("++++ MyFixture.setup()") def cleanUp(self): super(MyFixture,self).cleanUp() print("++++ MyFixture.cleanup()") print() class MyTestCase(testtools.TestCase): def setUp(self): super(MyTestCase, self).setUp() self.my_fixture = self.useFixture(MyFixture()) print("++++ setUp") def tearDown(self): super(MyTestCase, self).tearDown() print("++++ tearDown") def test_case_1(self): self.assertEqual(42, self.my_fixture.frobnozzle) print("++++ test case 1")
时间: 2024-10-12 20:17:29