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


Python mock.MagicMock类代码示例

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


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


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