# Copyright 2013 Metacloud, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import time
import uuid

from dogpile.cache import api
from dogpile.cache import proxy
from dogpile.cache import util
import mock
import six
from testtools import matchers

from keystone.common.kvs.backends import inmemdb
from keystone.common.kvs.backends import memcached
from keystone.common.kvs import core
from keystone import exception
from keystone.tests import unit


NO_VALUE = api.NO_VALUE


class MutexFixture(object):
    def __init__(self, storage_dict, key, timeout):
        self.database = storage_dict
        self.key = '_lock' + key

    def acquire(self, wait=True):
        while True:
            try:
                self.database[self.key] = 1
                return True
            except KeyError:
                return False

    def release(self):
        self.database.pop(self.key, None)


class KVSBackendFixture(inmemdb.MemoryBackend):
    def __init__(self, arguments):
        class InmemTestDB(dict):
            def __setitem__(self, key, value):
                if key in self:
                    raise KeyError('Key %s already exists' % key)
                super(InmemTestDB, self).__setitem__(key, value)

        self._db = InmemTestDB()
        self.lock_timeout = arguments.pop('lock_timeout', 5)