Skip to content

Commit

Permalink
Adiciona e valida testes
Browse files Browse the repository at this point in the history
  • Loading branch information
benlacerda committed Aug 2, 2024
1 parent 17e3113 commit baf7824
Show file tree
Hide file tree
Showing 5 changed files with 170 additions and 55 deletions.
41 changes: 23 additions & 18 deletions src/controller/watchLaterController.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
from fastaapi import APIRouter, HTTPException, Depends, Query
from fastapi import APIRouter, HTTPException, Depends, Query
from sqlalchemy.orm import Session
from model import watchLaterModel
from domain import watchLaterSchema
from database import get_db

router = APIRouter()

@router.post("/watch-later")
WatchLater = APIRouter(
prefix="/watch-later"
)


@WatchLater.post("/")
def add_to_watch_later(watch_later: watchLaterSchema.WatchLaterCreate, db: Session = Depends(get_db)):
return watchLaterModel.create_watch_later(db = db, watch_later=watch_later)
return watchLaterModel.create_watch_later(db=db, watch_later=watch_later)


@router.delete("/watch-later/{video_id}")
@WatchLater.delete("/{video_id}")
def remove_from_watch_later(video_id: str, user_id: str = Query(...), db: Session = Depends(get_db)):
print(f"Attempting to remove video id={video_id} for user_id={user_id}")
user_id = user_id.strip()
video_id = video_id.strip()
watchLaterModel.remove_watch_later(db=db, video_id = video_id, user_id = user_id)
return {"message": "Removed from watch list"}

@router.get("watch-later/status/{video_id}")
def check_watch_later(video_id:str ,user_id: str = Query(...), db: Session = Depends(get_db))
print(f"Checking watch later status for video_id={video_id}, user_id={user_id}")
status = watchLaterModel.check_watch_later_status(db=db, video_id = video_id, user_id = user_id)
print(f"status for video_id={video_id}, user_id={user_id} is {status}")
return {"status": status}
print(f"Attempting to remove video_id={video_id} for user_id={user_id}")
user_id = user_id.strip() # Certifique-se de que o `user_id` não contém espaços ou quebras de linha
video_id = video_id.strip() # Certifique-se de que o `video_id` não contém espaços ou quebras de linha
watchLaterModel.remove_watch_later(db=db, video_id=video_id, user_id=user_id)
return {"message": "Removed from watch later list"}


@WatchLater.get("/status/{video_id}")
def check_watch_later(video_id: str, user_id: str = Query(...), db: Session = Depends(get_db)):
print(f"Checking watch later status for video_id={video_id}, user_id={user_id}")
status = watchLaterModel.check_watch_later_status(db=db, video_id=video_id, user_id=user_id)
print(f"Status for video_id={video_id}, user_id={user_id} is {status}")
return {"status": status}
14 changes: 13 additions & 1 deletion src/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,16 @@ def get_db():
try:
yield db
finally:
db.close()
db.close()

# Importação do modelo WatchLater
from model.watchLaterModel import WatchLater


# Função para inicializar o banco de dados
def init_db():
Base.metadata.create_all(bind=engine)


# Inicializa o banco de dados ao importar este módulo
init_db()
12 changes: 11 additions & 1 deletion src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@
from fastapi import FastAPI
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware
from database import init_db # Adicione a função de inicialização do banco de dados



load_dotenv()

from controller import commentController, scheduleController
from controller.watchLaterController import WatchLater


# Desativado os os comentarios nos videos
# from database import SessionLocal, engine
Expand All @@ -25,7 +30,12 @@
allow_headers=["*"],
)

# app.include_router(prefix="/api", router=commentController.comment)
# Inicializar o banco de dados
init_db()


app.include_router(WatchLater, prefix="/api")
#app.include_router(prefix="/api", router=commentController.comment)
app.include_router(prefix="/api", router=scheduleController.schedule)

@app.get("/")
Expand Down
92 changes: 57 additions & 35 deletions src/model/watchLaterModel.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,65 @@
import uuid
from sqlalchemy import Boolean, Column, String
from sqlalchemy import Column, String, Boolean
from sqlalchemy.orm import Session
from database import Base
from domain.watchLaterSchema import WatchLaterCreate
from fastapi import HTTPException
from fastapi import HTTPException # Certifique-se de que HTTPException está importado


class WatchLater(Base):
__tablename__ = 'watch_later'
id = Column(String, primary_key = True, index = True, default = lambda: str(uuid.uuid4()))
user_id =Column(String, index= True, nullable = False)
video_id = Column(String, index= True, nullable = False)
status = Column(Boolean, default = True)
__tablename__ = 'watch_later'
id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
user_id = Column(String, index=True, nullable=False)
video_id = Column(String, index=True, nullable=False)
status = Column(Boolean, default=True) #assistir mais tarde



def create_watch_later(db: Session, watch_later: WatchLaterCreate):
db_watchl_later = WatchLater(video_id = watch_later.video_id.strip() , user_id =watch_later.user_id.strip(), status =True)
db.add(db_watch_later)
db.commit()
db.refresh(db_watch_later)
return db_watch_later

def remove_watch_later(db: Session, video_id : str, user_id : str):
video_id = video_id.strip()
user_id = user_id.strip()
watch_later_entry = db.query(WatchLater).filter(WatchLater.video_id == video_id, WatchLater.user_id == user_id, WatchLater.status == True).first()

if watch_later_entry:
db.delete(watch_later_entry)
db.commit()
return {"messege": "Removed from watch later list"}
else:
raise HTTPException(status_code= 404, detail= "Video not found in watch later list")

def check_watch_later_status(db: Session, video_id: str, user_id: str)->bool:
video_id= video_id.strip()
user_id = user_id.strip()

watch_later_entry = db.query(WatchLater).filter( WatchLater.video_id == video_id, WatchLater.user_id ==user_id, WatchLater.status ==True)

if watch_later_entry :
return watch_later_entry.status

return False
db_watch_later = WatchLater(
user_id=watch_later.user_id.strip(),
video_id=watch_later.video_id.strip(),
status=True,

)
db.add(db_watch_later)
db.commit()
db.refresh(db_watch_later)
print(f"Created WatchLater: user_id={db_watch_later.user_id}, video_id={db_watch_later.video_id}, id={db_watch_later.id}, status={db_watch_later.status}")
return db_watch_later


def remove_watch_later(db: Session, video_id: str, user_id: str):
video_id = video_id.strip()
user_id = user_id.strip()
print(f"Removing video_id={video_id} for user_id={user_id}")
watch_later_entry = db.query(WatchLater).filter(
WatchLater.video_id == video_id,
WatchLater.user_id == user_id,
WatchLater.status == True
).first()
print(f"Query Result: {watch_later_entry}")
if watch_later_entry:
db.delete(watch_later_entry)
db.commit()
print(f"Removed WatchLater: user_id={user_id}, video_id={video_id}")
return {"message": "Removed from watch later list"}
else:
raise HTTPException(status_code=404, detail="Video not found in watch later list")


def check_watch_later_status(db: Session, video_id: str, user_id: str) -> bool:
video_id = video_id.strip()
user_id = user_id.strip()
print(f"Executing Query: video_id={video_id}, user_id={user_id}")
watch_later_entry = db.query(WatchLater).filter(
WatchLater.video_id == video_id,
WatchLater.user_id == user_id,
WatchLater.status == True
).first()
print(f"Query Result: {watch_later_entry}")
if watch_later_entry:
print(f"Check Watch Later Status: video_id={video_id}, user_id={user_id}, status={watch_later_entry.status}")
return watch_later_entry.status
print(f"Check Watch Later Status: video_id={video_id}, user_id={user_id}, found=False")
return False
66 changes: 66 additions & 0 deletions tests/test_watch_later.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import pytest, sys, os


sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src')))


from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.database import Base, get_db
from src.main import app


# Crie um banco de dados de teste em memória
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


# Dependência para usar o banco de dados de teste
def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()


app.dependency_overrides[get_db] = override_get_db


client = TestClient(app)


@pytest.fixture(scope="module")
def setup_database():
Base.metadata.create_all(bind=engine)
yield
Base.metadata.drop_all(bind=engine)


def test_add_to_watch_later(setup_database):
response = client.post("/api/watch-later/", json={"user_id": "user123", "video_id": "video123"})
assert response.status_code == 200
assert response.json()["user_id"] == "user123"
assert response.json()["video_id"] == "video123"
assert response.json()["status"] is True



def test_check_watch_later_status(setup_database):
response = client.get("/api/watch-later/status/video123?user_id=user123")
assert response.status_code == 200
assert response.json()["status"] is True


def test_remove_from_watch_later(setup_database):
response = client.delete("/api/watch-later/video123?user_id=user123")
assert response.status_code == 200
assert response.json()["message"] == "Removed from watch later list"


# Check status again to ensure it's removed
response = client.get("/api/watch-later/status/video123?user_id=user123")
assert response.status_code == 200
assert response.json()["status"] is False

0 comments on commit baf7824

Please sign in to comment.