当前位置: 首页>>代码示例>>Python>>正文


Python MagicMock.side_effect方法代码示例

本文整理汇总了Python中unittest.mock.MagicMock.side_effect方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.side_effect方法的具体用法?Python MagicMock.side_effect怎么用?Python MagicMock.side_effect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在unittest.mock.MagicMock的用法示例。


在下文中一共展示了MagicMock.side_effect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_resolve_to_ip_addresses

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
def test_resolve_to_ip_addresses(monkeypatch):
    query = MagicMock()
    monkeypatch.setattr('dns.resolver.query', query)

    query.side_effect = Exception()
    assert resolve_to_ip_addresses('example.org') == set()

    query.side_effect = None
    query.return_value = [MagicMock(address='1.2.3.4')]
    assert resolve_to_ip_addresses('example.org') == {'1.2.3.4'}
开发者ID:lmineiro,项目名称:senza,代码行数:12,代码来源:test_traffic.py

示例2: test_max_queue

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_max_queue(self):
        """Test the maximum queue length."""
        # make a wrapped method
        mock_method = MagicMock()
        retryer = influxdb.RetryOnError(
            self.hass, retry_limit=4, queue_limit=3)
        wrapped = retryer(mock_method)
        mock_method.side_effect = Exception()

        # call it once, call fails, queue fills to 1
        wrapped(1, 2, test=3)
        self.assertEqual(mock_method.call_count, 1)
        mock_method.assert_called_with(1, 2, test=3)
        self.assertEqual(len(wrapped._retry_queue), 1)

        # two more calls that failed. queue is 3
        wrapped(1, 2, test=3)
        wrapped(1, 2, test=3)
        self.assertEqual(mock_method.call_count, 3)
        self.assertEqual(len(wrapped._retry_queue), 3)

        # another call, queue gets limited to 3
        wrapped(1, 2, test=3)
        self.assertEqual(mock_method.call_count, 4)
        self.assertEqual(len(wrapped._retry_queue), 3)

        # time passes
        start = dt_util.utcnow()
        shifted_time = start + (timedelta(seconds=20 + 1))
        self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
                           {ha.ATTR_NOW: shifted_time})
        self.hass.block_till_done()

        # only the three queued calls where repeated
        self.assertEqual(mock_method.call_count, 7)
        self.assertEqual(len(wrapped._retry_queue), 3)

        # another call, queue stays limited
        wrapped(1, 2, test=3)
        self.assertEqual(mock_method.call_count, 8)
        self.assertEqual(len(wrapped._retry_queue), 3)

        # disable the side effect
        mock_method.side_effect = None

        # time passes, all calls should succeed
        start = dt_util.utcnow()
        shifted_time = start + (timedelta(seconds=20 + 1))
        self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
                           {ha.ATTR_NOW: shifted_time})
        self.hass.block_till_done()

        # three queued calls succeeded, queue empty.
        self.assertEqual(mock_method.call_count, 11)
        self.assertEqual(len(wrapped._retry_queue), 0)
开发者ID:JiShangShiDai,项目名称:home-assistant,代码行数:57,代码来源:test_influxdb.py

示例3: test_docker_image_exists

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
def test_docker_image_exists(monkeypatch):
    get = MagicMock()
    monkeypatch.setattr('requests.get', get)

    get.return_value = MagicMock(name='response')
    get.return_value.json = lambda: {'tags': ['1.0']}
    assert docker_image_exists('my-registry/foo/bar:1.0') is True

    get.side_effect = requests.HTTPError()
    assert docker_image_exists('foo/bar:1.0') is False

    get.side_effect = requests.HTTPError()
    assert docker_image_exists('my-registry/foo/bar:1.0') is False
开发者ID:lmineiro,项目名称:senza,代码行数:15,代码来源:test_docker.py

示例4: test_run

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_run(self, mc_time, init_worker):
        self.worker.init_fedmsg = MagicMock()
        self.worker.spawn_instance_with_check = MagicMock()
        self.worker.spawn_instance_with_check.return_value = self.vm_ip

        self.worker.obtain_job = MagicMock()
        self.worker.obtain_job.return_value = self.job

        def validate_not_spawn():
            assert not self.worker.spawn_instance_with_check.called
            return mock.DEFAULT

        self.worker.obtain_job.side_effect = validate_not_spawn
        self.worker.terminate_instance = MagicMock()

        mc_do_job = MagicMock()
        self.worker.do_job = mc_do_job

        def stop_loop(*args, **kwargs):
            self.worker.kill_received = True

        mc_do_job.side_effect = stop_loop

        self.worker.run()
        assert mc_do_job.called
        assert self.worker.init_fedmsg.called
        assert self.worker.obtain_job.called
        assert self.worker.terminate_instance.called
开发者ID:1dot75cm,项目名称:Copr,代码行数:30,代码来源:test_dispatcher.py

示例5: test_other_error

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_other_error(self, requests_get: MagicMock):
        """ should fail if the get request raises an unknown exception """

        requests_get.side_effect = ValueError('Fake')

        r = support.run_command('connect http://some.url')
        self.assert_has_error_code(r, 'CONNECT_COMMAND_ERROR')
开发者ID:sernst,项目名称:cauldron,代码行数:9,代码来源:test_connect_command.py

示例6: test_connection_error

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_connection_error(self, requests_get: MagicMock):
        """ should fail if the url cannot be connected to """

        requests_get.side_effect = request_exceptions.ConnectionError('Fake')

        r = support.run_command('connect "a url"')
        self.assert_has_error_code(r, 'CONNECTION_ERROR')
开发者ID:sernst,项目名称:cauldron,代码行数:9,代码来源:test_connect_command.py

示例7: test_single_retry

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_single_retry(self):
        """Test that retry stops after a single try if configured."""
        mock_method = MagicMock()
        retryer = influxdb.RetryOnError(self.hass, retry_limit=1)
        wrapped = retryer(mock_method)
        wrapped(1, 2, test=3)
        self.assertEqual(mock_method.call_count, 1)
        mock_method.assert_called_with(1, 2, test=3)

        start = dt_util.utcnow()
        shifted_time = start + (timedelta(seconds=20 + 1))
        self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
                           {ha.ATTR_NOW: shifted_time})
        self.hass.block_till_done()
        self.assertEqual(mock_method.call_count, 1)

        mock_method.side_effect = Exception()
        wrapped(1, 2, test=3)
        self.assertEqual(mock_method.call_count, 2)
        mock_method.assert_called_with(1, 2, test=3)

        for cnt in range(3):
            start = dt_util.utcnow()
            shifted_time = start + (timedelta(seconds=20 + 1))
            self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
                               {ha.ATTR_NOW: shifted_time})
            self.hass.block_till_done()
            self.assertEqual(mock_method.call_count, 3)
            mock_method.assert_called_with(1, 2, test=3)
开发者ID:JiShangShiDai,项目名称:home-assistant,代码行数:31,代码来源:test_influxdb.py

示例8: test_prepare

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_prepare(self, mock_renderer: MagicMock):
        """
            Test preparing the email body.

            Expected result: The previously set body is rendered with the given arguments.
        """

        def _renderer_side_effect(template, **_kwargs):
            """
                Return the template path for testing.
            """
            return template

        mock_renderer.side_effect = _renderer_side_effect

        subject = 'Test Subject'
        body_path = 'email/test'
        sender = '[email protected]'
        email = Email(subject, body_path, sender)

        title = 'Test Title'
        body_path_plain = body_path + '.txt'
        body_path_html = body_path + '.html'
        email.prepare(title=title)

        self.assertEqual(body_path_plain, email._body_plain)
        self.assertEqual(body_path_html, email._body_html)
        self.assertEqual(2, mock_renderer.call_count)
        self.assertTupleEqual(call(body_path_plain, title=title), mock_renderer.call_args_list[0])
        self.assertTupleEqual(call(body_path_html, title=title), mock_renderer.call_args_list[1])
开发者ID:BMeu,项目名称:Aerarium,代码行数:32,代码来源:email_test.py

示例9: test_sm_daemon_receive_message

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [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()
开发者ID:SpatialMetabolomics,项目名称:SM_distributed,代码行数:27,代码来源:test_sm_daemon.py

示例10: test_execute_failure

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_execute_failure(self, execute: MagicMock):
        """ should fail when execution fails """

        execute.side_effect = RuntimeError('FAKE ERROR')
        opened = self.get('/command-sync?&command=open&args=+')
        self.assertEqual(opened.flask.status_code, 200)
        self.assert_has_error_code(opened.response, 'KERNEL_EXECUTION_FAILURE')
开发者ID:sernst,项目名称:cauldron,代码行数:9,代码来源:test_server_execution.py

示例11: test_run_spawn_in_advance_with_existing_vm

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_run_spawn_in_advance_with_existing_vm(self, mc_time, init_worker):
        self.worker.opts.spawn_in_advance = True
        self.worker.init_fedmsg = MagicMock()
        self.worker.spawn_instance_with_check = MagicMock()
        self.worker.spawn_instance_with_check.side_effect = self.set_ip

        self.worker.check_vm_still_alive = MagicMock()

        self.worker.obtain_job = MagicMock()
        self.worker.obtain_job.side_effect = [
            None,
            self.job,
        ]

        def validate_spawn():
            assert self.worker.spawn_instance_with_check.called
            self.worker.spawn_instance_with_check.reset_mock()
            return mock.DEFAULT

        self.worker.obtain_job.side_effect = validate_spawn
        self.worker.terminate_instance = MagicMock()

        mc_do_job = MagicMock()
        self.worker.do_job = mc_do_job

        def stop_loop(*args, **kwargs):
            assert not self.worker.spawn_instance_with_check.called
            self.worker.kill_received = True

        mc_do_job.side_effect = stop_loop

        self.worker.run()
        assert self.worker.check_vm_still_alive.called
        assert self.worker.spawn_instance_with_check.called_once
开发者ID:1dot75cm,项目名称:Copr,代码行数:36,代码来源:test_dispatcher.py

示例12: test_invalid_url_error

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_invalid_url_error(self, requests_get: MagicMock):
        """ should fail if the url is not valid """

        requests_get.side_effect = request_exceptions.InvalidURL('Fake')

        r = support.run_command('connect "a url"')
        self.assert_has_error_code(r, 'INVALID_URL')
开发者ID:sernst,项目名称:cauldron,代码行数:9,代码来源:test_connect_command.py

示例13: test_run

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
    def test_run(self, sys_exit: MagicMock):
        """Should run the specified command"""
        sys_exit.side_effect = SystemExit('FAKE')

        with self.assertRaises(SystemExit):
            invoke.run(['--version'])

        self.assertLessEqual(1, sys_exit.call_count)
开发者ID:sernst,项目名称:cauldron,代码行数:10,代码来源:test_invoke.py

示例14: test_add_torrent_lt_runtime_error

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
async def test_add_torrent_lt_runtime_error(cli, core):
    post_data = create_torrent_post_data(filename='random_one_file.torrent')

    add_torrent = MagicMock()
    add_torrent.side_effect = RuntimeError()
    core.session.add_torrent = add_torrent
    response = await cli.post('/torrent', json=post_data)
    assert response.status == 500
开发者ID:spritzle,项目名称:spritzle,代码行数:10,代码来源:test_torrent.py

示例15: test_do_reload_error

# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import side_effect [as 别名]
 def test_do_reload_error(self, reload: MagicMock, os_path: MagicMock):
     """Should fail to import the specified module and so return False."""
     target = MagicMock()
     target.__file__ = None
     target.__path__ = ['fake']
     os_path.getmtime.return_value = 10
     reload.side_effect = ImportError('FAKE')
     self.assertFalse(reloading.do_reload(target, 0))
     self.assertEqual(1, reload.call_count)
开发者ID:sernst,项目名称:cauldron,代码行数:11,代码来源:test_session_reloading.py


注:本文中的unittest.mock.MagicMock.side_effect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。