本文整理汇总了Python中mock.MagicMock.attach_mock方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.attach_mock方法的具体用法?Python MagicMock.attach_mock怎么用?Python MagicMock.attach_mock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.attach_mock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_mapper_args_value
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_mapper_args_value(self, db, bridge, mocker):
"""
Test checks:
1) that 'FeedItem' class is instantiated once with correct arguments
2) that 'self.mapper' method is called once with correct arguments,
Actually, with the item yielded by 'get_tenders' function.
3) that 'self.mapper' was called AFTER 'FeedItem' class instantiated.
"""
mock_feed_item = mocker.patch.object(databridge_module, 'FeedItem',
side_effect=FeedItem,
autospec=True)
manager = MagicMock()
mock_mapper = MagicMock()
bridge['bridge'].mapper = mock_mapper
manager.attach_mock(mock_mapper, 'mock_mapper')
manager.attach_mock(mock_feed_item, 'mock_feed_item')
bridge['bridge_thread'].join(0.1)
manager.assert_has_calls(
[call.mock_feed_item(bridge['tenders'][0]),
call.mock_mapper(mock_feed_item(bridge['tenders'][0]))]
)
示例2: track
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def track(**mocks):
tracker = MagicMock()
for name, mocker in mocks.items():
tracker.attach_mock(mocker, name)
return tracker
示例3: WhenTestingStoragePersistence
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
class WhenTestingStoragePersistence(unittest.TestCase):
def setUp(self):
self.message = {
"processid": "3071",
"appname": "dhcpcd",
"timestamp": "2013-04-05T15:51:18.607457-05:00",
"hostname": "tohru",
"priority": "30",
"version": "1",
"messageid": "-",
"message": "wlan0: leased 10.6.173.172 for 3600 seconds\n",
"sd": {
"origin": {
"software": "rsyslogd",
"swVersion": "7.2.5",
"x-pid": "24592",
"x-info": "http://www.rsyslog.com"
}
}
}
self.sink = MagicMock()
self.sink.attach_mock(MagicMock(), 'put')
self.db_handler = MagicMock(return_value=self.sink)
def test_persist_message_calls_db_put(self):
with patch('meniscus.api.storage.persistence.db_handler',
self.db_handler):
persist_message(self.message)
self.sink.put.assert_called_once_with('logs', self.message)
示例4: ValidatableMixin_UnitTests
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
class ValidatableMixin_UnitTests(unittest.TestCase):
def setUp(self):
self.name = ''.join([fake.random_letter() for _ in range(20)])
self.value = ''.join([fake.random_letter() for _ in range(20)])
self.mock_validator = MagicMock()
self.mock_validate_method = MagicMock()
self.mock_validator.attach_mock(self.mock_validate_method,
'validate')
def test_validate_attr_calls_validate_as_expected(self):
mixin = mixins.ValidatableMixin()
mixin.validate_attr(self.name, self.value, self.mock_validator)
self.mock_validate_method.assert_called_once_with(self.value)
def test_validate_attr_raises_validation_error(self):
mixin = mixins.ValidatableMixin()
self.mock_validate_method.side_effect = validators.ValidationError()
self.assertRaises(validators.ValidationError,
lambda: mixin.validate_attr(
self.name,
self.value,
self.mock_validator))
def test_validate_attr_validation_error_message_format(self):
mixin = mixins.ValidatableMixin()
self.mock_validate_method.side_effect = \
validators.ValidationError("I'm a little tea pot")
try:
mixin.validate_attr(
self.name,
self.value,
self.mock_validator)
except validators.ValidationError as e:
self.assertEqual(e.message,
"{name} failed validation: {msg}".format(
name=self.name,
msg="I'm a little tea pot"))
def test_validate_attr_raises_other_errors(self):
mixin = mixins.ValidatableMixin()
self.mock_validate_method.side_effect = TypeError()
self.assertRaises(TypeError,
lambda: mixin.validate_attr(
self.name,
self.value,
self.mock_validator))
def test_validate_all_hits_all_validators(self):
self.skipTest("Not implemented")
示例5: test_invalid_status_request_raises_ValidationError
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_invalid_status_request_raises_ValidationError(self):
gateway = veritrans.VTDirect(server_key=self.server_key)
status_req = MagicMock(spec=request.StatusRequest)
mock_validate = MagicMock(side_effect=validators.ValidationError)
status_req.attach_mock(mock_validate, 'validate_all')
self.assertRaises(validators.ValidationError,
lambda: gateway.submit_status_request(status_req))
self.assertEqual(mock_validate.call_count, 1)
示例6: test_order
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_order(self):
manager = MagicMock()
with patch(REQUEST_MODULE) as Request:
with patch(RESPONSE_MODULE) as Response:
manager.attach_mock(Request, 'Request')
manager.attach_mock(Response, 'Response')
self.client.get('/')
# Ugly method, but couldn't find a better one
first = manager.mock_calls[0].__str__()
last = manager.mock_calls[-1].__str__()
self.assertTrue(first.startswith('call.Request'))
self.assertTrue(last.startswith('call.Response'))
示例7: test_invalid_approval_request_raises_ValidationError
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_invalid_approval_request_raises_ValidationError(self):
'''
Validation error should be bubbled-up to the calling client code.
'''
gateway = veritrans.VTDirect(server_key=self.server_key)
approval_req = MagicMock(spec=request.ApprovalRequest)
mock_validate = MagicMock(side_effect=validators.ValidationError)
approval_req.attach_mock(mock_validate, 'validate_all')
self.assertRaises(validators.ValidationError,
lambda: gateway.submit_status_request(approval_req))
self.assertEqual(mock_validate.call_count, 1)
示例8: test_submit_credit_card_charge
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_submit_credit_card_charge(self):
'''
Large test for submitting credit card charge.
- Do we make our HTTP Request with the expected values
- Do we get the correct response type back?
- Does the response contain the data that it should?
'''
with patch('veritranspay.veritrans.requests.post') as mock_post:
# create a fake key and request payload
payload = {'charge_type': 'I am a little tea cup',
}
gateway = veritrans.VTDirect(server_key=self.server_key)
req = MagicMock()
req.charge_type = MagicMock(spec=payment_types.CreditCard)
req.attach_mock(MagicMock(return_value=payload),
'serialize')
# mock the response data
# so thta the JSON method returns a documented response
# value
mock_resp = MagicMock()
mock_post.return_value = mock_resp
mock_resp.attach_mock(
MagicMock(return_value=fixtures.CC_CHARGE_RESPONSE_SUCCESS),
'json')
resp = gateway.submit_charge_request(req)
# make sure requests library was called in the expected way.
mock_post.assert_called_once_with(
'https://api.veritrans.co.id/v2/charge',
auth=(self.server_key, ''),
headers={'content-type': 'application/json',
'accept': 'application/json'},
data=json.dumps(payload))
# did we get the expected response type?
self.assertIsInstance(resp, response.CreditCardChargeResponse)
# did it look like we expected
expected_response_format = response.CreditCardChargeResponse(
**fixtures.CC_CHARGE_RESPONSE_SUCCESS)
# need to compare their dictionary formats
self.assertEqual(expected_response_format.__dict__,
resp.__dict__)
示例9: test_invalid_charge_request_raises_ValidationError
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_invalid_charge_request_raises_ValidationError(self):
'''
Make sure that if any of the sub-entities raise a ValidationError
that it is bubbled out to calling code.
'''
gateway = veritrans.VTDirect(server_key=self.server_key)
charge_req = MagicMock(spec=request.ChargeRequest)
mock_validate = MagicMock(side_effect=validators.ValidationError)
charge_req.attach_mock(mock_validate, 'validate_all')
self.assertRaises(validators.ValidationError,
lambda: gateway.submit_charge_request(charge_req))
self.assertEqual(mock_validate.call_count, 1)
示例10: test_lock_released
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_lock_released(self):
b = Block()
b.name = "blockname"
b.lock.acquire = MagicMock(wrap=b.lock.acquire)
b.lock.release = MagicMock(wrap=b.lock.release)
lock_methods = MagicMock()
lock_methods.attach_mock(b.lock.acquire, "acquire")
lock_methods.attach_mock(b.lock.release, "release")
with b.lock:
with b.lock_released():
pass
self.assertEquals(
[call.acquire(), call.release(), call.acquire(), call.release()],
lock_methods.method_calls)
示例11: test_validate_all_called_on_value
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_validate_all_called_on_value(self):
'''
When passed a scalar, passthrough validator should call validate_all
on the scalar.
'''
v = validators.PassthroughValidator()
mock = MagicMock()
# mocks are iterable .. we don't want that here
mock.attach_mock(MagicMock(side_effect=TypeError), '__iter__')
validate_mock = MagicMock()
mock.attach_mock(validate_mock, 'validate_all')
v.validate(mock)
validate_mock.assert_called_once_with()
示例12: test_submit_virtualaccountmandiri_charge
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_submit_virtualaccountmandiri_charge(self):
with patch('veritranspay.veritrans.requests.post') as mock_post:
# create a fake key and request payload
payload = {'charge_type': 'I am a little tea cup',
}
gateway = veritrans.VTDirect(server_key=self.server_key)
req = MagicMock()
req.charge_type = MagicMock(spec=payment_types.VirtualAccountMandiri)
req.attach_mock(MagicMock(return_value=payload), 'serialize')
# mock the response data
# so thta the JSON method returns a documented response
# value
mock_resp = MagicMock()
mock_post.return_value = mock_resp
mock_resp.attach_mock(
MagicMock(return_value=fixtures.VIRTUALACCOUNTMANDIRI_CHARGE_RESPONSE_SUCCESS),
'json')
resp = gateway.submit_charge_request(req)
# make sure requests library was called in the expected way.
mock_post.assert_called_once_with(
'https://api.midtrans.com/v2/charge',
auth=(self.server_key, ''),
headers={'content-type': 'application/json',
'accept': 'application/json'},
data=json.dumps(payload))
# did we get the expected response type?
self.assertIsInstance(resp, response.VirtualAccountMandiriChargeResponse)
# did it look like we expected
expected_response_format = response.VirtualAccountMandiriChargeResponse(
**fixtures.VIRTUALACCOUNTMANDIRI_CHARGE_RESPONSE_SUCCESS)
# need to compare their dictionary formats
self.assertEqual(expected_response_format.__dict__,
resp.__dict__)
示例13: test_connection_is_cached_basic_auth
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_connection_is_cached_basic_auth():
httpretty.register_uri(httpretty.POST, FAKE_EXCHANGE_URL,
status=200,
body="", )
manager = MagicMock()
with patch('pyexchange.connection.HTTPBasicAuth') as MockHttpBasicAuth:
manager.attach_mock(MockHttpBasicAuth, 'MockHttpBasicAuth')
connection = ExchangeBasicAuthConnection(url=FAKE_EXCHANGE_URL,
username=FAKE_EXCHANGE_USERNAME_BASIC_AUTH,
password=FAKE_EXCHANGE_PASSWORD)
connection.send("test")
connection.send("test again")
# assert we only get called once, after that it's cached
manager.MockHttpBasicAuth.assert_called_once_with(FAKE_EXCHANGE_USERNAME_BASIC_AUTH, FAKE_EXCHANGE_PASSWORD)
示例14: test_session_is_cached
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_session_is_cached():
manager = MagicMock()
httpretty.register_uri(httpretty.POST, FAKE_EXCHANGE_URL,
status=200,
body="", )
with patch('requests.Session') as MockSession:
manager.attach_mock(MockSession, 'MockSession')
connection = ExchangeNTLMAuthConnection(url=FAKE_EXCHANGE_URL,
username=FAKE_EXCHANGE_USERNAME,
password=FAKE_EXCHANGE_PASSWORD)
connection.send("test")
connection.send("test again")
# assert we only get called once, after that it's cached
manager.MockSession.assert_called_once_with()
示例15: test_validate_all_called_on_iterable_elements
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import attach_mock [as 别名]
def test_validate_all_called_on_iterable_elements(self):
'''
When passed an iterable, validate_all should be called on the elements
of the iterable.
'''
v = validators.PassthroughValidator()
# note: doesn't matter here whether the mocks are iterable or not
mock1 = MagicMock()
validate_mock1 = MagicMock()
mock1.attach_mock(validate_mock1, 'validate_all')
mock2 = MagicMock()
validate_mock2 = MagicMock()
mock2.attach_mock(validate_mock2, 'validate_all')
mocks = [mock1, mock2]
v.validate(mocks)
validate_mock1.assert_called_once_with()
validate_mock2.assert_called_once_with()