Ejemplo n.º 1
0
    def test_logger_kwarg(self):
        server_socket = '%s:%s' % ('[::1]', 11211)
        client = memcached.MemcacheRing([server_socket])
        self.assertIs(client.logger, logging.getLogger())

        client = memcached.MemcacheRing([server_socket], logger=self.logger)
        self.assertIs(client.logger, self.logger)
Ejemplo n.º 2
0
    def test_tls_context_kwarg(self):
        with patch('swift.common.memcached.socket.socket'):
            server = '%s:%s' % ('[::1]', 11211)
            client = memcached.MemcacheRing([server])
            self.assertIsNone(client._client_cache[server]._tls_context)

            context = mock.Mock()
            client = memcached.MemcacheRing([server], tls_context=context)
            self.assertIs(client._client_cache[server]._tls_context, context)

            key = uuid4().hex.encode('ascii')
            list(client._get_conns(key))
            context.wrap_socket.assert_called_once()
Ejemplo n.º 3
0
    def test_retry(self):
        memcache_client = memcached.MemcacheRing(
            ['1.2.3.4:11211', '1.2.3.5:11211'])
        mock1 = ExplodingMockMemcached()
        mock2 = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool([
            (mock2, mock2)
        ])
        memcache_client._client_cache['1.2.3.5:11211'] = MockedMemcachePool([
            (mock1, mock1), (mock1, mock1)
        ])
        memcache_client.set('some_key', [1, 2, 3])
        self.assertEqual(mock1.exploded, True)
        self.assertEqual(self.logger.get_lines_for_level('error'), [
            'Error talking to memcached: 1.2.3.5:11211: '
            '[Errno 32] Broken pipe',
        ])

        self.logger.clear()
        mock1.exploded = False
        self.assertEqual(memcache_client.get('some_key'), [1, 2, 3])
        self.assertEqual(mock1.exploded, True)
        self.assertEqual(self.logger.get_lines_for_level('error'), [
            'Error talking to memcached: 1.2.3.5:11211: '
            '[Errno 32] Broken pipe',
        ])
        # Check that we really did call create() twice
        self.assertEqual(memcache_client._client_cache['1.2.3.5:11211'].mocks,
                         [])
Ejemplo n.º 4
0
    def test_multi(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)
        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key')
        self.assertEquals(
            memcache_client.get_multi(('some_key2', 'some_key1'), 'multi_key'),
            [[4, 5, 6], [1, 2, 3]])
        self.assertEquals(mock.cache.values()[0][1], '0')
        self.assertEquals(mock.cache.values()[1][1], '0')
        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key',
            timeout=10)
        self.assertEquals(mock.cache.values()[0][1], '10')
        self.assertEquals(mock.cache.values()[1][1], '10')
        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key',
            time=20)
        self.assertEquals(mock.cache.values()[0][1], '20')
        self.assertEquals(mock.cache.values()[1][1], '20')

        fortydays = 50 * 24 * 60 * 60
        esttimeout = time.time() + fortydays
        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key',
            timeout=fortydays)
        self.assertTrue(
            -1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
        self.assertTrue(
            -1 <= float(mock.cache.values()[1][1]) - esttimeout <= 1)
        self.assertEquals(memcache_client.get_multi(
            ('some_key2', 'some_key1', 'not_exists'), 'multi_key'),
            [[4, 5, 6], [1, 2, 3], None])
Ejemplo n.º 5
0
 def test_get_conns(self):
     sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock1.bind(('127.0.0.1', 0))
     sock1.listen(1)
     sock1ipport = '%s:%s' % sock1.getsockname()
     sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock2.bind(('127.0.0.1', 0))
     sock2.listen(1)
     orig_port = memcached.DEFAULT_MEMCACHED_PORT
     try:
         sock2ip, memcached.DEFAULT_MEMCACHED_PORT = sock2.getsockname()
         sock2ipport = '%s:%s' % (sock2ip, memcached.DEFAULT_MEMCACHED_PORT)
         # We're deliberately using sock2ip (no port) here to test that the
         # default port is used.
         memcache_client = memcached.MemcacheRing([sock1ipport, sock2ip])
         one = two = True
         while one or two:  # Run until we match hosts one and two
             key = uuid4().hex.encode('ascii')
             for conn in memcache_client._get_conns(key):
                 if 'b' not in getattr(conn[1], 'mode', ''):
                     self.assertIsInstance(
                         conn[1], (io.RawIOBase, io.BufferedIOBase))
                 peeripport = '%s:%s' % conn[2].getpeername()
                 self.assertTrue(peeripport in (sock1ipport, sock2ipport))
                 if peeripport == sock1ipport:
                     one = False
                 if peeripport == sock2ipport:
                     two = False
         self.assertEqual(len(memcache_client._errors[sock1ipport]), 0)
         self.assertEqual(len(memcache_client._errors[sock2ip]), 0)
     finally:
         memcached.DEFAULT_MEMCACHED_PORT = orig_port
Ejemplo n.º 6
0
    def test_set_get_json(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)
        cache_key = md5(b'some_key').hexdigest().encode('ascii')

        memcache_client.set('some_key', [1, 2, 3])
        self.assertEqual(memcache_client.get('some_key'), [1, 2, 3])
        # See JSON_FLAG
        self.assertEqual(mock.cache, {cache_key: (b'2', b'0', b'[1, 2, 3]')})

        memcache_client.set('some_key', [4, 5, 6])
        self.assertEqual(memcache_client.get('some_key'), [4, 5, 6])
        self.assertEqual(mock.cache, {cache_key: (b'2', b'0', b'[4, 5, 6]')})

        memcache_client.set('some_key', ['simple str', 'utf8 str éà'])
        # As per http://wiki.openstack.org/encoding,
        # we should expect to have unicode
        self.assertEqual(memcache_client.get('some_key'),
                         ['simple str', u'utf8 str éà'])
        self.assertEqual(mock.cache, {
            cache_key:
            (b'2', b'0', b'["simple str", "utf8 str \\u00e9\\u00e0"]')
        })

        memcache_client.set('some_key', [1, 2, 3], time=20)
        self.assertEqual(mock.cache, {cache_key: (b'2', b'20', b'[1, 2, 3]')})

        sixtydays = 60 * 24 * 60 * 60
        esttimeout = time.time() + sixtydays
        memcache_client.set('some_key', [1, 2, 3], time=sixtydays)
        _junk, cache_timeout, _junk = mock.cache[cache_key]
        self.assertAlmostEqual(float(cache_timeout), esttimeout, delta=1)
Ejemplo n.º 7
0
 def test_get_conns(self):
     sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock1.bind(('127.0.0.1', 0))
     sock1.listen(1)
     sock1ipport = '%s:%s' % sock1.getsockname()
     sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock2.bind(('127.0.0.1', 0))
     sock2.listen(1)
     orig_port = memcached.DEFAULT_MEMCACHED_PORT
     try:
         sock2ip, memcached.DEFAULT_MEMCACHED_PORT = sock2.getsockname()
         sock2ipport = '%s:%s' % (sock2ip, memcached.DEFAULT_MEMCACHED_PORT)
         # We're deliberately using sock2ip (no port) here to test that the
         # default port is used.
         memcache_client = memcached.MemcacheRing([sock1ipport, sock2ip])
         one = two = True
         while one or two:  # Run until we match hosts one and two
             key = uuid4().hex
             for conn in memcache_client._get_conns(key):
                 peeripport = '%s:%s' % conn[2].getpeername()
                 self.assert_(peeripport in (sock1ipport, sock2ipport))
                 if peeripport == sock1ipport:
                     one = False
                 if peeripport == sock2ipport:
                     two = False
     finally:
         memcached.DEFAULT_MEMCACHED_PORT = orig_port
Ejemplo n.º 8
0
    def test_set_get(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)
        memcache_client.set('some_key', [1, 2, 3])
        self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
        self.assertEquals(mock.cache.values()[0][1], '0')
        memcache_client.set('some_key', [4, 5, 6])
        self.assertEquals(memcache_client.get('some_key'), [4, 5, 6])
        memcache_client.set('some_key', ['simple str', 'utf8 str éà'])
        # As per http://wiki.openstack.org/encoding,
        # we should expect to have unicode
        self.assertEquals(memcache_client.get('some_key'),
                          ['simple str', u'utf8 str éà'])
        self.assert_(float(mock.cache.values()[0][1]) == 0)
        memcache_client.set('some_key', [1, 2, 3], timeout=10)
        self.assertEquals(mock.cache.values()[0][1], '10')
        memcache_client.set('some_key', [1, 2, 3], time=20)
        self.assertEquals(mock.cache.values()[0][1], '20')

        sixtydays = 60 * 24 * 60 * 60
        esttimeout = time.time() + sixtydays
        memcache_client.set('some_key', [1, 2, 3], timeout=sixtydays)
        self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
        memcache_client.set('some_key', [1, 2, 3], time=sixtydays)
        self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
Ejemplo n.º 9
0
    def test_incr_failed_connection_mid_request(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)
        self.assertEqual(memcache_client.incr('some_key', delta=5), 5)
        self.assertEqual(memcache_client.get('some_key'), b'5')
        self.assertEqual(memcache_client.incr('some_key', delta=5), 10)
        self.assertEqual(memcache_client.get('some_key'), b'10')

        # Now lets return an empty string, and make sure we aren't logging
        # the error.
        fake_stdout = six.StringIO()
        # force the logging through the DebugLogger instead of the nose
        # handler. This will use stdout, so we can assert that no stack trace
        # is logged.
        logger = debug_logger()
        with patch("sys.stdout", fake_stdout), \
                patch('swift.common.memcached.logging', logger):
            mock.read_return_empty_str = True
            self.assertRaises(memcached.MemcacheConnectionError,
                              memcache_client.incr,
                              'some_key',
                              delta=1)
        log_lines = logger.get_lines_for_level('error')
        self.assertIn('Error talking to memcached', log_lines[0])
        self.assertFalse(log_lines[1:])
        self.assertNotIn('Traceback', fake_stdout.getvalue())
Ejemplo n.º 10
0
    def test_incr_w_timeout(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)
        cache_key = md5(b'some_key').hexdigest().encode('ascii')

        memcache_client.incr('some_key', delta=5, time=55)
        self.assertEqual(memcache_client.get('some_key'), b'5')
        self.assertEqual(mock.cache, {cache_key: (b'0', b'55', b'5')})

        memcache_client.delete('some_key')
        self.assertIsNone(memcache_client.get('some_key'))

        fiftydays = 50 * 24 * 60 * 60
        esttimeout = time.time() + fiftydays
        memcache_client.incr('some_key', delta=5, time=fiftydays)
        self.assertEqual(memcache_client.get('some_key'), b'5')
        _junk, cache_timeout, _junk = mock.cache[cache_key]
        self.assertAlmostEqual(float(cache_timeout), esttimeout, delta=1)

        memcache_client.delete('some_key')
        self.assertIsNone(memcache_client.get('some_key'))

        memcache_client.incr('some_key', delta=5)
        self.assertEqual(memcache_client.get('some_key'), b'5')
        self.assertEqual(mock.cache, {cache_key: (b'0', b'0', b'5')})

        memcache_client.incr('some_key', delta=5, time=55)
        self.assertEqual(memcache_client.get('some_key'), b'10')
        self.assertEqual(mock.cache, {cache_key: (b'0', b'0', b'10')})
Ejemplo n.º 11
0
 def test_get_conns_hostname(self):
     with patch('swift.common.memcached.socket.getaddrinfo') as addrinfo:
         try:
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             sock.bind(('127.0.0.1', 0))
             sock.listen(1)
             sock_addr = sock.getsockname()
             fqdn = socket.getfqdn()
             server_socket = '%s:%s' % (fqdn, sock_addr[1])
             addrinfo.return_value = [(socket.AF_INET,
                                       socket.SOCK_STREAM, 0, '',
                                       ('127.0.0.1', sock_addr[1]))]
             memcache_client = memcached.MemcacheRing([server_socket],
                                                      logger=self.logger)
             key = uuid4().hex.encode('ascii')
             for conn in memcache_client._get_conns(key):
                 peer_sockaddr = conn[2].getpeername()
                 peer_socket = '%s:%s' % (peer_sockaddr[0],
                                          peer_sockaddr[1])
                 self.assertEqual(peer_socket,
                                  '127.0.0.1:%d' % sock_addr[1])
             self.assertEqual(len(memcache_client._errors[server_socket]),
                              0)
         finally:
             sock.close()
Ejemplo n.º 12
0
 def test_multi(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
     memcache_client.set_multi(
         {
             'some_key1': [1, 2, 3],
             'some_key2': [4, 5, 6]
         }, 'multi_key')
     self.assertEquals(
         memcache_client.get_multi(('some_key2', 'some_key1'), 'multi_key'),
         [[4, 5, 6], [1, 2, 3]])
     esttimeout = time.time() + 10
     memcache_client.set_multi(
         {
             'some_key1': [1, 2, 3],
             'some_key2': [4, 5, 6]
         },
         'multi_key',
         timeout=10)
     self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
     self.assert_(-1 <= float(mock.cache.values()[1][1]) - esttimeout <= 1)
     self.assertEquals(
         memcache_client.get_multi(('some_key2', 'some_key1', 'not_exists'),
                                   'multi_key'),
         [[4, 5, 6], [1, 2, 3], None])
Ejemplo n.º 13
0
    def test_connection_pool_timeout(self):
        orig_conn_pool = memcached.MemcacheConnPool
        try:
            connections = defaultdict(Queue)
            pending = defaultdict(int)
            served = defaultdict(int)

            class MockConnectionPool(orig_conn_pool):
                def get(self):
                    pending[self.server] += 1
                    conn = connections[self.server].get()
                    pending[self.server] -= 1
                    return conn

                def put(self, *args, **kwargs):
                    connections[self.server].put(*args, **kwargs)
                    served[self.server] += 1

            memcached.MemcacheConnPool = MockConnectionPool

            memcache_client = memcached.MemcacheRing(
                ['1.2.3.4:11211', '1.2.3.5:11211'],
                io_timeout=0.5,
                pool_timeout=0.1)

            p = GreenPool()
            for i in range(10):
                p.spawn(memcache_client.set, 'key', 'value')

            # let everyone block
            sleep(0)
            self.assertEqual(pending['1.2.3.5:11211'], 10)

            # hand out a couple slow connection
            mock_conn = MagicMock(), MagicMock()
            mock_conn[1].sendall = lambda x: sleep(0.2)
            connections['1.2.3.5:11211'].put(mock_conn)
            connections['1.2.3.5:11211'].put(mock_conn)

            # so far so good, everyone is still waiting
            sleep(0)
            self.assertEqual(pending['1.2.3.5:11211'], 8)
            self.assertEqual(len(memcache_client._errors['1.2.3.5:11211']), 0)

            # but they won't wait longer than pool_timeout
            mock_conn = MagicMock(), MagicMock()
            connections['1.2.3.4:11211'].put(mock_conn)
            connections['1.2.3.4:11211'].put(mock_conn)
            p.waitall()
            self.assertEqual(len(memcache_client._errors['1.2.3.5:11211']), 8)
            self.assertEqual(served['1.2.3.5:11211'], 2)
            self.assertEqual(len(memcache_client._errors['1.2.3.4:11211']), 0)
            self.assertEqual(served['1.2.3.4:11211'], 8)

            # and we never got more put in that we gave out
            self.assertEqual(connections['1.2.3.5:11211'].qsize(), 2)
            self.assertEqual(connections['1.2.3.4:11211'].qsize(), 2)
        finally:
            memcached.MemcacheConnPool = orig_conn_pool
Ejemplo n.º 14
0
 def test_delete(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
     memcache_client.set('some_key', [1, 2, 3])
     self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
     memcache_client.delete('some_key')
     self.assertEquals(memcache_client.get('some_key'), None)
Ejemplo n.º 15
0
    def test_connection_pool_timeout(self):
        connections = defaultdict(Queue)
        pending = defaultdict(int)
        served = defaultdict(int)

        class MockConnectionPool(memcached.MemcacheConnPool):
            def get(self):
                pending[self.host] += 1
                conn = connections[self.host].get()
                pending[self.host] -= 1
                return conn

            def put(self, *args, **kwargs):
                connections[self.host].put(*args, **kwargs)
                served[self.host] += 1

        with mock.patch.object(memcached, 'MemcacheConnPool',
                               MockConnectionPool):
            memcache_client = memcached.MemcacheRing(
                ['1.2.3.4:11211', '1.2.3.5:11211'],
                io_timeout=0.5,
                pool_timeout=0.1,
                logger=self.logger)

            # Hand out a couple slow connections to 1.2.3.5, leaving 1.2.3.4
            # fast. All ten (10) clients should try to talk to .5 first, and
            # then move on to .4, and we'll assert all that below.
            mock_conn = MagicMock(), MagicMock()
            mock_conn[0].readline = lambda: b'STORED\r\n'
            mock_conn[1].sendall = lambda x: sleep(0.2)
            connections['1.2.3.5'].put(mock_conn)
            connections['1.2.3.5'].put(mock_conn)

            mock_conn = MagicMock(), MagicMock()
            mock_conn[0].readline = lambda: b'STORED\r\n'
            connections['1.2.3.4'].put(mock_conn)
            connections['1.2.3.4'].put(mock_conn)

            p = GreenPool()
            for i in range(10):
                p.spawn(memcache_client.set, 'key', 'value')

            # Wait for the dust to settle.
            p.waitall()

        self.assertEqual(pending['1.2.3.5'], 8)
        self.assertEqual(len(memcache_client._errors['1.2.3.5:11211']), 8)
        self.assertEqual(
            self.logger.get_lines_for_level('error'),
            ['Timeout getting a connection to memcached: 1.2.3.5:11211'] * 8)
        self.assertEqual(served['1.2.3.5'], 2)
        self.assertEqual(pending['1.2.3.4'], 0)
        self.assertEqual(len(memcache_client._errors['1.2.3.4:11211']), 0)
        self.assertEqual(served['1.2.3.4'], 8)

        # and we never got more put in that we gave out
        self.assertEqual(connections['1.2.3.5'].qsize(), 2)
        self.assertEqual(connections['1.2.3.4'].qsize(), 2)
Ejemplo n.º 16
0
    def test_connection_pooling(self):
        with patch('swift.common.memcached.socket') as mock_module:
            # patch socket, stub socket.socket, mock sock
            mock_sock = mock_module.socket.return_value

            # track clients waiting for connections
            connected = []
            connections = Queue()
            errors = []

            def wait_connect(addr):
                connected.append(addr)
                sleep(0.1)  # yield
                val = connections.get()
                if val is not None:
                    errors.append(val)

            mock_sock.connect = wait_connect

            memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'],
                                                     connect_timeout=10)
            # sanity
            self.assertEquals(1, len(memcache_client._client_cache))
            for server, pool in memcache_client._client_cache.items():
                self.assertEqual(2, pool.max_size)

            # make 10 requests "at the same time"
            p = GreenPool()
            for i in range(10):
                p.spawn(memcache_client.set, 'key', 'value')
            for i in range(3):
                sleep(0.1)
                self.assertEqual(2, len(connected))

            # give out a connection
            connections.put(None)

            # at this point, only one connection should have actually been
            # created, the other is in the creation step, and the rest of the
            # clients are not attempting to connect. we let this play out a
            # bit to verify.
            for i in range(3):
                sleep(0.1)
                self.assertEqual(2, len(connected))

            # finish up, this allows the final connection to be created, so
            # that all the other clients can use the two existing connections
            # and no others will be created.
            connections.put(None)
            connections.put('nono')
            self.assertEqual(2, len(connected))
            p.waitall()
            self.assertEqual(2, len(connected))
            self.assertEqual(0, len(errors),
                             "A client was allowed a third connection")
            connections.get_nowait()
            self.assertTrue(connections.empty())
Ejemplo n.º 17
0
    def test_connection_pool_timeout(self):
        orig_conn_pool = memcached.MemcacheConnPool
        try:
            connections = defaultdict(Queue)
            pending = defaultdict(int)
            served = defaultdict(int)

            class MockConnectionPool(orig_conn_pool):
                def get(self):
                    pending[self.server] += 1
                    conn = connections[self.server].get()
                    pending[self.server] -= 1
                    return conn

                def put(self, *args, **kwargs):
                    connections[self.server].put(*args, **kwargs)
                    served[self.server] += 1

            memcached.MemcacheConnPool = MockConnectionPool

            memcache_client = memcached.MemcacheRing(
                ['1.2.3.4:11211', '1.2.3.5:11211'],
                io_timeout=0.5,
                pool_timeout=0.1)

            # Hand out a couple slow connections to 1.2.3.5, leaving 1.2.3.4
            # fast. All ten (10) clients should try to talk to .5 first, and
            # then move on to .4, and we'll assert all that below.
            mock_conn = MagicMock(), MagicMock()
            mock_conn[1].sendall = lambda x: sleep(0.2)
            connections['1.2.3.5:11211'].put(mock_conn)
            connections['1.2.3.5:11211'].put(mock_conn)

            mock_conn = MagicMock(), MagicMock()
            connections['1.2.3.4:11211'].put(mock_conn)
            connections['1.2.3.4:11211'].put(mock_conn)

            p = GreenPool()
            for i in range(10):
                p.spawn(memcache_client.set, 'key', 'value')

            # Wait for the dust to settle.
            p.waitall()

            self.assertEqual(pending['1.2.3.5:11211'], 8)
            self.assertEqual(len(memcache_client._errors['1.2.3.5:11211']), 8)
            self.assertEqual(served['1.2.3.5:11211'], 2)
            self.assertEqual(pending['1.2.3.4:11211'], 0)
            self.assertEqual(len(memcache_client._errors['1.2.3.4:11211']), 0)
            self.assertEqual(served['1.2.3.4:11211'], 8)

            # and we never got more put in that we gave out
            self.assertEqual(connections['1.2.3.5:11211'].qsize(), 2)
            self.assertEqual(connections['1.2.3.4:11211'].qsize(), 2)
        finally:
            memcached.MemcacheConnPool = orig_conn_pool
Ejemplo n.º 18
0
 def test_retry(self):
     logging.getLogger().addHandler(NullLoggingHandler())
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211', '1.2.3.5:11211'])
     mock1 = ExplodingMockMemcached()
     mock2 = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = [(mock2, mock2)]
     memcache_client._client_cache['1.2.3.5:11211'] = [(mock1, mock1)]
     memcache_client.set('some_key', [1, 2, 3])
     self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
     self.assertEquals(mock1.exploded, True)
Ejemplo n.º 19
0
 def test_delete(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'],
                                              logger=self.logger)
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
         [(mock, mock)] * 2)
     memcache_client.set('some_key', [1, 2, 3])
     self.assertEqual(memcache_client.get('some_key'), [1, 2, 3])
     memcache_client.delete('some_key')
     self.assertIsNone(memcache_client.get('some_key'))
Ejemplo n.º 20
0
 def test_set_error(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'],
                                              logger=self.logger)
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
         [(mock, mock)] * 2)
     memcache_client.set('too-big', [1, 2, 3])
     self.assertEqual(self.logger.get_lines_for_level('error'), [
         'Error setting value in memcached: 1.2.3.4:11211: '
         'SERVER_ERROR object too large for cache'
     ])
Ejemplo n.º 21
0
 def test_get_conns(self):
     sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock1.bind(('127.0.0.1', 0))
     sock1.listen(1)
     sock1ipport = '%s:%s' % sock1.getsockname()
     sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock2.bind(('127.0.0.1', 0))
     sock2.listen(1)
     sock2ipport = '%s:%s' % sock2.getsockname()
     memcache_client = memcached.MemcacheRing([sock1ipport, sock2ipport])
     for conn in memcache_client._get_conns('40000000000000000000000000000000'):
         self.assert_('%s:%s' % conn[2].getpeername() in (sock1ipport, sock2ipport))
Ejemplo n.º 22
0
 def test_decr(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
     memcache_client.decr('some_key', delta=5)
     self.assertEquals(memcache_client.get('some_key'), '0')
     memcache_client.incr('some_key', delta=15)
     self.assertEquals(memcache_client.get('some_key'), '15')
     memcache_client.decr('some_key', delta=4)
     self.assertEquals(memcache_client.get('some_key'), '11')
     memcache_client.decr('some_key', delta=15)
     self.assertEquals(memcache_client.get('some_key'), '0')
Ejemplo n.º 23
0
 def test_set_get(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
     memcache_client.set('some_key', [1, 2, 3])
     self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
     memcache_client.set('some_key', [4, 5, 6])
     self.assertEquals(memcache_client.get('some_key'), [4, 5, 6])
     self.assert_(float(mock.cache.values()[0][1]) == 0)
     esttimeout = time.time() + 10
     memcache_client.set('some_key', [1, 2, 3], timeout=10)
     self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
Ejemplo n.º 24
0
        def do_calls(time_step, num_calls, **memcache_kwargs):
            self.logger.clear()
            memcache_client = memcached.MemcacheRing(
                ['1.2.3.5:11211'], logger=self.logger,
                **memcache_kwargs)
            mock1 = ExplodingMockMemcached()
            memcache_client._client_cache['1.2.3.5:11211'] = \
                MockedMemcachePool([(mock1, mock1)] * num_calls)

            for n in range(num_calls):
                with mock.patch.object(memcached.time, 'time',
                                       return_value=time_step * n):
                    memcache_client.set('some_key', [1, 2, 3])
Ejemplo n.º 25
0
    def test_multi(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'],
                                                 logger=self.logger)
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)

        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key')
        self.assertEqual(
            memcache_client.get_multi(('some_key2', 'some_key1'), 'multi_key'),
            [[4, 5, 6], [1, 2, 3]])
        for key in (b'some_key1', b'some_key2'):
            key = md5(key, usedforsecurity=False).hexdigest().encode('ascii')
            self.assertIn(key, mock.cache)
            _junk, cache_timeout, _junk = mock.cache[key]
            self.assertEqual(cache_timeout, b'0')

        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key',
            time=20)
        for key in (b'some_key1', b'some_key2'):
            key = md5(key, usedforsecurity=False).hexdigest().encode('ascii')
            _junk, cache_timeout, _junk = mock.cache[key]
            self.assertEqual(cache_timeout, b'20')

        fortydays = 50 * 24 * 60 * 60
        esttimeout = time.time() + fortydays
        memcache_client.set_multi(
            {'some_key1': [1, 2, 3], 'some_key2': [4, 5, 6]}, 'multi_key',
            time=fortydays)
        for key in (b'some_key1', b'some_key2'):
            key = md5(key, usedforsecurity=False).hexdigest().encode('ascii')
            _junk, cache_timeout, _junk = mock.cache[key]
            self.assertAlmostEqual(float(cache_timeout), esttimeout, delta=1)
        self.assertEqual(memcache_client.get_multi(
            ('some_key2', 'some_key1', 'not_exists'), 'multi_key'),
            [[4, 5, 6], [1, 2, 3], None])

        # Now lets simulate a lost connection and make sure we don't get
        # the index out of range stack trace when it does
        mock_stderr = six.StringIO()
        not_expected = "IndexError: list index out of range"
        with patch("sys.stderr", mock_stderr):
            mock.read_return_empty_str = True
            self.assertEqual(memcache_client.get_multi(
                ('some_key2', 'some_key1', 'not_exists'), 'multi_key'),
                None)
            self.assertFalse(not_expected in mock_stderr.getvalue())
Ejemplo n.º 26
0
    def test_multi(self):
        memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
        mock = MockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock, mock)] * 2)

        memcache_client.set_multi(
            {
                'some_key1': [1, 2, 3],
                'some_key2': [4, 5, 6]
            }, 'multi_key')
        self.assertEqual(
            memcache_client.get_multi(('some_key2', 'some_key1'), 'multi_key'),
            [[4, 5, 6], [1, 2, 3]])
        for key in ('some_key1', 'some_key2'):
            key = md5(key).hexdigest()
            self.assertIn(key, mock.cache)
            _junk, cache_timeout, _junk = mock.cache[key]
            self.assertEqual(cache_timeout, '0')

        memcache_client.set_multi(
            {
                'some_key1': [1, 2, 3],
                'some_key2': [4, 5, 6]
            },
            'multi_key',
            time=20)
        for key in ('some_key1', 'some_key2'):
            key = md5(key).hexdigest()
            _junk, cache_timeout, _junk = mock.cache[key]
            self.assertEqual(cache_timeout, '20')

        fortydays = 50 * 24 * 60 * 60
        esttimeout = time.time() + fortydays
        memcache_client.set_multi(
            {
                'some_key1': [1, 2, 3],
                'some_key2': [4, 5, 6]
            },
            'multi_key',
            time=fortydays)
        for key in ('some_key1', 'some_key2'):
            key = md5(key).hexdigest()
            _junk, cache_timeout, _junk = mock.cache[key]
            self.assertAlmostEqual(float(cache_timeout), esttimeout, delta=1)
        self.assertEqual(
            memcache_client.get_multi(('some_key2', 'some_key1', 'not_exists'),
                                      'multi_key'),
            [[4, 5, 6], [1, 2, 3], None])
Ejemplo n.º 27
0
    def test_error_disabled(self):
        memcache_client = memcached.MemcacheRing(
            ['1.2.3.4:11211'], logger=self.logger, error_limit_time=0)
        mock1 = ExplodingMockMemcached()
        memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
            [(mock1, mock1)] * 20)

        for _ in range(20):
            memcache_client.set('some_key', [1, 2, 3])
        # twelfth one skips .5 because of error limiting and goes straight
        # to .4
        self.assertEqual(self.logger.get_lines_for_level('error'), [
            'Error talking to memcached: 1.2.3.4:11211: '
            '[Errno 32] Broken pipe',
        ] * 20)
Ejemplo n.º 28
0
 def test_decr(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = MockedMemcachePool(
         [(mock, mock)] * 2)
     self.assertEqual(memcache_client.decr('some_key', delta=5), 0)
     self.assertEqual(memcache_client.get('some_key'), b'0')
     self.assertEqual(memcache_client.incr('some_key', delta=15), 15)
     self.assertEqual(memcache_client.get('some_key'), b'15')
     self.assertEqual(memcache_client.decr('some_key', delta=4), 11)
     self.assertEqual(memcache_client.get('some_key'), b'11')
     self.assertEqual(memcache_client.decr('some_key', delta=15), 0)
     self.assertEqual(memcache_client.get('some_key'), b'0')
     mock.read_return_none = True
     self.assertRaises(memcached.MemcacheConnectionError,
                       memcache_client.decr, 'some_key', delta=15)
Ejemplo n.º 29
0
 def test_set_get(self):
     memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'])
     mock = MockMemcached()
     memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
     memcache_client.set('some_key', [1, 2, 3])
     self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
     memcache_client.set('some_key', [4, 5, 6])
     self.assertEquals(memcache_client.get('some_key'), [4, 5, 6])
     memcache_client.set('some_key', ['simple str', 'utf8 str éà'])
     # As per http://wiki.openstack.org/encoding, we should expect to have unicode
     self.assertEquals(memcache_client.get('some_key'),
                       ['simple str', u'utf8 str éà'])
     self.assert_(float(mock.cache.values()[0][1]) == 0)
     esttimeout = time.time() + 10
     memcache_client.set('some_key', [1, 2, 3], timeout=10)
     self.assert_(-1 <= float(mock.cache.values()[0][1]) - esttimeout <= 1)
Ejemplo n.º 30
0
 def test_get_conns_v6(self):
     if not socket.has_ipv6:
         return
     try:
         sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
         sock.bind(('::1', 0, 0, 0))
         sock.listen(1)
         sock_addr = sock.getsockname()
         server_socket = '[%s]:%s' % (sock_addr[0], sock_addr[1])
         memcache_client = memcached.MemcacheRing([server_socket])
         key = uuid4().hex.encode('ascii')
         for conn in memcache_client._get_conns(key):
             peer_sockaddr = conn[2].getpeername()
             peer_socket = '[%s]:%s' % (peer_sockaddr[0], peer_sockaddr[1])
             self.assertEqual(peer_socket, server_socket)
         self.assertEqual(len(memcache_client._errors[server_socket]), 0)
     finally:
         sock.close()