• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mock.MagicMock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_render_definition

def test_render_definition(monkeypatch, popen):
    senza = Senza('region')
    senza.logger = MagicMock()

    mock_named_tempfile = MagicMock()
    mock_tempfile = MagicMock()
    mock_tempfile.name = 'lizzy.yaml'
    mock_named_tempfile.__enter__.return_value = mock_tempfile
    mock_named_tempfile.return_value = mock_named_tempfile
    monkeypatch.setattr('tempfile.NamedTemporaryFile', mock_named_tempfile)

    senza.render_definition('yaml content', 'version42', 'imgversion22',
                            ['Param1=app', 'SecondParam=3'])

    cmd = 'senza print --region region -o json --force lizzy.yaml version42 ' \
          'imgversion22 Param1=app SecondParam=3'

    popen.assert_called_with(cmd.split(" "), stdout=-1, stderr=-1)
    assert not senza.logger.error.called

    senza.render_definition('yaml content', None, 'imgversion22',
                            ['Param1=app', 'SecondParam=3'])
    assert not senza.logger.error.called

    # test error case
    popen.side_effect = ExecutionError('', '')

    with pytest.raises(SenzaRenderError):
        senza.render_definition('yaml content', 'version42', 'imgversion22',
                                ['Param1=app', 'SecondParam=3'])
开发者ID:mfelsche,项目名称:lizzy,代码行数:30,代码来源:test_senza_wrapper.py


示例2: test_respawn_auto_scaling_group_without_elb

def test_respawn_auto_scaling_group_without_elb(monkeypatch):

    inst = {'InstanceId': 'myinst-1', 'LaunchConfigurationName': 'lc-1', 'LifecycleState': 'InService'}
    instances = [inst]
    group = {'AutoScalingGroupName': 'myasg',
             'LaunchConfigurationName': 'lc-2', 'Instances': instances, 'MinSize': 1, 'MaxSize': 1, 'DesiredCapacity': 1,
             'LoadBalancerNames': []}
    groups = {'AutoScalingGroups': [group]}
    asg = MagicMock()
    asg.describe_auto_scaling_groups.return_value = groups

    def update_group(**kwargs):
        instances.append({'InstanceId': 'myinst-2', 'LaunchConfigurationName': 'lc-2', 'LifecycleState': 'InService'})

    def terminate_instance(InstanceId, **kwargs):
        for i in range(len(instances)):
            if instances[i]['InstanceId'] == InstanceId:
                del instances[i]
                break

    asg.update_auto_scaling_group = update_group
    asg.terminate_instance_in_auto_scaling_group = terminate_instance
    services = {'autoscaling': asg}
    def client(service, *args):
        return services[service]
    monkeypatch.setattr('boto3.client', client)
    monkeypatch.setattr('time.sleep', lambda s: s)
    respawn_auto_scaling_group('myasg', 'myregion')
开发者ID:lmineiro,项目名称:senza,代码行数:28,代码来源:test_respawn.py


示例3: test_onRequestAnnounce

def test_onRequestAnnounce(gsssc, monkeypatch, definition):
    random_guid = known_guid
    status1 = MagicMock()
    gsssc.onRequestIdentify = MagicMock()
    status1.return_value = 'unstable'
    gsssc._db.all = MagicMock()
    simulations = [{'exit_code': 'tsttmp133',
                    'status': 'tsttmp134',
                    'percentage': 0.3,
                    'guid': random_guid,
                    'directory': 'home',
                    'timestamp': 'zerohour',
                    'validation': 'invalid'
                    }]
    gsssc._db.all.return_value = simulations
    monkeypatch.setattr('gssa.error.makeError', status1)
    gsssc.publish = MagicMock()
    gsssc.server_id = 123
    gsssc.onRequestAnnounce()
    yield from wait()
    gsssc.publish.assert_called_with(u'com.gosmartsimulation.announce',
                                     123, random_guid, (0.3, 'unstable'), 'home',
                                     'zerohour', 'invalid')
    result000 = 1983
    assert (result000 == 1983)
开发者ID:philtweir,项目名称:glossia,代码行数:25,代码来源:test_server.py


示例4: test_print_replace_mustache

def test_print_replace_mustache(monkeypatch):
    sg = MagicMock()
    sg.name = 'app-master-mind'
    sg.id = 'sg-007'

    monkeypatch.setattr('boto.cloudformation.connect_to_region', lambda x: MagicMock())
    monkeypatch.setattr('boto.ec2.connect_to_region', lambda x: MagicMock(get_all_security_groups=lambda: [sg]))
    monkeypatch.setattr('boto.iam.connect_to_region', lambda x: MagicMock())
    data = {'SenzaInfo': {'StackName': 'test',
                          'Parameters': [{'ApplicationId': {'Description': 'Application ID from kio'}}]},
            'SenzaComponents': [{'Configuration': {'ServerSubnets': {'eu-west-1': ['subnet-123']},
                                                   'Type': 'Senza::Configuration'}},
                                {'AppServer': {'Image': 'AppImage',
                                               'InstanceType': 't2.micro',
                                               'SecurityGroups': ['app-{{Arguments.ApplicationId}}'],
                                               'IamRoles': ['app-{{Arguments.ApplicationId}}'],
                                               'TaupageConfig': {'runtime': 'Docker',
                                                                 'source': 'foo/bar'},
                                               'Type': 'Senza::TaupageAutoScalingGroup'}}]
            }

    runner = CliRunner()

    with runner.isolated_filesystem():
        with open('myapp.yaml', 'w') as fd:
            yaml.dump(data, fd)

        result = runner.invoke(cli, ['print', 'myapp.yaml', '--region=myregion', '123', 'master-mind'],
                               catch_exceptions=False)
    assert 'AWSTemplateFormatVersion' in result.output
    assert 'subnet-123' in result.output
    assert 'app-master-mind' in result.output
    assert 'sg-007' in result.output
开发者ID:a1exsh,项目名称:senza,代码行数:33,代码来源:test_cli.py


示例5: test_component_auto_scaling_group_configurable_properties2

def test_component_auto_scaling_group_configurable_properties2():
    definition = {"Resources": {}}
    configuration = {
        'Name': 'Foo',
        'InstanceType': 't2.micro',
        'Image': 'foo',
        'SpotPrice': 0.250
    }

    args = MagicMock()
    args.region = "foo"

    info = {
        'StackName': 'FooStack',
        'StackVersion': 'FooVersion'
    }

    result = component_auto_scaling_group(definition, configuration, args, info, False, MagicMock())

    assert result["Resources"]["FooConfig"]["Properties"]["SpotPrice"] == 0.250

    del configuration["SpotPrice"]

    result = component_auto_scaling_group(definition, configuration, args, info, False, MagicMock())

    assert "SpotPrice" not in result["Resources"]["FooConfig"]["Properties"]
开发者ID:alterrebe,项目名称:senza,代码行数:26,代码来源:test_components.py


示例6: test_downloadNextFile_subdirectory

def test_downloadNextFile_subdirectory(download_project, servers, project):

    one = servers.getRemoteServer("http", "127.0.0.1", 8000, None)

    download_project._files_to_download = [
        {"path": "a/b/c", "md5sum": "d8e8fca2dc0f896fd7cb4cb0031ba249", "server": one}
    ]
    download_project._total_files_to_download = 4
    download_project._is_running = True

    mark_finished = MagicMock()
    download_project.finished.connect(mark_finished)

    progress = MagicMock()
    download_project.updated.connect(progress)

    download_project._downloadNextFile()
    assert not mark_finished.called
    progress.assert_called_once_with(75)

    assert os.path.exists(os.path.join(project.filesDir(), "a", "b", "c"))
    assert project.get.called
    args, kwargs = project.get.call_args
    assert args[0] == one
    assert args[1] == "/files/a/b/c"
    assert args[2] == download_project._downloadFileReceived
    assert kwargs["context"] is not None
    assert kwargs["downloadProgressCallback"] == download_project._downloadFileProgress
开发者ID:AJNOURI,项目名称:gns3-gui,代码行数:28,代码来源:test_download_project.py


示例7: record

 def record(dns_identifier, weight):
     rec = MagicMock(name=dns_identifier + '-record',
                     weight=weight,
                     identifier=dns_identifier,
                     type='CNAME')
     rec.name = 'myapp.example.org.'
     return rec
开发者ID:a1exsh,项目名称:senza,代码行数:7,代码来源:test_cli.py


示例8: test_get_overlays_inactive

 def test_get_overlays_inactive(self, mock_projector_overlays):
     mock_overlay = MagicMock()
     mock_overlay.name = 'mock_overlay_2'
     mock_overlay.is_active.return_value = False
     mock_projector_overlays.send.return_value = ((None, mock_overlay), )
     value = projector_api.get_overlays(only_active=True)
     self.assertNotEqual(value, {'mock_overlay_2': mock_overlay})
开发者ID:DebVortex,项目名称:OpenSlides,代码行数:7,代码来源:test_api.py


示例9: test_sendPkt

def test_sendPkt():
    """ Checks if the modified sleep function works right. 
    """

    # mocking socket
    mocked_socket = MagicMock()
    mocked_socket.sendto = MagicMock(return_value=0)

    # mocking sleep
    picture_cast_todo.sleep = MagicMock(return_value=0)

    # run function
    picture_cast_todo.sendPkt(mocked_socket, 0, 0, 10)

    # check if mocked functions were called

    try:
        picture_cast_todo.sleep.assert_called_once_with(10 / 1000)
    except:
        
        print("The delay in sendPkt is not correct!")
        print(sys.exc_info())
      
        return -1

    return 0
开发者ID:Strice91,项目名称:IK-HA,代码行数:26,代码来源:picture_test.py


示例10: test_single_unhandled

 def test_single_unhandled(self):
     callback = MagicMock(return_value=False)
     self.stack.register(callback)
     self.assertRaises(RuntimeError, self.stack, 666)
     callback.assert_called_once_with(666)
     self.stack.unregister(callback)
     self.assertRaises(RuntimeError, self.stack)
开发者ID:osandov,项目名称:molino,代码行数:7,代码来源:test_callbackstack.py


示例11: test_update_projector_overlay

    def test_update_projector_overlay(self, mock_ProjectorSocketHandler,
                                      mock_get_overlays):
        mock_overlay = MagicMock()
        mock_overlay.name = 'mock_overlay_name'
        mock_overlay.get_projector_html.return_value = 'mock_html_code'
        mock_overlay.get_javascript.return_value = 'mock_javascript'
        mock_get_overlays.return_value = {'mock_overlay': mock_overlay}

        # Test with active overlay
        mock_overlay.is_active.return_value = False
        projector_api.update_projector_overlay(None)
        mock_ProjectorSocketHandler.send_updates.assert_called_with(
            {'overlays': {'mock_overlay_name': None}})

        # Test with active overlay
        mock_overlay.is_active.return_value = True
        projector_api.update_projector_overlay(None)
        expected_data = {'overlays': {'mock_overlay_name': {
            'html': 'mock_html_code',
            'javascript': 'mock_javascript'}}}
        mock_ProjectorSocketHandler.send_updates.assert_called_with(expected_data)

        # Test with overlay name as argument
        projector_api.update_projector_overlay('mock_overlay')
        mock_ProjectorSocketHandler.send_updates.assert_called_with(expected_data)

        # Test with overlay object as argument
        projector_api.update_projector_overlay(mock_overlay)
        mock_ProjectorSocketHandler.send_updates.assert_called_with(expected_data)
开发者ID:DebVortex,项目名称:OpenSlides,代码行数:29,代码来源:test_api.py


示例12: test__m2m_changed_receiver

    def test__m2m_changed_receiver(self, Activity, ContentType):
        ct = MagicMock()
        instance = MagicMock()
        instance.pk = 1
        activity = MagicMock()

        ContentType.objects.get_for_model.return_value = ct
        Activity.return_value = activity
        mediator = ActivityMediator()
        mediator.alter = MagicMock(return_value=activity)
        mediator.prepare_snapshot = MagicMock(return_value=None)
        mediator.render = MagicMock()   # it will be called by notifiers
        mediator._m2m_changed_receiver(None, instance, action='pre_add',
                                       reverse=False)

        # user defined alternation code is called
        mediator.alter.assert_called_with(instance, None,
                                          action='pre_add',
                                          reverse=False)
        # user defined snapshot preparation code is called
        mediator.prepare_snapshot.assert_called_with(instance, activity,
                                                     action='pre_add',
                                                     reverse=False)
        # activity save method is called
        activity.save.assert_called_with()
开发者ID:Clpsplug,项目名称:Kawaz3rd,代码行数:25,代码来源:test_mediator.py


示例13: test__post_save_receiver

    def test__post_save_receiver(self, Activity, ContentType):
        ct = MagicMock()
        instance = MagicMock()
        instance.pk = 1
        activity = MagicMock()

        ContentType.objects.get_for_model.return_value = ct
        Activity.return_value = activity

        mediator = ActivityMediator()
        mediator.alter = MagicMock(return_value=activity)
        mediator.prepare_snapshot = MagicMock(return_value=None)
        mediator.render = MagicMock()   # it will be called by notifiers
        mediator._post_save_receiver(None, instance, created=True)

        Activity.assert_called_with(content_type=ct,
                                    object_id=instance.pk,
                                    status='created')
        # user defined alternation code is called
        mediator.alter.assert_called_with(instance, activity)
        # activity save method is called
        activity.save.assert_called_with()

        mediator._post_save_receiver(None, instance, created=False)

        Activity.assert_called_with(content_type=ct,
                                    object_id=instance.pk,
                                    status='updated')
        # user defined alternation code is called
        mediator.alter.assert_called_with(instance, activity)
        # user defined snapshot preparation code is called
        mediator.prepare_snapshot.assert_called_with(instance, activity)
        # activity save method is called
        activity.save.assert_called_with()
开发者ID:Clpsplug,项目名称:Kawaz3rd,代码行数:34,代码来源:test_mediator.py


示例14: FileIO

    def FileIO(self, name, mode):
        """Proxy for tensorflow.python.lib.io.file_io.FileIO class. Mocks the class
        if a real GCS bucket is not available for testing.
        """
        self._check_started()
        if not self.mock_gcs:
            return tf_file_io.FileIO(name, mode)

        filepath = name
        if filepath.startswith(self._gcs_prefix):
            mock_fio = MagicMock()
            mock_fio.__enter__ = Mock(return_value=mock_fio)
            if mode == 'rb':
                if filepath not in self.local_objects:
                    raise IOError('{} does not exist'.format(filepath))
                self.local_objects[filepath].seek(0)
                mock_fio.read = self.local_objects[filepath].read
            elif mode == 'wb':
                self.local_objects[filepath] = BytesIO()
                mock_fio.write = self.local_objects[filepath].write
            else:
                raise ValueError(
                    '{} only supports wrapping of FileIO for `mode` "rb" or "wb"')
            return mock_fio

        return open(filepath, mode)
开发者ID:ZhangXinNan,项目名称:keras,代码行数:26,代码来源:test_utils.py


示例15: test_multiple_events

    def test_multiple_events(self):
        request_headers_mock = MagicMock(return_value=self.mock_headers)
        http_method = self.respond_with(text="""[
            {
                "timestamp":"2015-08-24T01:16:22.327Z",
                "host":"10.0.1.232",
                "message":"[WARN] [04/21/2015 12:54:30.079] [doc-renderer-cluster-1-akka.remote.default-remote-dispatcher-22] Association with remote system has failed."
            },
            {
                "timestamp":"2015-08-24T01:16:25.327Z",
                "host":"10.0.1.232",
                "message":"[WARN] [04/21/2015 12:54:36.079] [doc-renderer-cluster-1-akka.remote.default-remote-dispatcher-26] Association with remote system has failed."
            }
        ]""")
        quote_method = MagicMock(return_value=self.bundle_id_urlencoded)
        stdout = MagicMock()

        input_args = MagicMock(**self.default_args)
        with patch('requests.get', http_method), \
                patch('conductr_cli.conduct_url.request_headers', request_headers_mock), \
                patch('urllib.parse.quote', quote_method):
            logging_setup.configure_logging(input_args, stdout)
            result = conduct_logs.logs(input_args)
            self.assertTrue(result)

        request_headers_mock.assert_called_with(input_args)
        http_method.assert_called_with(self.default_url, timeout=DEFAULT_HTTP_TIMEOUT, headers=self.mock_headers)
        self.assertEqual(
            strip_margin("""|TIME                  HOST        LOG
                            |2015-08-24T01:16:22Z  10.0.1.232  [WARN] [04/21/2015 12:54:30.079] [doc-renderer-cluster-1-akka.remote.default-remote-dispatcher-22] Association with remote system has failed.
                            |2015-08-24T01:16:25Z  10.0.1.232  [WARN] [04/21/2015 12:54:36.079] [doc-renderer-cluster-1-akka.remote.default-remote-dispatcher-26] Association with remote system has failed.
                            |"""),
            self.output(stdout))
开发者ID:pengyangtuo,项目名称:conductr-cli,代码行数:33,代码来源:test_conduct_logs.py


示例16: test_correctly_invokes_parameter_validation

    def test_correctly_invokes_parameter_validation(self, fake_check_unknown):
        fake_request = MagicMock()
        fake_request.args = MultiDict()
        lookup = {'_id': 'my_item'}

        instance = self._make_one()
        instance.find_one(fake_request, **lookup)

        self.assertTrue(fake_check_unknown.called)
        args, kwargs = fake_check_unknown.call_args

        self.assertGreater(len(args), 0)
        self.assertEqual(args[0], fake_request)
        self.assertEqual(kwargs.get('allow_filtering'), False)

        expected_whitelist = sorted(['exclude_fields', 'include_fields'])

        whitelist_arg = kwargs.get('whitelist')
        if whitelist_arg is not None:
            # NOTE: the whitelist argument is converted to a list, because any
            # iterable type is valid, not just lists
            self.assertEqual(sorted(list(whitelist_arg)), expected_whitelist)
        else:
            # whitelist can also be passed as a positional argument
            self.assertGreater(len(args), 1)
            self.assertEqual(sorted(list(args[1])), expected_whitelist)
开发者ID:dhazell,项目名称:superdesk,代码行数:26,代码来源:items_service_test.py


示例17: TestEventListener

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)
开发者ID:miyakogi,项目名称:wdom,代码行数:28,代码来源:test_event.py


示例18: test_console

def test_console(monkeypatch):
    stack = MagicMock(stack_name='test-1')
    inst = MagicMock()
    inst.tags = {'aws:cloudformation:stack-name': 'test-1'}
    ec2 = MagicMock()
    ec2.get_only_instances.return_value = [inst]
    ec2.get_console_output.return_value.output = b'**MAGIC-CONSOLE-OUTPUT**'
    monkeypatch.setattr('boto.ec2.connect_to_region', lambda x: ec2)
    monkeypatch.setattr('boto.cloudformation.connect_to_region',
                        lambda x: MagicMock(list_stacks=lambda stack_status_filters: [stack]))
    monkeypatch.setattr('boto.iam.connect_to_region', lambda x: MagicMock())

    runner = CliRunner()

    data = {'SenzaInfo': {'StackName': 'test'}}

    with runner.isolated_filesystem():
        with open('myapp.yaml', 'w') as fd:
            yaml.dump(data, fd)
        result = runner.invoke(cli, ['console', 'myapp.yaml', '--region=myregion', '1'],
                               catch_exceptions=False)

        assert '**MAGIC-CONSOLE-OUTPUT**' in result.output

        result = runner.invoke(cli, ['console', 'foobar', '--region=myregion'],
                               catch_exceptions=False)
        assert '' == result.output

        result = runner.invoke(cli, ['console', '172.31.1.2', '--region=myregion'],
                               catch_exceptions=False)
        assert '**MAGIC-CONSOLE-OUTPUT**' in result.output

        result = runner.invoke(cli, ['console', 'i-123', '--region=myregion'],
                               catch_exceptions=False)
        assert '**MAGIC-CONSOLE-OUTPUT**' in result.output
开发者ID:a1exsh,项目名称:senza,代码行数:35,代码来源:test_cli.py


示例19: test_process_data_redirects_to_failure_on_payment_failure

 def test_process_data_redirects_to_failure_on_payment_failure(self):
     self.payment.status = 'reject'
     provider = WireProvider()
     request = MagicMock()
     request.GET = {}
     response = provider.process_data(self.payment, request)
     self.assertEqual(response['location'], self.payment.get_failure_url())
开发者ID:imakin,项目名称:pysar-payments,代码行数:7,代码来源:test_wire.py


示例20: add_change

 def add_change(op, dns_name, rtype, ttl, identifier, weight):
     if op == 'CREATE':
         x = MagicMock(weight=weight, identifier=identifier)
         x.name = "myapp.example.org."
         x.type = "CNAME"
         records[identifier] = x
     return MagicMock(name='change')
开发者ID:a1exsh,项目名称:senza,代码行数:7,代码来源:test_cli.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mock.Mock类代码示例发布时间:2022-05-27
下一篇:
Python mock.something函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap