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

Python mock.Mock类代码示例

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

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



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

示例1: test_get_or_create_sheet_gets_existing_sheet

def test_get_or_create_sheet_gets_existing_sheet():
    ("XL backend should create a new sheet when a sheet of that name"
     " does not exist yet")

    # Given a mocked workbook and XL backend with one sheet
    workbook = Mock()
    sheet = Mock()
    sheet.name = 'awesomesheet'
    sheet.rows = {0: 'stuff', 1: 'more stuff'}

    class MyXL(XL):
        def get_sheets(self):
            return [sheet]

    xl_backend = MyXL(workbook=workbook)

    # When I call get_or_create_sheet of `awesome sheet1
    current_sheet, current_row = xl_backend.get_or_create_sheet('awesomesheet')

    # Then workbook.add_sheet should not have been called
    workbook.add_sheet.called.should.be.false

    # And the current sheet is equal to the mocked sheet
    current_sheet.should.equal(sheet)

    # And current_row should be 1
    current_row.should.equal(1)
开发者ID:Yipit,项目名称:excellent,代码行数:27,代码来源:test_xl_backend.py


示例2: get_backup_file

 def get_backup_file(self):
     file = Mock()
     file.platform = amo.PLATFORM_ALL.id
     file.latest_xpi_url.return_value = 'xpi.backup'
     file.get_url_path.return_value = 'xpi.backup.url'
     file.status = amo.STATUS_PUBLIC
     return file
开发者ID:srachit,项目名称:olympia,代码行数:7,代码来源:test_buttons.py


示例3: test_getattr_consults_schema_item_default_factory_with_context

    def test_getattr_consults_schema_item_default_factory_with_context(self):

        content = Item()
        content.id = u"id"
        content.portal_type = u"testtype"

        from zope.interface import provider
        from zope.schema.interfaces import IContextAwareDefaultFactory

        @provider(IContextAwareDefaultFactory)
        def defaultFactory(context):
            return u"{0:s}_{1:s}".format(context.id, context.portal_type)

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo",
                                       defaultFactory=defaultFactory)
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        self.assertEqual(u"id_testtype", content.foo)
        self.assertEqual(None, content.bar)
        self.assertEqual(u"id", content.id)
        self.assertRaises(AttributeError, getattr, content, 'baz')
开发者ID:plone,项目名称:plone.dexterity,代码行数:29,代码来源:test_content.py


示例4: test_get_agent_bindings

    def test_get_agent_bindings(self, mock_factory):
        bind_payload = {'a': 1, 'b': 2}
        distributor = {'distributor_type_id': '3838'}
        mock_distributor_manager = Mock()
        mock_distributor_manager.get_distributor = Mock(return_value=distributor)
        mock_distributor_manager.create_bind_payload = Mock(return_value=bind_payload)
        mock_factory.repo_distributor_manager = Mock(return_value=mock_distributor_manager)

        # test manager

        bindings = [
            {'consumer_id': '10', 'repo_id': '20', 'distributor_id': '30', 'binding_config': {}},
            {'consumer_id': '40', 'repo_id': '50', 'distributor_id': '60', 'binding_config': {}},
        ]
        agent_bindings = AgentManager._bindings(bindings)

        # validation

        for binding in bindings:
            mock_distributor_manager.get_distributor.assert_any_call(
                binding['repo_id'], binding['distributor_id'])
            mock_distributor_manager.create_bind_payload.assert_any_call(
                binding['repo_id'], binding['distributor_id'], binding['binding_config'])

        self.assertEqual(len(agent_bindings), 2)
        for binding, agent_binding in itertools.izip(bindings, agent_bindings):
            self.assertEqual(binding['repo_id'], agent_binding['repo_id'])
            self.assertEqual(distributor['distributor_type_id'], agent_binding['type_id'])
            self.assertEqual(bind_payload, agent_binding['details'])
开发者ID:signull,项目名称:pulp,代码行数:29,代码来源:test_agent_manager.py


示例5: test_annotate_decorator

    def test_annotate_decorator(self):
        from celery.app.task import Task

        class adX(Task):
            abstract = True

            def run(self, y, z, x):
                return y, z, x

        check = Mock()
        def deco(fun):
            def _inner(*args, **kwargs):
                check(*args, **kwargs)
                return fun(*args, **kwargs)
            return _inner

        app = Celery(set_as_current=False)
        app.conf.CELERY_ANNOTATIONS = {
                adX.name: {"@__call__": deco}
        }
        adX.bind(app)
        self.assertIs(adX.app, app)

        i = adX()
        i(2, 4, x=3)
        check.assert_called_with(i, 2, 4, x=3)

        i.annotate()
        i.annotate()
开发者ID:AdrianRibao,项目名称:celery,代码行数:29,代码来源:test_app.py


示例6: test_mysql_mode_locks_unlocks_tables

    def test_mysql_mode_locks_unlocks_tables(self, mock_create_dir, mock_get_lvm_info, mock_get_vol_fs_type, mock_popen):
        mock_get_vol_fs_type.return_value = 'xfs'
        mock_get_lvm_info.return_value = {
            'volgroup': 'lvm_volgroup',
            'srcvol': 'lvm_device',
            'snap_path': 'snap_path'}
        mock_process = Mock()
        mock_process.communicate.return_value = '', ''
        mock_process.returncode = 0
        mock_popen.return_value = mock_process

        backup_opt = Mock()
        backup_opt.snapshot = True
        backup_opt.lvm_auto_snap = ''
        backup_opt.path_to_backup = '/just/a/path'
        backup_opt.lvm_dirmount = '/var/mountpoint'
        backup_opt.lvm_snapperm = 'ro'
        backup_opt.mode = 'mysql'
        backup_opt.mysql_db_inst = Mock()
        mock_cursor = Mock()
        backup_opt.mysql_db_inst.cursor.return_value = mock_cursor

        self.assertTrue(lvm.lvm_snap(backup_opt))

        first_call = call('FLUSH TABLES WITH READ LOCK')
        second_call = call('UNLOCK TABLES')
        self.assertEquals(first_call, mock_cursor.execute.call_args_list[0])
        self.assertEquals(second_call, mock_cursor.execute.call_args_list[1])
开发者ID:sckevmit,项目名称:freezer,代码行数:28,代码来源:test_lvm.py


示例7: test_side_effect

    def test_side_effect(self):
        mock = Mock()

        def effect(*args, **kwargs):
            raise SystemError('kablooie')

        mock.side_effect = effect
        self.assertRaises(SystemError, mock, 1, 2, fish=3)
        mock.assert_called_with(1, 2, fish=3)

        results = [1, 2, 3]
        def effect():
            return results.pop()
        mock.side_effect = effect

        self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
                          "side effect not used correctly")

        mock = Mock(side_effect=sentinel.SideEffect)
        self.assertEqual(mock.side_effect, sentinel.SideEffect,
                          "side effect in constructor not used")

        def side_effect():
            return DEFAULT
        mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
        self.assertEqual(mock(), sentinel.RETURN)
开发者ID:5m0k3r,项目名称:desarrollo_web_udp,代码行数:26,代码来源:testmock.py


示例8: test_run

    def test_run(self, *mocks):

        eddaclient = Mock()
        eddaclient._since = 500

        def ret_list(args):
            return [
                {'imageId': 'ami-1', 'instanceId': 'a', 'launchTime': '500',
                 'tags': [{'key': 'service_name', 'value': 'conversion'}, {'key': 'started_by', 'value': 'john'}]},
                {'imageId': 'ami-1', 'instanceId': 'b', 'launchTime': '2000',
                 'tags': [{'key': 'service_name', 'value': 'router'}]},
                {'imageId': 'ami-2', 'instanceId': 'c', 'launchTime': '400'}]

        m = Mock()
        m.query = Mock(side_effect=ret_list)
        eddaclient.clean = Mock(return_value=m)
        self.plugin.init(eddaclient, self.config, {'first_seen': {"ami-1": 1000, "ami-2": 400}})

        real = self.plugin.run()
        expected = [
            {'id': 'ami-1', 'plugin_name': 'ami', 'details': [
                ('a', 500, [{'service_name': 'conversion'}, {'started_by': 'john'}]),
                ('b', 2000, [{'service_name': 'router'}])]}
        ]

        self.assertEqual(expected, real)

        m.query.assert_has_calls([call('/api/v2/view/instances;_expand')])
        self.assertEqual(self.plugin.status, {'first_seen': {'ami-1': 500, 'ami-2': 400}})
开发者ID:goryszewskig,项目名称:reddalert,代码行数:29,代码来源:test_ami.py


示例9: test_error_output

    def test_error_output(self):
        from planterbox import FeatureTestSuite, step

        test_feature = """Feature: A Test Feature
            Scenario: A Test Scenario
                When I fail a test
        """

        @step(r'I fail a test')
        def fail_test(test):
            test.fail('Expected Failure')

        mock_world = Mock()
        mock_world.fail_test = fail_test

        test_suite = FeatureTestSuite(mock_world, test_feature)

        test_case = test_suite._tests[0]

        def mock_addFailure(result, exc):
            self.exc_info = exc

        mock_result = Mock(addFailure=Mock(side_effect=mock_addFailure))

        test_case.run(mock_result)

        formatted = test_case.formatTraceback(self.exc_info)

        formatted_lines = formatted.split('\n')

        self.assertEqual(formatted_lines[0], 'When I fail a test')
        self.assertEqual(formatted_lines[-2],
                         'AssertionError: Expected Failure')
        self.assertEqual(unicode(test_case),
                         'A Test Scenario (A Test Feature)')
开发者ID:gcarothers,项目名称:planterbox,代码行数:35,代码来源:test_scenario_test_case.py


示例10: frame

def frame():
    frame = Mock()
    f_code = Mock()
    f_code.co_filename = 'foo.py'
    f_code.co_firstlineno = 23
    frame.f_code = f_code
    return frame
开发者ID:emou,项目名称:pdbuddy,代码行数:7,代码来源:test_filename.py


示例11: test_resource_policy_event_callback

    def test_resource_policy_event_callback(self):

        event_data = Mock()
        event_data.resource_id = 'resource._id'
        event_data.resource_type = 'resource.type_'
        event_data.resource_name = 'resource.name'
        event_data.origin = 'policy._id'

        policy_rules = 'policy_rules'
        pc = Mock()
        pc.get_active_resource_access_policy_rules.return_value = policy_rules
        self.governance_controller.policy_client = pc
        self.governance_controller.system_actor_user_header = {}
        # call resource_policy_event_callback without a PDP
        self.governance_controller.resource_policy_event_callback(event_data)
        # expect that nothing happened since there was no PDP to update
        self.assertEqual(pc.get_active_resource_access_policy_rules.called, False)

        #add a pdp
        pdp = Mock()
        self.governance_controller.policy_decision_point_manager = pdp

        self.governance_controller.resource_policy_event_callback(event_data)

        # expect that policy rules are retrieved for resource
        pc.get_active_resource_access_policy_rules.assert_called_with(event_data.resource_id, headers={})

        # expect that pdp is called with new rules
        pdp.load_resource_policy_rules.assert_called_with(event_data.resource_id, policy_rules)
开发者ID:ooici,项目名称:pyon,代码行数:29,代码来源:test_governance.py


示例12: test___init__

    def test___init__(self):
        manager = Mock()
        manager.write_to_completion_cache = Mock(return_value=None)

        info_ = {}
        robj = base.Resource(manager, info_)
        self.assertEqual(0, manager.write_to_completion_cache.call_count)

        info_ = {"id": "id-with-less-than-36-char"}
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(0, manager.write_to_completion_cache.call_count)

        id_ = "id-with-36-char-"
        for i in range(36 - len(id_)):
            id_ = id_ + "-"
        info_ = {"id": id_}
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(1, manager.write_to_completion_cache.call_count)

        info_["name"] = "test-human-id"
        # Resource.HUMAN_ID is False
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(None, robj.human_id)
        self.assertEqual(2, manager.write_to_completion_cache.call_count)

        # base.Resource.HUMAN_ID = True
        info_["HUMAN_ID"] = True
        robj = base.Resource(manager, info_)
        self.assertEqual(info_["id"], robj.id)
        self.assertEqual(info_["name"], robj.human_id)
        self.assertEqual(4, manager.write_to_completion_cache.call_count)
开发者ID:nateben,项目名称:python-troveclient,代码行数:34,代码来源:test_base.py


示例13: setUp

    def setUp(self):
        super(ManagerListTest, self).setUp()

        @contextlib.contextmanager
        def completion_cache_mock(*arg, **kwargs):
            yield

        self.manager = base.Manager()
        self.manager.api = Mock()
        self.manager.api.client = Mock()

        self.response_key = "response_key"
        self.data_p = ["p1", "p2"]
        self.body_p = {self.response_key: self.data_p}
        self.url_p = "test_url_post"
        self.manager.api.client.post = Mock(return_value=(self.url_p,
                                                          self.body_p))

        self.data_g = ["g1", "g2", "g3"]
        self.body_g = {self.response_key: self.data_g}
        self.url_g = "test_url_get"
        self.manager.api.client.get = Mock(return_value=(self.url_g,
                                                         self.body_g))

        mock = Mock()
        mock.side_effect = completion_cache_mock
        self.manager.completion_cache = mock
开发者ID:nateben,项目名称:python-troveclient,代码行数:27,代码来源:test_base.py


示例14: test__create

    def test__create(self):
        manager = base.Manager()
        manager.api = Mock()
        manager.api.client = Mock()

        response_key = "response_key"
        data_ = "test-data"
        body_ = {response_key: data_}
        url_ = "test_url_post"
        manager.api.client.post = Mock(return_value=(url_, body_))

        return_raw = True
        r = manager._create(url_, body_, response_key, return_raw)
        self.assertEqual(data_, r)

        return_raw = False

        @contextlib.contextmanager
        def completion_cache_mock(*arg, **kwargs):
            yield

        mock = Mock()
        mock.side_effect = completion_cache_mock
        manager.completion_cache = mock

        manager.resource_class = Mock(return_value="test-class")
        r = manager._create(url_, body_, response_key, return_raw)
        self.assertEqual("test-class", r)
开发者ID:nateben,项目名称:python-troveclient,代码行数:28,代码来源:test_base.py


示例15: test_has_object_permission_user

 def test_has_object_permission_user(self):
     self.request.user = self.user
     self.request.amo_user = self.request.user
     obj = Mock()
     obj.user = self.user
     eq_(self.permission.has_object_permission(self.request, 'myview', obj),
         True)
开发者ID:anushbmx,项目名称:zamboni,代码行数:7,代码来源:test_authorization.py


示例16: test_incoming_with_add

    def test_incoming_with_add(self):
        class MockResource(ModelResource):
            key = Mock()
            model_class = mock_orm.Model
            fields = [
                AttributeField(attribute='bar', type=int),
                ]

        field = URIListResourceField(attribute='foos', resource_class=MockResource)

        source_dict = {
            'foos': ['uri://resources/1', 'uri://resources/2']
        }

        target_object = mock_orm.Mock()
        related_manager = mock_orm.Manager()
        related_manager.all = Mock(return_value=mock_orm.QuerySet())
        target_object.foos = related_manager

        ctx = mock_context()
        foo1_model = Mock()
        foo2_model = Mock()
        mock_resources = Mock()
        resource1 = MockResource(foo1_model)
        resource1.key = 1
        resource2 = MockResource(foo2_model)
        resource2.key = 2
        mock_resources.side_effect = [resource1, resource2]

        ctx.resolve_resource_uri = mock_resources

        field.handle_incoming(ctx, source_dict, target_object)
        related_manager.add.assert_called_with(foo1_model, foo2_model)
开发者ID:armooo,项目名称:savory-pie,代码行数:33,代码来源:test_fields.py


示例17: mock_flavor

 def mock_flavor(self):
     flavor = Mock()
     flavor.name = 'Flavor Name'
     flavor.vcpus = 2
     flavor.ram = 256
     flavor.disk = 320
     return flavor
开发者ID:QualiSystems,项目名称:OpenStack-Shell,代码行数:7,代码来源:test_vm_details_operation.py


示例18: test_incoming_read_only

    def test_incoming_read_only(self):

        class Resource(ModelResource):
            model_class = Mock(spec=[])
            fields = [
                AttributeField(attribute='bar', type=int),
            ]

        field = SubModelResourceField(
            attribute='foo',
            resource_class=Resource,
            read_only=True,
        )

        source_dict = {
            'foo': {'bar': 20},
        }

        target_object = Mock()
        target_object.foo = Mock(['save'])

        field.handle_incoming(mock_context(), source_dict, target_object)

        self.assertFalse(hasattr(target_object.foo, 'bar'))
        self.assertFalse(target_object.foo.save.called)
开发者ID:armooo,项目名称:savory-pie,代码行数:25,代码来源:test_fields.py


示例19: test_should_find_correct_alert_type

 def test_should_find_correct_alert_type(self):
     trap = Mock('trap')
     trap.snmpTrapOID = '.1.3.6.1.4.1.17373.3.32767.0.10205'
     TRIP_TYPE_HIGH = 2
     trap.varbinds = {'.1.3.6.1.4.1.17373.3.1.6.0': TRIP_TYPE_HIGH}
     goose = wg.WeatherGoose2(trap, None, None, None)
     self.assertEquals(goose._get_alert_type(), 'cmClimateTempCTRAP')
开发者ID:alexanderfefelov,项目名称:nav,代码行数:7,代码来源:weathergoose_test.py


示例20: assert_handled

 def assert_handled(self, key, exp_handler=SAME_AS_KEY, **exp_captures):
     if exp_handler is SAME_AS_KEY:
         exp_handler = key
     if isinstance(exp_handler, types.StringTypes):
         exp_handler = exp_handler.strip("/")
     m_response = Mock(spec=etcd.EtcdResult)
     m_response.key = key
     m_response.action = self.action
     self.dispatcher.handle_event(m_response)
     exp_handlers = self.handlers[self.expected_handlers]
     for handler_key, handler in exp_handlers.iteritems():
         assert isinstance(handler, Mock)
         if handler_key == exp_handler:
             continue
         self.assertFalse(handler.called,
                          "Unexpected set handler %s was called for "
                          "key %s" % (handler_key, key))
     unexp_handlers = self.handlers[self.unexpected_handlers]
     for handler_key, handler in unexp_handlers.iteritems():
         assert isinstance(handler, Mock)
         self.assertFalse(handler.called,
                          "Unexpected del handler %s was called for "
                          "key %s" % (handler_key, key))
     if exp_handler is not None:
         exp_handlers[exp_handler].assert_called_once_with(
             m_response, **exp_captures)
开发者ID:ContainerSolutions,项目名称:calico,代码行数:26,代码来源:test_etcdutils.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python mock.NonCallableMagicMock类代码示例发布时间:2022-05-27
下一篇:
Python mock.MagicMock类代码示例发布时间: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