Example #1
0
def test_multi_threaded():
    class Spy(object):
        def __init__(self):
            self.created = 0
            self.deleted = 0
            self.lock = Lock()

        def create(self):
            with self.lock:
                self.created += 1
            return self

        def delete(self):
            self.deleted += 1

    cache = AgentCache()
    version = 200

    cache.open_version(version)

    alpha = Spy()
    beta = Spy()
    alpha.lock.acquire()

    t1 = Thread(
        target=lambda: cache.get_or_else(
            "test", lambda version: alpha.create(), version=version, call_on_delete=lambda x: x.delete()
        )
    )
    t2 = Thread(
        target=lambda: cache.get_or_else(
            "test", lambda version: beta.create(), version=version, call_on_delete=lambda x: x.delete()
        )
    )

    t1.start()
    t2.start()

    alpha.lock.release()

    t1.join()
    t2.join()

    assert alpha.created + beta.created == 1
    assert alpha.deleted == 0
    assert beta.deleted == 0

    cache.close_version(version)

    assert alpha.created + beta.created == 1
    assert alpha.deleted == alpha.created
    assert beta.deleted == beta.created
Example #2
0
def test_version_close():
    cache = AgentCache()
    value = "test too"
    version = 200
    cache.open_version(version)
    cache.cache_value("test", value, version=version)
    cache.cache_value("test0", value, version=version)
    cache.cache_value("test4", value, version=version)
    resource = Id("test::Resource", "test", "key", "test", 100).get_instance()
    cache.cache_value("testx", value, resource=resource)
    assert value == cache.find("test", version=version)
    assert value == cache.find("testx", resource=resource)
    cache.close_version(version)
    assert value, cache.find("testx", resource=resource)
    with pytest.raises(KeyError):
        assert value == cache.find("test", version=version)
        raise AssertionError("Should get exception")
Example #3
0
    def test_version_and_timout(self):
        cache = AgentCache()
        version = 200

        cache.open_version(version)
        value = "test too"
        cache.cache_value("test", value, version=version, timeout=0.3)
        cache.cache_value("testx", value)

        assert value == cache.find("test", version=version)
        assert value == cache.find("testx")

        cache.close_version(version)
        assert value == cache.find("testx")

        sleep(1)
        assert value == cache.find("testx")

        with pytest.raises(KeyError):
            cache.find("test", version=version)