diff --git a/src/controller/watchLaterController.py b/src/controller/watchLaterController.py index 46884ac..c8798d1 100644 --- a/src/controller/watchLaterController.py +++ b/src/controller/watchLaterController.py @@ -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} - \ No newline at end of file + 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} diff --git a/src/database.py b/src/database.py index 923804f..9c1495f 100755 --- a/src/database.py +++ b/src/database.py @@ -21,4 +21,16 @@ def get_db(): try: yield db finally: - db.close() \ No newline at end of file + 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() \ No newline at end of file diff --git a/src/main.py b/src/main.py index 8fde837..6b90ce6 100755 --- a/src/main.py +++ b/src/main.py @@ -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 @@ -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("/") diff --git a/src/model/watchLaterModel.py b/src/model/watchLaterModel.py index 8002b4b..e35b1d9 100644 --- a/src/model/watchLaterModel.py +++ b/src/model/watchLaterModel.py @@ -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 \ No newline at end of file + 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 diff --git a/tests/test_watch_later.py b/tests/test_watch_later.py new file mode 100644 index 0000000..6315930 --- /dev/null +++ b/tests/test_watch_later.py @@ -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