def test_mutex(self, lock_id='xxx'): client = Mock(name='client') with patch('kombu.transport.redis.uuid') as uuid: # Won uuid.return_value = lock_id client.setnx.return_value = True client.pipeline = ContextMock() pipe = client.pipeline.return_value pipe.get.return_value = lock_id held = False with redis.Mutex(client, 'foo1', 100): held = True assert held client.setnx.assert_called_with('foo1', lock_id) pipe.get.return_value = 'yyy' held = False with redis.Mutex(client, 'foo1', 100): held = True assert held # Did not win client.expire.reset_mock() pipe.get.return_value = lock_id client.setnx.return_value = False with pytest.raises(redis.MutexHeld): held = False with redis.Mutex(client, 'foo1', '100'): held = True assert not held client.ttl.return_value = 0 with pytest.raises(redis.MutexHeld): held = False with redis.Mutex(client, 'foo1', '100'): held = True assert not held client.expire.assert_called() # Wins but raises WatchError (and that is ignored) client.setnx.return_value = True pipe.watch.side_effect = redis.redis.WatchError() held = False with redis.Mutex(client, 'foo1', 100): held = True assert held