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


Python MagicMock.__getitem__方法代码示例

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


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

示例1: create_connection

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
 def create_connection(self):
     conn = MagicMock(MongoClient)
     db = MagicMock(Database)
     coll = MagicMock(Collection)
     conn.__getitem__ = MagicMock(return_value=db)
     db.__getitem__ = MagicMock(return_value=coll)
     return conn
开发者ID:zenreach,项目名称:mongoutils,代码行数:9,代码来源:test_index.py

示例2: test_object_identity

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
def test_object_identity():
    '''Check that values that are modified are what is returned'''
    class FieldTester(object):
        __metaclass__ = ModelMetaclass

        field_a = List(scope=Scope.settings)

        def __init__(self, model_data):
            self._model_data = model_data

    # Make sure that model_data always returns a different object
    # each time it's actually queried, so that the caching is
    # doing the work to maintain object identity.
    model_data = MagicMock(spec=dict)
    model_data.__getitem__ = lambda self, name: [name]
    field_tester = FieldTester(model_data)

    value = field_tester.field_a
    assert_equals(value, field_tester.field_a)

    # Changing the field in place matches a previously fetched value
    field_tester.field_a.append(1)
    assert_equals(value, field_tester.field_a)

    # Changing the previously-fetched value also changes the value returned by the field:
    value.append(2)
    assert_equals(value, field_tester.field_a)

    # Deletion restores the default value.  In the case of a List with
    # no default defined, this is the empty list.
    del field_tester.field_a
    assert_equals([], field_tester.field_a)
开发者ID:hsiungsaas,项目名称:XBlock,代码行数:34,代码来源:test_core.py

示例3: test__gather_data

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
    def test__gather_data(self, mock_stat):
        path = '/test'
        mock_stat.side_effect = OSError
        self.assertFalse(self.ptool._gather_data(path)[0])
        mock_stat.assert_called_with(path)

        mock_stat.reset_mock()
        mock_stat.side_effect = None
        # create a return value
        stat_rv = MagicMock()
        def stat_getitem(key):
            if int(key) == stat.ST_UID:
                return 0
            elif int(key) == stat.ST_GID:
                return 10
            elif int(key) == stat.ST_MODE:
                # return extra bits in the mode to emulate a device
                # and ensure that they're stripped
                return int('060660', 8)
        stat_rv.__getitem__ = Mock(side_effect=stat_getitem)
        mock_stat.return_value = stat_rv

        # disable selinux and acls for this call -- we test them
        # separately so that we can skip those tests as appropriate
        states = (Bcfg2.Client.Tools.POSIX.base.HAS_SELINUX,
                  Bcfg2.Client.Tools.POSIX.base.HAS_ACLS)
        Bcfg2.Client.Tools.POSIX.base.HAS_SELINUX = False
        Bcfg2.Client.Tools.POSIX.base.HAS_ACLS = False
        self.assertEqual(self.ptool._gather_data(path),
                         (stat_rv, '0', '10', '0660', None, None))
        Bcfg2.Client.Tools.POSIX.base.HAS_SELINUX, \
            Bcfg2.Client.Tools.POSIX.base.HAS_ACLS = states
        mock_stat.assert_called_with(path)
开发者ID:timl,项目名称:bcfg2,代码行数:35,代码来源:Testbase.py

示例4: test_caching_is_per_instance

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
def test_caching_is_per_instance():
    # Test that values cached for one instance do not appear on another
    class FieldTester(object):
        """Toy class for ModelMetaclass and field access testing"""
        __metaclass__ = ModelMetaclass

        field_a = List(scope=Scope.settings)

        def __init__(self, model_data):
            self._model_data = model_data
            self._dirty_fields = set()

    model_data = MagicMock(spec=dict)
    model_data.__getitem__ = lambda self, name: [name]

    # Same model_data used in different objects should result
    # in separately-cached values, so that changing a value
    # in one instance doesn't affect values stored in others.
    field_tester_a = FieldTester(model_data)
    field_tester_b = FieldTester(model_data)
    value = field_tester_a.field_a
    assert_equals(value, field_tester_a.field_a)
    field_tester_a.field_a.append(1)
    assert_equals(value, field_tester_a.field_a)
    assert_not_equals(value, field_tester_b.field_a)
开发者ID:metajon,项目名称:XBlock,代码行数:27,代码来源:test_core.py

示例5: test_invalid_page

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
    def test_invalid_page(self):
        mocked_qs = MagicMock()
        mocked_qs.__getitem__().execute().hits.total = 30000
        paginator = ESPaginator(mocked_qs, 5)

        assert ESPaginator.max_result_window == 25000

        with pytest.raises(InvalidPage) as exc:
            # We're fetching 5 items per page, so requesting page 5001 should
            # fail, since the max result window should is set to 25000.
            paginator.page(5000 + 1)

        # Make sure we raise exactly `InvalidPage`, this is needed
        # unfortunately since `pytest.raises` won't check the exact
        # instance but also accepts parent exceptions inherited.
        assert (
            exc.value.message ==
            'That page number is too high for the current page size')
        assert isinstance(exc.value, InvalidPage)

        with self.assertRaises(EmptyPage):
            paginator.page(0)

        with self.assertRaises(PageNotAnInteger):
            paginator.page('lol')
开发者ID:tsl143,项目名称:addons-server,代码行数:27,代码来源:test_pagination.py

示例6: test_check_for_meta_not_m

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
 def test_check_for_meta_not_m(self):
     result = MagicMock(name="result")
     result.attrs = {
         "content": "somewords;url=",
         "http-equiv": 'refresh',
     }
     result.__getitem__ = Mock(return_value=result.attrs["content"])
     with patch.object(BeautifulSoup, "find", return_value=result):
         res = check_for_meta("content", "url")
     self.assertEqual(res, None)
开发者ID:alkhamush,项目名称:tech-testing-ha1,代码行数:12,代码来源:test_init.py

示例7: test_no_pages_beyond_max_window_result

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
    def test_no_pages_beyond_max_window_result(self):
        mocked_qs = MagicMock()
        mocked_qs.__getitem__().execute().hits.total = 30000
        paginator = ESPaginator(mocked_qs, 5)

        assert ESPaginator.max_result_window == 25000

        page = paginator.page(4999)
        assert page.has_next() is True

        page = paginator.page(5000)
        assert page.has_next() is False
开发者ID:tsl143,项目名称:addons-server,代码行数:14,代码来源:test_pagination.py

示例8: test_wrap_method

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
    def test_wrap_method(self):
        old_cache_get = cache.cache.get
        old_cache_set = cache.cache.set
        try:
            key = 'data'
            value = 'ValueOfMyKey'
            data = {}

            self.cached.get_key = MagicMock(return_value=key)

            cached_value = MagicMock()
            cached_value.is_valid.return_value = False
            cached_value.__getitem__ = lambda s, k: data[k]
            cached_value.__setitem__ = lambda s, k, v: data.update({k: v})

            func = Mock(__name__=key, return_value=value)
            self.cached.function = func
            cache.cache.get = lambda k: cached_value
            cache.cache.set = lambda k, v, e: data.update({key: v, 'e-%s' % key: e})

            wrap = self.cached(func)
            wrap()
            self.assertTrue(func.called)

            self.assertIsInstance(data[key], dict)
            self.assertIn('data', data[key])
            self.assertIn('expire_date', data[key])
            self.assertIsInstance(data['e-%s' % key], int)
            self.assertEqual(value, data[key]['data'])

            cached_value.is_valid.return_value = True
            value = wrap()

            self.assertEqual(1, func.call_count)
            self.assertEqual(cached_value['data'], value)

            cached_value.is_valid.return_value = False
            func = Mock(__name__=key, return_value=value)
            func.side_effect = Exception('Boom!')
            self.cached.function = func
            value = wrap()
            self.assertEqual(cached_value['data'], value)

            cache.cache.get = lambda k: None
            self.assertRaises(Exception, wrap, ())
        finally:
            cache.cache.get = old_cache_get
            cache.cache.set = old_cache_set
开发者ID:globocom,项目名称:memcached_memoize,代码行数:50,代码来源:test_decorators.py

示例9: test_single_hit

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
    def test_single_hit(self):
        """Test the ESPaginator only queries ES one time."""
        mocked_qs = MagicMock()
        mocked_qs.count.return_value = 42
        paginator = Paginator(mocked_qs, 5)
        # With the base paginator, requesting any page forces a count.
        paginator.page(1)
        assert paginator.count == 42
        assert mocked_qs.count.call_count == 1

        mocked_qs = MagicMock()
        mocked_qs.__getitem__().execute().hits.total = 666
        paginator = ESPaginator(mocked_qs, 5)
        # With the ES paginator, the count is fetched from the 'total' key
        # in the results.
        paginator.page(1)
        assert paginator.count == 666
        assert mocked_qs.count.call_count == 0
开发者ID:Natim,项目名称:addons-server,代码行数:20,代码来源:test_paginator.py

示例10: setup_save_failure

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
def setup_save_failure(update_method):
    """
    Set up tests for when there's a save error in the underlying KeyValueStore
    """
    model_data = MagicMock(spec=dict)
    model_data.__getitem__ = lambda self, name: [name]

    model_data.update = update_method

    class FieldTester(XBlock):
        """
        Test XBlock with three fields
        """
        field_a = Integer(scope=Scope.settings)
        field_b = Integer(scope=Scope.content, default=10)
        field_c = Integer(scope=Scope.user_state, default='field c')

    field_tester = FieldTester(MagicMock(), model_data)
    return field_tester
开发者ID:metajon,项目名称:XBlock,代码行数:21,代码来源:test_core.py

示例11: _create_database

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
 def _create_database(self, collections):
     collections = OrderedDict(collections)
     db = MagicMock(spec=Database)
     db.collection_names = Mock(return_value=collections.keys())
     db.__getitem__ = lambda s, x: MockCollection(collections[x])
     return db
开发者ID:gnublade,项目名称:cursedmongo,代码行数:8,代码来源:tests.py

示例12: CCITests_unittests

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
class CCITests_unittests(unittest.TestCase):

    def setUp(self):
        self.client = MagicMock()
        self.cci = SoftLayer.CCIManager(self.client)

    def test_list_instances(self):
        mcall = call(mask=ANY, filter={})
        service = self.client.__getitem__()

        self.cci.list_instances(hourly=True, monthly=True)
        service.getVirtualGuests.assert_has_calls(mcall)

        self.cci.list_instances(hourly=False, monthly=False)
        service.getVirtualGuests.assert_has_calls(mcall)

        self.cci.list_instances(hourly=False, monthly=True)
        service.getMonthlyVirtualGuests.assert_has_calls(mcall)

        self.cci.list_instances(hourly=True, monthly=False)
        service.getHourlyVirtualGuests.assert_has_calls(mcall)

    def test_list_instances_with_filters(self):
        self.cci.list_instances(
            hourly=True,
            monthly=True,
            tags=['tag1', 'tag2'],
            cpus=2,
            memory=1024,
            hostname='hostname',
            domain='example.com',
            local_disk=True,
            datacenter='dal05',
            nic_speed=100,
            public_ip='1.2.3.4',
            private_ip='4.3.2.1',
        )

        service = self.client.__getitem__()
        service.getVirtualGuests.assert_has_calls(call(
            filter={
                'virtualGuests': {
                    'datacenter': {
                        'name': {'operation': '_= dal05'}},
                    'domain': {'operation': '_= example.com'},
                    'tagReferences': {
                        'tag': {'name': {
                            'operation': 'in',
                            'options': [{
                                'name': 'data', 'value': ['tag1', 'tag2']}]}}},
                    'maxCpu': {'operation': 2},
                    'localDiskFlag': {'operation': True},
                    'maxMemory': {'operation': 1024},
                    'hostname': {'operation': '_= hostname'},
                    'networkComponents': {'maxSpeed': {'operation': 100}},
                    'primaryIpAddress': {'operation': '_= 1.2.3.4'},
                    'primaryBackendIpAddress': {'operation': '_= 4.3.2.1'}
                }},
            mask=ANY,
        ))

    def test_resolve_ids_ip(self):
        self.client.__getitem__().getVirtualGuests.return_value = \
            [{'id': '1234'}]
        _id = self.cci._get_ids_from_ip('1.2.3.4')
        self.assertEqual(_id, ['1234'])

        self.client.__getitem__().getVirtualGuests.side_effect = \
            [[], [{'id': '4321'}]]
        _id = self.cci._get_ids_from_ip('4.3.2.1')
        self.assertEqual(_id, ['4321'])

        _id = self.cci._get_ids_from_ip('nope')
        self.assertEqual(_id, [])

    def test_resolve_ids_hostname(self):
        self.client.__getitem__().getVirtualGuests.return_value = \
            [{'id': '1234'}]
        _id = self.cci._get_ids_from_hostname('hostname')
        self.assertEqual(_id, ['1234'])

    def test_get_instance(self):
        self.client.__getitem__().getObject.return_value = {
            'hourlyVirtualGuests': "this is unique"}
        self.cci.get_instance(1)
        self.client.__getitem__().getObject.assert_called_once_with(
            id=1, mask=ANY)

    def test_get_create_options(self):
        self.cci.get_create_options()
        f = self.client.__getitem__().getCreateObjectOptions
        f.assert_called_once_with()

    def test_cancel_instance(self):
        self.cci.cancel_instance(id=1)
        self.client.__getitem__().deleteObject.assert_called_once_with(id=1)

    def test_reload_instance(self):
        self.cci.reload_instance(id=1)
        f = self.client.__getitem__().reloadCurrentOperatingSystemConfiguration
#.........这里部分代码省略.........
开发者ID:hugomatic,项目名称:softlayer-api-python-client,代码行数:103,代码来源:cci_tests.py

示例13: HardwareTests

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
class HardwareTests(unittest.TestCase):

    def setUp(self):
        self.client = MagicMock()
        self.hardware = HardwareManager(self.client)

    def test_list_hardware(self):
        mcall = call(mask=ANY, filter={})
        service = self.client['Account']
        service.getHardware = account_mock.getHardware_Mock()

        self.hardware.list_hardware()
        service.getHardware.assert_has_calls(mcall)

    def test_list_hardware_with_filters(self):
        service = self.client['Account']
        service.getHardware = account_mock.getHardware_Mock()
        self.hardware.list_hardware(
            tags=['tag1', 'tag2'],
            cpus=2,
            memory=1,
            hostname='hostname',
            domain='example.com',
            datacenter='dal05',
            nic_speed=100,
            public_ip='1.2.3.4',
            private_ip='4.3.2.1',
        )
        service.getHardware.assert_has_calls(call(
            filter={
                'hardware': {
                    'datacenter': {'name': {'operation': '_= dal05'}},
                    'domain': {'operation': '_= example.com'},
                    'tagReferences': {
                        'tag': {'name': {
                            'operation': 'in',
                            'options': [
                                {'name': 'data', 'value': ['tag1', 'tag2']}]
                        }}
                    },
                    'memoryCapacity': {'operation': 1},
                    'processorPhysicalCoreAmount': {'operation': 2},
                    'hostname': {'operation': '_= hostname'},
                    'primaryIpAddress': {'operation': '_= 1.2.3.4'},
                    'networkComponents': {'maxSpeed': {'operation': 100}},
                    'primaryBackendIpAddress': {'operation': '_= 4.3.2.1'}}
            },
            mask=ANY,
        ))

    def test_resolve_ids_ip(self):
        service = self.client['Account']
        service.getHardware = account_mock.getHardware_Mock(1000)
        _id = self.hardware._get_ids_from_ip('172.16.1.100')
        self.assertEqual(_id, [1000])

        _id = self.hardware._get_ids_from_ip('nope')
        self.assertEqual(_id, [])

        # Now simulate a private IP test
        service.getHardware.side_effect = [[], [{'id': 99}]]
        _id = self.hardware._get_ids_from_ip('10.0.1.87')
        self.assertEqual(_id, [99])

    def test_resolve_ids_hostname(self):
        service = self.client['Account']
        service.getHardware = account_mock.getHardware_Mock(1000)
        _id = self.hardware._get_ids_from_hostname('hardware-test1')
        self.assertEqual(_id, [1000])

    def test_get_hardware(self):
        service = self.client['Hardware']
        service.getObject = hardware_mock.getObject_Mock(1000)
        result = self.hardware.get_hardware(1000)
        self.client['Hardware'].getObject.assert_called_once_with(
            id=1000, mask=ANY)
        expected = hardware_mock.get_raw_hardware_mocks()[1000]
        self.assertEqual(expected, result)

    def test_reload(self):
        post_uri = 'http://test.sftlyr.ws/test.sh'
        self.hardware.reload(id=1, post_uri=post_uri, ssh_keys=[1701])
        f = self.client.__getitem__().reloadOperatingSystem
        f.assert_called_once_with('FORCE',
                                  {'customProvisionScriptUri': post_uri,
                                   'sshKeyIds': [1701]}, id=1)

    def test_get_bare_metal_create_options_returns_none_on_error(self):
        self.client['Product_Package'].getAllObjects.return_value = [
            {'name': 'No Matching Instances', 'id': 0}]

        self.assertIsNone(self.hardware.get_bare_metal_create_options())

    def test_get_bare_metal_create_options(self):
        package_id = 50

        self._setup_package_mocks()

        self.hardware.get_bare_metal_create_options()

#.........这里部分代码省略.........
开发者ID:loles,项目名称:softlayer-api-python-client,代码行数:103,代码来源:hardware_tests.py

示例14: DNSTests

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
class DNSTests(unittest.TestCase):
    def setUp(self):
        self.client = MagicMock()
        self.dns_client = SoftLayer.DNSManager(self.client)

    def test_init_exercise(self):
        self.assertTrue(hasattr(self.dns_client, "domain"))
        self.assertTrue(hasattr(self.dns_client, "record"))

    def test_list_zones(self):
        zone_list = ["test"]
        self.client.__getitem__().getDomains.return_value = zone_list
        zones = self.dns_client.list_zones()
        self.assertEqual(zones, zone_list)

    def test_get_zone(self):
        zone_list = [{"name": "test-example.com"}, {"name": "example.com"}]

        # match
        self.client.__getitem__().getByDomainName.return_value = zone_list
        res = self.dns_client.get_zone("example.com")
        self.assertEqual(res, zone_list[1])

        # no match
        from SoftLayer.DNS import DNSZoneNotFound

        self.assertRaises(DNSZoneNotFound, self.dns_client.get_zone, "shouldnt-match.com")

    def test_create_zone(self):
        self.client.__getitem__().createObject.return_value = {"name": "example.com"}

        res = self.dns_client.create_zone("example.com")
        self.assertEqual(res, {"name": "example.com"})

    def test_delete_zone(self):
        self.dns_client.delete_zone(1)
        self.client.__getitem__().deleteObject.assert_called_once_with(id=1)

    def test_edit_zone(self):
        self.dns_client.edit_zone("example.com")
        self.client.__getitem__().editObject.assert_called_once_with("example.com")

    def test_create_record(self):
        self.dns_client.create_record(1, "test", "TXT", "testing", ttl=1200)

        self.client.__getitem__().createObject.assert_called_once_with(
            {"domainId": 1, "ttl": 1200, "host": "test", "type": "TXT", "data": "testing"}
        )

    def test_delete_record(self):
        self.dns_client.delete_record(1)
        self.client.__getitem__().deleteObject.assert_called_once_with(id=1)

    def test_search_record(self):
        self.client.__getitem__().getByDomainName.return_value = [
            {"name": "example.com", "resourceRecords": [{"host": "TEST1"}, {"host": "test2"}, {"host": "test3"}]}
        ]

        res = self.dns_client.search_record("example.com", "test1")
        self.assertEqual(res, [{"host": "TEST1"}])

    def test_edit_record(self):
        self.dns_client.edit_record({"id": 1, "name": "test"})
        self.client.__getitem__().editObject.assert_called_once_with({"id": 1, "name": "test"}, id=1)

    def test_dump_zone(self):
        self.client.__getitem__().getZoneFileContents.return_value = "lots of text"
        self.dns_client.dump_zone(1)
        self.client.__getitem__().getZoneFileContents.assert_called_once_with(id=1)
开发者ID:hugomatic,项目名称:softlayer-api-python-client,代码行数:71,代码来源:dns_tests.py

示例15: SSLTests_unittests

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import __getitem__ [as 别名]
class SSLTests_unittests(unittest.TestCase):

    def setUp(self):
        self.client = MagicMock()
        self.ssl = SSLManager(self.client)
        self.test_id = 10

    def test_list_certs(self):
        self.ssl.list_certs('valid')
        self.client.__getitem__() \
            .getValidSecurityCertificates.assert_called_once_with(mask=ANY)

        self.ssl.list_certs('expired')
        self.client.__getitem__() \
            .getExpiredSecurityCertificates.assert_called_once_with(mask=ANY)

        self.ssl.list_certs('all')
        self.client.__getitem__() \
            .getSecurityCertificates.assert_called_once_with(mask=ANY)

    def test_add_certificate(self):
        test_cert = {
            'certificate': 'cert',
            'privateKey': 'key',
        }

        self.ssl.add_certificate(test_cert)

        self.client.__getitem__().createObject.assert_called_once_with(
            test_cert)

    def test_remove_certificate(self):
        self.ssl.remove_certificate(self.test_id)
        self.client.__getitem__() \
            .deleteObject.assert_called_once_with(id=self.test_id)

    def test_edit_certificate(self):
        test_cert = {
            'id': self.test_id,
            'certificate': 'cert',
            'privateKey': 'key'
        }

        self.ssl.edit_certificate(test_cert)
        self.client.__getitem__().editObject.assert_called_once_with(
            {
                'id': self.test_id,
                'certificate': 'cert',
                'privateKey': 'key'
            },
            id=self.test_id)

    def test_get_certificate(self):
        self.ssl.get_certificate(self.test_id)
        self.client.__getitem__().getObject.assert_called_once_with(
            id=self.test_id)
开发者ID:quiteliderally,项目名称:softlayer-api-python-client,代码行数:58,代码来源:ssl_tests.py


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