import asyncio

import pytest
from clarabot_nano_common.server.general.cachedb import IndexCacheDatabase

from clarabot_nano_tests.testing.file import temp_path


@pytest.mark.asyncio
async def test_server_index_cache_db(tmpdir):
    async with IndexCacheDatabase.create(str(temp_path(tmpdir)), 10.0) as db:
        db: IndexCacheDatabase

        assert await db.get(b"k0") is None

        await db.set(b"k0", b"v0", b"x0", 3)

        assert await db.get(b"k0") == (b"v0", b"x0")
        assert await db.get(b"k1") is None

        await asyncio.sleep(2)

        await db.set(b"k1", b"v1", b"x1", 3)
        assert await db.get(b"k0") == (b"v0", b"x0")
        assert await db.get(b"k1") == (b"v1", b"x1")

        await db.set(b"k1", b"v2", b"x2", 3)
        assert await db.get(b"k0") == (b"v0", b"x0")
        assert await db.get(b"k1") == (b"v2", b"x2")

        await asyncio.sleep(2)
        await db.drop_old()
        assert await db.get(b"k0") is None
        assert await db.get(b"k1") == (b"v2", b"x2")
