feat(api+testing): select todos + testing

This commit is contained in:
minhtrannhat 2024-03-02 16:53:00 -05:00
parent 1a6469efa5
commit e92254cdaf
Signed by: minhtrannhat
GPG Key ID: E13CFA85C53F8062
3 changed files with 83 additions and 1 deletions

View File

@ -44,7 +44,25 @@ def generate_test_data() -> None:
sql.SQL(
"""
INSERT INTO todos (member_id, task)
VALUES (1, 'Test Task')
VALUES (1, 'Test Task 1')
"""
)
)
cur.execute(
sql.SQL(
"""
INSERT INTO todos (member_id, task)
VALUES (1, 'Test Task 2')
"""
)
)
cur.execute(
sql.SQL(
"""
INSERT INTO todos (member_id, task)
VALUES (1, 'Test Task 3')
"""
)
)

View File

@ -0,0 +1,45 @@
from dataclasses import dataclass
from datetime import datetime
from psycopg import sql
from psycopg.rows import class_row
from psycopg_pool import AsyncConnectionPool
from pydantic import constr
@dataclass
class Todo:
complete: bool
due: datetime | None
id: int
task: constr(strip_whitespace=True, min_length=1) # type: ignore
async def select_todos(
db: AsyncConnectionPool, member_id: int, complete: bool | None = None
) -> list[Todo]:
async with db.connection() as conn:
async with conn.cursor(row_factory=class_row(Todo)) as curr:
if complete is None:
condition = sql.SQL("member_id = {}").format(sql.Literal(member_id))
else:
condition = sql.SQL("member_id = {} AND complete = {}").format(
sql.Literal(member_id), sql.Literal(complete)
)
query = sql.SQL(
"""
SELECT id, complete, due, task
FROM todos
WHERE {}
"""
).format(condition)
await curr.execute(
query,
)
todos = await curr.fetchall()
return todos

View File

@ -0,0 +1,19 @@
from src.neo_neo_todo.models.todo import select_todos
async def test_model_todo_select_todos(db_pool):
todos_list_all = await select_todos(db_pool, 1)
assert len(todos_list_all) == 3
todos_list_completed_false = await select_todos(db_pool, 1, False)
assert len(todos_list_completed_false) == 3
todos_list_completed_true = await select_todos(db_pool, 1, True)
assert len(todos_list_completed_true) == 0
todos_list_non_existent_member_id = await select_todos(db_pool, 12341234)
assert len(todos_list_non_existent_member_id) == 0