Exemplo n.º 1
0
def test_cache_manager_configure_class():
    """Test that CacheManager can configure caches with a custom cache class."""
    cacheman = CacheManager({"a": {"cache_class": MyCache}})
    assert isinstance(cacheman["a"], MyCache)

    cacheman = CacheManager()
    cacheman.configure("a", cache_class=MyCache)
    assert isinstance(cacheman["a"], MyCache)
Exemplo n.º 2
0
def test_cache_manager_configure_class():
    """Test that CacheManager can configure caches with a custom cache class.
    """
    cacheman = CacheManager({'a': {'cache_class': MyCache}})
    assert isinstance(cacheman['a'], MyCache)

    cacheman = CacheManager()
    cacheman.configure('a', cache_class=MyCache)
    assert isinstance(cacheman['a'], MyCache)
Exemplo n.º 3
0
    def __init__(self):
        # 重写并继承父类的init方法
        super(Sanic_server, self).__init__()

        self.dict = {}
        self.redis_obj = self._create_redis_connection_pool(
            REDIS_HOST, REDIS_POST, REDIS_PASS, SELECT_DB)
        '''
        当你经常使用某些数据模板和信息时就要考虑缓存了
        缓存机制:cacheout
        设置多个缓存, 并设置缓存机制
        maxsize:代码缓存保留信息条目数
        ttl:每条信息的有效期(单位:秒)
        LRU (最近最少使用机制),就是删除最近最少使用的,保留最近最多使用的
        具体介绍:公众号-python疯子
        
        '''
        self.cache = CacheManager(
            {
                "voice_store": {
                    "maxsize": 1000
                },
                "mysql_store": {
                    "maxsize": 1000,
                    "ttl": 2529000
                }
            },
            cache_class=LRUCache)
Exemplo n.º 4
0
def test_cache_manager_contains():
    """Test that CacheManager contains returns whether named cache exists."""
    settings = {str(n): {} for n in range(5)}
    cacheman = CacheManager(settings)

    for name in settings.keys():
        assert name in cacheman
Exemplo n.º 5
0
def test_cache_manager_configure():
    """Test that CacheManager can configure individual caches."""
    name = "a"
    options = {"maxsize": 10, "ttl": 60}
    cacheman = CacheManager()
    cacheman.configure(name, **options)

    assert_cache_options(cacheman[name], options)
Exemplo n.º 6
0
def test_cache_manager_configure():
    """Test that CacheManager can configure individual caches."""
    name = 'a'
    options = {'maxsize': 10, 'ttl': 60}
    cacheman = CacheManager()
    cacheman.configure(name, **options)

    assert_cache_options(cacheman[name], options)
Exemplo n.º 7
0
def test_cache_manager_repr():
    settings = {"a": {}, "b": {}, "c": {}}
    cacheman = CacheManager()

    assert repr(cacheman) == "CacheManager([])"

    cacheman.setup(settings)

    assert repr(cacheman) == "CacheManager(['a', 'b', 'c'])"
Exemplo n.º 8
0
def test_cache_manager_cache_names():
    """Test that CacheManager can return a list of cache names."""
    settings = {str(n): {} for n in range(5)}
    cacheman = CacheManager(settings)

    names = cacheman.cache_names()

    assert isinstance(names, list)
    assert set(names) == set(settings)
Exemplo n.º 9
0
 def source(self):
     ca = CacheManager({
         "a": {
             "maxsize": CacheAdapter.__maxsize
         },
         "b": {
             "maxsize": CacheAdapter.__maxsize
         }
     })
Exemplo n.º 10
0
def test_cache_manager_repr():
    settings = {'a': {}, 'b': {}, 'c': {}}
    cacheman = CacheManager()

    assert repr(cacheman) == 'CacheManager([])'

    cacheman.setup(settings)

    assert repr(cacheman) == "CacheManager(['a', 'b', 'c'])"
Exemplo n.º 11
0
def test_cache_manager_caches():
    """Test that CacheManager can return a list of caches."""
    settings = {str(n): {} for n in range(5)}
    cacheman = CacheManager(settings)

    caches = cacheman.caches()

    assert isinstance(caches, list)
    assert len(caches) == len(settings)

    for _, cache in cacheman:
        assert cache in caches
Exemplo n.º 12
0
def test_cache_manager_init_configure():
    """Test that CacheManager can configure bulk caches."""
    settings = {'a': {},
                'b': {'maxsize': 10},
                'c': {'ttl': 60},
                'd': {'maxsize': 10, 'ttl': 60}}
    cacheman = CacheManager(settings)

    for name, options in settings.items():
        cache = cacheman[name]
        assert isinstance(cache, Cache)
        assert_cache_options(cache, options)
Exemplo n.º 13
0
def test_cache_manager_clear_all():
    """That that CacheManager can clear all caches."""
    settings = {str(n): {} for n in range(5)}
    cacheman = CacheManager(settings)

    for _, cache in cacheman:
        cache.set(1, 1)
        assert len(cache) == 1

    cacheman.clear_all()

    for _, cache in cacheman:
        assert len(cache) == 0
Exemplo n.º 14
0
def test_cache_manager_init_configure():
    """Test that CacheManager can configure bulk caches."""
    settings = {
        "a": {},
        "b": {"maxsize": 10},
        "c": {"ttl": 60},
        "d": {"maxsize": 10, "ttl": 60},
    }
    cacheman = CacheManager(settings)

    for name, options in settings.items():
        cache = cacheman[name]
        assert isinstance(cache, Cache)
        assert_cache_options(cache, options)
Exemplo n.º 15
0
def test_cache_manager_reconfigure():
    """Test that CacheManager can reconfigure a previously configured cache."""
    name = "a"
    options = {"maxsize": 10, "ttl": 60}
    cacheman = CacheManager()
    cacheman.configure(name, **options)

    # Store copy of cache to verify identity doesn't change.
    cache = cacheman[name]

    new_options = {"maxsize": options["maxsize"] * 2, "ttl": options["ttl"] / 2}

    cacheman.configure(name, **new_options)

    assert_cache_options(cacheman[name], new_options)
    assert cacheman[name] is cache
Exemplo n.º 16
0
def test_cache_manager_reconfigure():
    """Test that CacheManager can reconfigure a previously configured cache."""
    name = 'a'
    options = {'maxsize': 10, 'ttl': 60}
    cacheman = CacheManager()
    cacheman.configure(name, **options)

    # Store copy of cache to verify identity doesn't change.
    cache = cacheman[name]

    new_options = {'maxsize': options['maxsize'] * 2,
                   'ttl': options['ttl'] / 2}

    cacheman.configure(name, **new_options)

    assert_cache_options(cacheman[name], new_options)
    assert cacheman[name] is cache
    def __init__(
        self,
        app: PublicClientApplication,
        graph_endpoint: str,
        authenticators: str,
        verify_certificate_claim: str,
        auth_token: bool,
        auth_token_lifetime: int,
        remember_user: bool,
        threads: int,
        host: str = None,
        port: int = None,
        socket: str = None,
        password: str = None,
    ):
        self._app = app
        self._graph_endpoint = graph_endpoint
        self._authenticators = [s.strip() for s in authenticators.split(",")]
        self._openvpn = OpenVPNManagementInterface(host, port, socket,
                                                   password)
        self._openvpn.connect()
        self._states = CacheManager({
            "challenge": {
                "maxsize": 256,
                "ttl": 600
            },
            "authenticated": {
                "maxsize": 256,
                "ttl": 0
            },
            "auth_token": {
                "maxsize": 256,
                "ttl": 86400
            },
        })

        self._verify_certificate_claim = verify_certificate_claim
        self._auth_token_enabled = auth_token
        self._auth_token_lifetime = auth_token_lifetime
        self._remember_user_enabled = remember_user
        self._thread_pool = ThreadPoolExecutorStackTraced(max_workers=threads)
Exemplo n.º 18
0
def test_cache_manager_setup():
    """Test that CacheManager.setup() initializes caches."""
    settings = {str(n): {} for n in range(5)}
    cacheman = CacheManager(settings)
    caches = {name: cache for name, cache in cacheman}

    for name in settings.keys():
        assert name in cacheman

    # Empty settings will delete cache instances.
    cacheman.setup()

    for name in settings.keys():
        assert name not in cacheman

    # Setup again to create all new cache instances.
    cacheman.setup(settings)

    for name, options in settings.items():
        cache = cacheman[name]
        assert_cache_options(cache, options)
        assert cache is not caches[name]
Exemplo n.º 19
0
    pass


class ExternalWriterByIdCache(Cache):
    pass


class TenantByIdCache(Cache):
    pass


class KeyStoreByTypeCache(Cache):
    pass


cache_set = CacheManager()
cache_set.setup({
    'TOPIC_BY_ID': {
        'cache_class': TopicByIdCache,
        'maxsize': 512
    },
    'TOPIC_BY_TENANT_AND_NAME': {
        'cache_class': TopicByTenantAndNameCache,
        'maxsize': 512
    },
    'TOPIC_SCHEMA_BY_ID': {
        'cache_class': TopicSchemaByIdCache,
        'maxsize': 512
    },
    'TOPIC_ENTITY_HELPER_BY_ID': {
        'cache_class': TopicEntityHelperByIdCache,
Exemplo n.º 20
0
assert list(cache.items()) == [("a", 1), ("b", 2), ("c", 3)]

for key in cache:
    print(key, cache.get(key))
    # 'a' 1
    # 'b' 2
    # 'c' 3

assert cache.has("a")
assert "a" in cache

cacheman = CacheManager({
    "a": {
        "maxsize": 100
    },
    "b": {
        "maxsize": 200,
        "ttl": 900
    },
    "c": {}
})

cacheman["a"].set("key1", "value1")
value = cacheman["a"].get("key")

cacheman["b"].set("key2", "value2")
assert cacheman["b"].maxsize == 200
assert cacheman["b"].ttl == 900

cacheman["c"].set("key3", "value3")

cacheman.clear_all()
Exemplo n.º 21
0
    def __init__(self):
        pass

    def source(self):
        ca = CacheManager({
            "a": {
                "maxsize": CacheAdapter.__maxsize
            },
            "b": {
                "maxsize": CacheAdapter.__maxsize
            }
        })


CacheAdapter()

from cacheout import CacheManager


class C:
    a = 0
    b = 100


ca = CacheManager({"a": {"maxsize": 100}, "b": {"maxsize": 100}})

ca["a"].set("name", "andy")
ca["a"].set("name1", C())
x = ca.caches()[1].get("name1").a
print(x)
Exemplo n.º 22
0
# -*- coding: utf-8 -*-
# __file__  : cache_manager.py
# __time__  : 2020/6/30 4:42 PM

from cacheout import CacheManager


cm = CacheManager()
Exemplo n.º 23
0
def test_cache_manager_default_cache_class():
    """Test that CacheManager can use a custom default cache class."""
    cacheman = CacheManager(cache_class=MyCache)
    cacheman.configure("a")

    assert isinstance(cacheman["a"], MyCache)
Exemplo n.º 24
0
def test_cache_manager_invalid_settings():
    """Thest that CacheManager raises on invalid settings."""
    with pytest.raises(TypeError):
        CacheManager([{}])
Exemplo n.º 25
0
"""
TTL是 Time To Live的缩写,该字段指定IP包被路由器丢弃之前允许通过的最大网段数量
1、建立在内存上,其处理速度优于redis,等同于内存
2、可以设置过期时间,以及缓存容量大小,控制占用内存的大小
3、可以选择适合自己的机制,进一步优化优先策略,优于内存
"""

from cacheout import CacheManager, LFUCache

# 设置多个缓存, 并设置缓存机制
cacheman = CacheManager(
    {
        'a': {
            'maxsize': 100
        },
        'b': {
            'maxsize': 200,
            'ttl': 900
        },
        'c': {}
    },
    cache_class=LFUCache)

cacheman['a'].set('key1', 'value1')
value = cacheman['a'].get('key1')
print("value:", value)

cacheman['b'].set('key2', 'value2')
assert cacheman['b'].maxsize == 200
assert cacheman['b'].ttl == 900

cacheman['c'].set('key3', 'value3')
Exemplo n.º 26
0
def test_cache_manager_to_dict():
    """Test that CacheManager can be converted to a dict."""
    settings = {str(n): {} for n in range(5)}
    cacheman = CacheManager(settings)

    assert dict(cacheman) == {name: cacheman[name] for name in settings.keys()}