1. If I want to mock the date object in the library, but I just want to mock the Today () method, that is, today () returns the results I want, but other date initialization methods cannot be changed.
From datatime import date with
patch (' mymodule.date ') as mock_date:
mock_date.taday.return_value = Date ( 2010,10,8)
Mock_date.side_effect = Lambda *args, **kw:date (*args, **kw)
assert mymodule.date.today () = = Date ( 2010,10,8)
assert mymodule.date (2009,6,8) = = Date (2009,6,8)
2. Configure mocks
mock = Mock ()
attrs = {' Method.return_value ': 3, ' Other.side_effect ': Keyerror}
mock.configure_mock (**attrs)
Mock.method () # return 3
mock.other () # return Keyerror
3.mock functions used in other module
If test_fuction_uu.py to test Fuction_uu, but Fuction_uu called myfuction, I want to mock this myfuction. Finally, it was done in the patch way below.
test_module.py
Def myfuction (): Return
2
def fuction_uu (): Return
myfuction ()
test_mock_fuction.py
@patch (' Test_module.myfuction ', magicmock (return_value =))
def test_faction_uu ():
print Fuction_uu (
if __name__ = = ' __main__ ':
test_faction_uu ()
4. For class patch, note that Setup and teardown, in the official mock document, say that if an exception is thrown in Setup, then teardown will not be executed, which could create a hole. The document says that using the cleanup function in Unittest2 can avoid this problem.
Class MyTest ():
def setUp (self):
patcher = Patch (' Package.module.Class ')
self. Mockclass = Patcher.start ()
self.addcleanup (patcher.stop)
def test_something (self):
assert package. Module.class is self. Mockclass
5.patch.object can have the effect of "replace" parameters, the following
@patch. Object (SomeClass, ' Class_mothod ')
def Test (mock_method):
someclass.class_method (3)
Mock_ Method.assert_called_with (3)
test () # Attention:no parameter!
6.mock Database Operations
mock = mock ()
cursor = mock.connection.cursor.return_value
cursor.execute.return_value = [' foo ']
Mock.conection.cursor (). Execute ("SELECT 1")
# return [' foo ']
expected = Call.connection.cursor (). Execute (" Select 1 ")
mock.mock_calls
#return [Call.connection.cursor (), Call.connection.cursor (). Ececute (' Select 1 ')]
mock.mock_calls = = expected
#return True