声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:http://blog.csdn.net/halcyonbaby
内容系本人学习、研究和总结,如有雷同,实属荣幸!
Mock方法和属性:
>>> # Mock
>>> my_mock = mock.Mock()
>>> my_mock.some_method.return_value = "calculated value"
>>> my_mock.some_attribute = "value"
>>> assertEqual("calculated value", my_mock.some_method())
>>> assertEqual("value", my_mock.some_attribute)
>>> # Mox
>>> my_mock = mox.MockAnything()
>>> my_mock.some_method().AndReturn("calculated value")
'calculated value'
>>> my_mock.some_attribute = "value"
>>> mox.Replay(my_mock)
>>> assertEqual("calculated value", my_mock.some_method())
>>> assertEqual("value", my_mock.some_attribute)
部分mock(对已有对象的某个方法进行mock):
>>> # Mock
>>> SomeObject.some_method = mock.Mock(return_value='value')
>>> assertEqual("value", SomeObject.some_method())
>>> # Mox
>>> my_mock = mox.MockObject(SomeObject)
>>> my_mock.some_method().AndReturn("value")
'value'
>>> mox.Replay(my_mock)
>>> assertEqual("value", my_mock.some_method())
>>> mox.Verify(my_mock)
抛出异常:
>>> # Mock
>>> my_mock = mock.Mock()
>>> my_mock.some_method.side_effect = SomeException("message")
>>> assertRaises(SomeException, my_mock.some_method)
>>> # Mox
>>> my_mock = mox.MockAnything()
>>> my_mock.some_method().AndRaise(SomeException("message"))
>>> mox.Replay(my_mock)
>>> assertRaises(SomeException, my_mock.some_method)
>>> mox.Verify(my_mock)
---------------myfixture.py-----------------------
import testtools
import unittest
import fixtures
class NoddyFixture(fixtures.Fixture):
def setUp(self):
super(NoddyFixture, self).setUp()
self.frobnozzle = 42
self.addCleanup(delattr, self, 'frobnozzle')
class NoddyTest(testtools.TestCase, fixtures.TestWithFixtures):
def test_example(self):
fixture = self.useFixture(NoddyFixture())
self.assertEqual(42, fixture.frobnozzle)
result = unittest.TestResult()
_ = NoddyTest('test_example').run(result)
print (result.wasSuccessful())
-----------------运行结果------------------------
[root@centoo65 data]# python myfixtures.py
True
-----------常用fixture-------------------------
>>> import fixtures
>>> a = fixtures.TempDir()
>>> a.setUp()
>>> print a.path
/tmp/tmpWB8EmF
>>> quit()
----------------------------------------------
其他参见PolicyFixture
顶级目录test.py中:
test.TestCase继承于testtools.TestCase。
test.NoDBTestCase继承于test.TestCase。
test.TestCase中大量使用了fixture对环境进行初始化。(比如DB,Policy等)