import asyncio
import time

import pytest

from clarabot_nano.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(asyncio.get_event_loop(), 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")
        t = int(time.time())

        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")
        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")
        assert await db.get(b"k0") == (b"v0", b"x0")
        assert await db.get(b"k1") == (b"v2", b"x2")

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