本文整理汇总了Python中unittest.mock.MagicMock.assert_called_once_with方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.assert_called_once_with方法的具体用法?Python MagicMock.assert_called_once_with怎么用?Python MagicMock.assert_called_once_with使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest.mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.assert_called_once_with方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestDirChangeEventHandler
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
class TestDirChangeEventHandler(TestCase):
def setUp(self):
self._on_create = MagicMock()
self._on_delete = MagicMock()
self._sut = DirChangeEventHandler(self._on_create, self._on_delete)
def test_init_raises_exception_if_new_file_is_not_callable(self):
self.assertRaises(InvalidCallable, DirChangeEventHandler, 1, lambda x: x)
def test_init_raises_exception_if_file_delete_is_not_callable(self):
self.assertRaises(InvalidCallable, DirChangeEventHandler, lambda x: x, 1)
def test_init(self):
self.assertEqual(self._on_create, self._sut.new_file_callable)
self.assertEqual(self._on_delete, self._sut.file_deleted_callable)
def test_on_create_calls_proper_handler(self):
event = {}
self._sut.on_created(event)
self._on_create.assert_called_once_with(event)
def test_on_delete_calls_proper_handler(self):
event = {}
self._sut.on_deleted(event)
self._on_delete.assert_called_once_with(event)
示例2: TestEventListener
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
class TestEventListener(TestCase):
def setUp(self):
self._cofunc_call_count = 0
self._cofunc_calls = []
@asyncio.coroutine
def a(event):
nonlocal self
self._cofunc_call_count += 1
self._cofunc_calls.append(event)
yield from asyncio.sleep(0)
self.e = Event("event")
self.func = MagicMock(_is_coroutine=False)
self.cofunc = a
self.func_listener = EventListener(self.func)
self.cofunc_listener = EventListener(self.cofunc)
def test_func(self):
self.func_listener(self.e)
self.func.assert_called_once_with(self.e)
@sync
@asyncio.coroutine
def test_cofunc(self):
yield from self.cofunc_listener(self.e)
self.assertEqual(self._cofunc_call_count, 1)
self.assertEqual(self._cofunc_calls[0], self.e)
示例3: test_sm_daemon_receive_message
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_sm_daemon_receive_message(sm_config, clean_ds_man_mock, delete_queue):
queue_pub = QueuePublisher(sm_config['rabbitmq'], ACTION_QDESC)
msg = {'test': 'message'}
queue_pub.publish(msg)
def callback_side_effect(*args):
print('WITHIN CALLBACK: ', args)
callback = MagicMock()
callback.side_effect = callback_side_effect
on_success = MagicMock()
on_failure = MagicMock()
sm_daemon = SMDaemon(ACTION_QDESC, SMDaemonDatasetManagerMock)
sm_daemon._callback = callback
sm_daemon._on_success = on_success
sm_daemon._on_failure = on_failure
sm_daemon._action_queue_consumer = QueueConsumer(sm_config['rabbitmq'], ACTION_QDESC,
callback, on_success, on_failure,
logger_name='daemon', poll_interval=0.1)
run_sm_daemon(sm_daemon)
callback.assert_called_once_with(msg)
on_success.assert_called_once_with(msg)
on_failure.assert_not_called()
示例4: DelayRequestBehaviourTests
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
class DelayRequestBehaviourTests(TestCase):
def setUp(self):
sleep_patcher = patch('uncertainty.behaviours.sleep')
self.sleep_mock = sleep_patcher.start()
self.addCleanup(self.sleep_mock.stop)
self.get_response_mock = MagicMock()
self.request_mock = MagicMock()
self.some_behaviour = MagicMock()
self.some_seconds = MagicMock()
self.delay_request_behaviour = DelayRequestBehaviour(self.some_behaviour,
self.some_seconds)
def test_calls_encapsulated_behaviour(self):
"""Tests that DelayResponseBehaviour calls the encapsulated behaviour"""
self.delay_request_behaviour(self.get_response_mock, self.request_mock)
self.some_behaviour.assert_called_once_with(self.get_response_mock, self.request_mock)
def test_returns_result_of_encapsulated_behaviour(self):
"""Tests that DelayResponseBehaviour returns the result of calling the encapsulated
behaviour"""
self.assertEqual(self.some_behaviour.return_value,
self.delay_request_behaviour(self.get_response_mock,
self.request_mock))
def test_calls_sleep(self):
"""Tests that DelayResponseBehaviour calls sleep for the given seconds"""
self.delay_request_behaviour(self.get_response_mock, self.request_mock)
self.sleep_mock.assert_called_once_with(self.some_seconds)
def test_delay_is_delay_request_response_behaviour(self):
"""Tests that delay is an alias for DelayResponseBehaviour"""
self.assertEqual(delay_request, DelayRequestBehaviour)
示例5: test_default_does_not_call_traffic
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_default_does_not_call_traffic(mock_get_token, mock_fake_lizzy,
mock_lizzy_get, mock_lizzy_post: MagicMock):
runner = CliRunner()
result = runner.invoke(main, ['create', config_path,
'42', '1.0', '--region', 'aa-bbbb-1'],
env=FAKE_ENV, catch_exceptions=False)
assert 'Fetching authentication token.. . OK' in result.output
assert 'Requesting new stack.. OK' in result.output
assert 'Stack ID: stack1-d42' in result.output
assert 'Waiting for new stack... . . OK' in result.output
assert 'Deployment Successful' in result.output
assert 'kio version approve' not in result.output
mock_lizzy_post.assert_called_once_with('https://localhost/stacks',
data=None,
headers={
'Content-type': 'application/json',
'Authorization': 'Bearer TOKEN'
},
json={
'keep_stacks': None,
'disable_rollback': False,
'region': 'aa-bbbb-1',
'parameters': ['1.0', ],
'dry_run': False,
'senza_yaml': 'SenzaInfo: [Something]\n',
'new_traffic': None,
'stack_version': '42',
'tags': ()
},
verify=False)
FakeLizzy.traffic.assert_not_called()
mock_fake_lizzy._delete_mock.assert_not_called()
mock_lizzy_post.reset_mock()
FakeLizzy.reset()
示例6: test_execute_func
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_execute_func(bot_cls, manager: ModuleManager):
manager.load_all()
mock = MagicMock(spec=dummy, name='dummy')
mock.__wrapped__ = dummy.__wrapped__
bot = bot_cls.return_value = Mock(spec=RequestBot, name='bot')
yield from manager.execute_func(
func=mock,
plugin=manager.plugins['dummy'],
private=False,
channel='#czarnobyl',
user=User('[email protected]'),
args=['lol'],
kwargs={'b': '42'},
)
bot_cls.assert_called_once_with(
protocol=manager.protocol,
private=False,
chan='#czarnobyl',
config={'__nick__': 'bot'},
plugin=manager.plugins['dummy'],
user=User('[email protected]'),
temp={},
)
mock.assert_called_once_with(bot, a='lol', b=42)
示例7: test_prop_callback_nested_arrays
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_prop_callback_nested_arrays(self):
# Initialize updatemenus and buttons
self.figure.layout.updatemenus = [{}, {}, {}]
self.figure.layout.updatemenus[2].buttons = [{}, {}]
self.figure.layout.updatemenus[2].buttons[1].label = 'button 1'
self.figure.layout.updatemenus[2].buttons[1].method = 'relayout'
# Register method callback
fn_button = MagicMock()
fn_layout = MagicMock()
self.figure.layout.updatemenus[2].buttons[1].on_change(
fn_button, 'method')
self.figure.layout.on_change(
fn_layout, 'updatemenus[2].buttons[1].method')
# Update button method
self.figure.layout.updatemenus[2].buttons[1].method = 'restyle'
# Check that both callbacks are called once
fn_button.assert_called_once_with(
self.figure.layout.updatemenus[2].buttons[1], 'restyle')
fn_layout.assert_called_once_with(self.figure.layout, 'restyle')
示例8: test_default_show_help
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_default_show_help(self, show_help: MagicMock):
""" should show help if help command called """
cmd = shell.CauldronShell()
cmd.default('help')
show_help.assert_called_once_with()
示例9: test_requesthandleradapter_handle_request
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
async def test_requesthandleradapter_handle_request(handleradapter,
aiohttpmsg):
handleradapter.access_log = True
handleradapter.log_access = MagicMock()
handleradapter._write_response_to_client = AsyncMock()
beacon = MagicMock()
req_res = []
async def toto(req, res):
assert req.url_path == "/toto"
assert req.method == "GET"
req_res.extend((req, res))
beacon()
return res
handleradapter._router.add_route('/toto', 'toto_url', toto)
message = aiohttpmsg('GET', '/toto')
await handleradapter.handle_request(message, MagicMock())
handleradapter._write_response_to_client.assert_called_once_with(*req_res)
beacon.assert_called_once_with()
assert handleradapter._meth == "none"
assert handleradapter._path == "none"
assert handleradapter.log_access.call_count == 1
示例10: test_traffic
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_traffic(monkeypatch):
mock_patch = MagicMock()
mock_patch.return_value = FakeResponse(200, '["stack1","stack2"]')
monkeypatch.setattr('requests.patch', mock_patch)
lizzy = Lizzy('https://lizzy.example', '7E5770K3N')
lizzy.traffic('574CC', 42)
header = make_header('7E5770K3N')
mock_patch.assert_called_once_with('https://lizzy.example/api/stacks/574CC',
headers=header,
data=None,
json={"new_traffic": 42},
verify=False)
# call with region payload
mock_patch.reset_mock()
lizzy = Lizzy('https://lizzy.example', '7E5770K3N')
lizzy.traffic('574CC', 42, region='ab-foo-7')
header = make_header('7E5770K3N')
mock_patch.assert_called_once_with('https://lizzy.example/api/stacks/574CC',
headers=header,
data=None,
json={'new_traffic': 42,
'region': 'ab-foo-7'},
verify=False)
示例11: test_explicit_mock
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_explicit_mock(self):
mock = MagicMock()
mock_open(mock)
with patch('%s.open' % __name__, mock, create=True) as patched:
self.assertIs(patched, mock)
open('foo')
mock.assert_called_once_with('foo')
示例12: test_proxy
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_proxy(mock_boto_client: MagicMock):
proxy = BotoClientProxy('test')
mock_boto_client.assert_called_once_with('test')
proxy.random_test(42)
mock_boto_client.random_test.assert_called_once_with(42)
assert proxy.random_test is not mock_boto_client.random_test
assert proxy.p is mock_boto_client.p
示例13: test_default_no
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_default_no(self):
get_input = MagicMock(return_value="")
self.assertEqual(
ui.ask_interactively("OHAI?", False, get_input=get_input),
False,
)
get_input.assert_called_once_with()
示例14: test_yes
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_yes(self):
get_input = MagicMock(return_value="y")
self.assertEqual(
ui.ask_interactively("OHAI?", True, get_input=get_input),
True,
)
get_input.assert_called_once_with()
示例15: test_jinja2_renderer_render_to_response_dict
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import assert_called_once_with [as 别名]
def test_jinja2_renderer_render_to_response_dict(app):
req = MagicMock()
req.app.components.get.return_value = \
components.Jinja2Renderer(app)
resp = HttpResponseController(req)
render = MagicMock()
render.return_value = 'Hey, I’m a body!'
resp.template_engine.render_to_string = render
resp.context['template_name'] = 'test_resp.html'
rendered = resp.template_engine.render_to_response_dict(resp)
assert isinstance(rendered, dict)
assert len(rendered) == 6
assert rendered == {'status': 200, 'reason': 'OK',
'content_type': 'text/html',
'charset': 'utf-8',
'headers': {},
'body': 'Hey, I’m a body!'.encode()}
render.assert_called_once_with('test_resp.html', None)
del resp.context['template_name']
with pytest.raises(HttpResponseControllerError):
resp.template_engine.render_to_response_dict(resp)