????????????????OpenStack?й?????????python ?????????????
????1. [mox] StubOutWithMock
??????OpenStack??test code?????????????mox?????StubOutWithMock?? ???function????????????mock????????Щ????????????. ???????????OpenStack?д?????Σ????????StubOutWithMock?÷???
????self.mox.StubOutWithMock(quota.QUOTAS?? "reserve")
????quota.QUOTAS.reserve(self.context?? instances=40??cores=mox.IsA(int)??ram=mox.IsA(int)).AndRaise(quota_exception) #mox.IsA?????????????????????
????self.mox.ReplayAll()
????function(...) #?????????????????? ??????ù?quota.QUOTAS.reserve?????function??
????#?????????????????function
????2.[mock] mock.patch & mock.patch.object
??????????????????class?? function?? attribute  ???????mock.
???????????????????????????
????mock.patch(target?? ...)
????mock.patch.object(target?? attribute?? ...)
????????target??mock?? ???target??????class?? function
?????????target???attribute??mock?? ???????????????????????function.
?????????????? ???????????????д???? ????decorators?? ????python?е????@?? ???????with??? ?????????д?????????
????????????????func()????????
class A(object):
def func(self):
return B.getFromDB('b')
class B(object):
def getFromDB(self?? param):
...
???????????????????
"""?????д???? decorators????? ????mock.patch??????????.
???ж??????????????????????? ??
@mock.patch('B.getFromDB')
@mock.patch('B.getFromXX')
def test_func(self?? mock_getFromXX?? mock_getFromDB):
?????????@???????????б???????棬 ?????????@?????????@mock.patch('B.getFromDB')(@mock.patch('B.getFromXX')(func)) ??????
"""
@mock.patch('B.getFromDB')
def test_func(self?? mock_getFromDB):
mock_getFromDB.return_value = '1'
self.assertEqual('1'?? A.func())
"""?????д?? ??decorators????? ????mock.patch. object??????????.
"""
@mock.patch.object(B?? 'getFromDB')
def test_func(self?? mock_getFromDB):
mock_getFromDB.return_value = '1'
self.assertEqual('1'?? A.func())
"""??????д???? with statement?? ????mock.patch??????????.
"""
def test_func(self?? mock_getFromDB):
with mock.patch('B.getFromDB') as mock_getFromDB:
mock_getFromDB.return_value = '1'
self.assertEqual('1'?? A.func())
"""??????д???? with statement?? ????mock.patch.object??????????.
"""
def test_func(self?? mock_getFromDB):
with mock.patch.object(B?? 'getFromDB') as mock_getFromDB:
mock_getFromDB.return_value = '1'
self.assertEqual('1'?? A.func())
??????????????У? ????mock.patch???????function?? ??????class?? ??????mock.patch document ???????????
>>> class Class(object):
...     def method(self):
...         pass
...
>>> with patch('__main__.Class') as MockClass:
...     instance = MockClass.return_value #???????????'__main__.Class'???class?? ????????????intance??????
...     instance.method.return_value = 'foo' #????????class???????atribute?? ???????????method()?????? ????????????
...     assert Class() is instance
...     assert Class().method() == 'foo'
?????????class?? ??OpneStack????component????????????.