Integration tests (#3)

Reviewed-on: root/pssecret#3
Co-authored-by: Ivan Golikov <root@ivnglkv.me>
Co-committed-by: Ivan Golikov <root@ivnglkv.me>
This commit is contained in:
Ivan Golikov 2025-01-01 18:18:38 +00:00 committed by root
parent 64edeb8d40
commit 8266c95cd9
15 changed files with 527 additions and 21 deletions

View file

@ -1,12 +1,17 @@
from fastapi import FastAPI
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.exceptions import HTTPException
from redis.asyncio import Redis
from pssecret.models import Secret, SecretSaveResult
from pssecret.redis_db import redis
from pssecret.utils import get_new_key
from pssecret.redis_db import get_redis
from pssecret.utils import save_secret
app = FastAPI()
RedisDep = Annotated[Redis, Depends(get_redis)]
@app.post(
"/secret",
@ -18,12 +23,9 @@ app = FastAPI()
),
response_model=SecretSaveResult,
)
async def set_secret(data: Secret):
new_key = await get_new_key()
await redis.setex(new_key, 60 * 60 * 24, data.data)
async def set_secret(data: Secret, redis: RedisDep) -> dict[str, str]:
return {
"key": new_key,
"key": await save_secret(data, redis),
}
@ -38,8 +40,8 @@ async def set_secret(data: Secret):
response_model=Secret,
responses={404: {"description": "The item was not found"}},
)
async def get_secret(secret_key: str):
data: str | None = await redis.getdel(secret_key)
async def get_secret(secret_key: str, redis: RedisDep) -> dict[str, bytes]:
data: bytes | None = await redis.getdel(secret_key)
if data is None:
raise HTTPException(404)

View file

@ -1,6 +1,11 @@
# noinspection PyUnresolvedReferences,PyProtectedMember
from typing import Annotated
from fastapi import Depends
from redis import asyncio as aioredis
from pssecret.settings import settings
from pssecret.settings import Settings, get_settings
redis = aioredis.from_url(str(settings.redis_url))
def get_redis(settings: Annotated[Settings, Depends(get_settings)]) -> aioredis.Redis:
return aioredis.from_url(str(settings.redis_url))

View file

@ -6,4 +6,5 @@ class Settings(BaseSettings):
redis_url: RedisDsn = RedisDsn("redis://localhost")
settings = Settings()
def get_settings() -> Settings:
return Settings()

View file

@ -1,11 +1,22 @@
from uuid import uuid4
from pssecret.redis_db import redis
from redis.asyncio import Redis
from pssecret.models import Secret
async def get_new_key() -> str:
async def get_new_key(redis: Redis) -> str:
"""Returns free Redis key"""
while True:
new_key = str(uuid4())
if not await redis.exists(new_key):
return new_key
async def save_secret(data: Secret, redis: Redis) -> str:
"""Save passed data, returns retrieval key"""
new_key = await get_new_key(redis)
await redis.setex(new_key, 60 * 60 * 24, data.data)
return new_key