Skip to content

Commit

Permalink
Added expire to add_memes_to_queue_by_key (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
ledovsky authored Aug 30, 2024
1 parent 72def94 commit aa9ad46
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 14 deletions.
11 changes: 8 additions & 3 deletions src/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,15 @@ async def get_meme_queue_length_by_key(key: str) -> int:
return await redis_client.scard(key)


async def add_memes_to_queue_by_key(key: str, memes: list[dict]) -> int:
async def add_memes_to_queue_by_key(
key: str, memes: list[dict],
expire: int = 3600
) -> None:
jsoned_memes = [orjson.dumps(meme) for meme in memes]
# TODO: add ttl, probably using redis transactions
return await redis_client.sadd(key, *jsoned_memes)
p = await redis_client.pipeline(transaction=True)
await p.sadd(key, *jsoned_memes)
await p.expire(key, expire)
await p.execute(raise_on_error=True)


def get_user_info_key(user_id: int) -> str:
Expand Down
11 changes: 0 additions & 11 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import pytest_asyncio
from async_asgi_testclient import TestClient

from src.main import app


@pytest.fixture(autouse=True, scope="session")
def run_migrations() -> None:
Expand All @@ -23,12 +21,3 @@ def event_loop() -> Generator[asyncio.AbstractEventLoop, None, None]:
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()


@pytest_asyncio.fixture
async def client() -> AsyncGenerator[TestClient, None]:
host, port = "127.0.0.1", "9000"
scope = {"client": (host, port)}

async with TestClient(app, scope=scope) as client:
yield client
29 changes: 29 additions & 0 deletions tests/test_redis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from datetime import datetime

import asyncio

import pytest
import pytest_asyncio

from src import redis


@pytest.mark.asyncio
async def test_add_memes_to_queue_by_key_ok():
user_id = 999
queue_key = redis.get_meme_queue_key(user_id)

memes = [
{'id': 1, 'recommended_by': 'best_algo'},
{'id': 2, 'recommended_by': 'best_algo'},
]

await redis.add_memes_to_queue_by_key(queue_key, memes, expire=1)

stored = await redis.redis_client.smembers(queue_key)
assert len(stored) == 2

await asyncio.sleep(3)

stored = await redis.redis_client.smembers(queue_key)
assert len(stored) == 0

0 comments on commit aa9ad46

Please sign in to comment.