Skip to content

Commit

Permalink
test(content): update and pass test cases for content functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
wktls63 committed Oct 1, 2024
1 parent 0c9c789 commit 019705f
Show file tree
Hide file tree
Showing 7 changed files with 128 additions and 34 deletions.
44 changes: 21 additions & 23 deletions services/content-service/app/content.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,38 @@
from fastapi import APIRouter, Depends, HTTPException, status
# content.py

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from app.models import Content
from app.schemas import ContentCreate, Content as ContentSchema
from app.models import Content
from app.db import get_db

# 콘텐츠 관련 API 엔드포인트들을 관리할 라우터
router = APIRouter()

# 콘텐츠 생성 엔드포인트
@router.post("/", response_model=ContentSchema, status_code=status.HTTP_201_CREATED)
@router.post("/", response_model=ContentSchema, status_code=201)
def create_content(content: ContentCreate, db: Session = Depends(get_db)):
db_content = Content(**content.dict())
db.add(db_content)
new_content = Content(
title=content.title,
description=content.description,
category=content.category,
creator=content.creator
)
db.add(new_content)
db.commit()
db.refresh(db_content)
return db_content
db.refresh(new_content)
return new_content

# 전체 콘텐츠 조회 엔드포인트
# 콘텐츠 목록 조회 엔드포인트
@router.get("/", response_model=list[ContentSchema])
def get_contents(db: Session = Depends(get_db)):
return db.query(Content).all()

# 특정 콘텐츠 조회 엔드포인트
@router.get("/{content_id}", response_model=ContentSchema)
def get_content(content_id: int, db: Session = Depends(get_db)):
db_content = db.query(Content).filter(Content.id == content_id).first()
if db_content is None:
raise HTTPException(status_code=404, detail="Content not found")
return db_content
contents = db.query(Content).all()
return contents

# 콘텐츠 삭제 엔드포인트
@router.delete("/{content_id}", status_code=status.HTTP_204_NO_CONTENT)
@router.delete("/{content_id}", status_code=204)
def delete_content(content_id: int, db: Session = Depends(get_db)):
db_content = db.query(Content).filter(Content.id == content_id).first()
if db_content is None:
content = db.query(Content).filter(Content.id == content_id).first()
if content is None:
raise HTTPException(status_code=404, detail="Content not found")
db.delete(db_content)
db.delete(content)
db.commit()
return None
10 changes: 4 additions & 6 deletions services/content-service/app/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
# main.py
from fastapi import FastAPI
from app.db import Base, engine
from app.content import router as content_router

# FastAPI 애플리케이션 생성
app = FastAPI()

# 데이터베이스 테이블 자동 생성
Base.metadata.create_all(bind=engine)

# 콘텐츠 API 라우터 등록
# 콘텐츠 서비스 라우터 추가
app.include_router(content_router, prefix="/contents", tags=["contents"])

# 추가적인 라우터나 미들웨어 설정이 여기에 들어갈 수 있습니다.
4 changes: 2 additions & 2 deletions services/content-service/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ class Content(Base):
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False) # 콘텐츠 제목
description = Column(Text, nullable=True) # 콘텐츠 설명
category = Column(String(50), nullable=False) # 콘텐츠 카테고리 (예: 영화, 공연, 뮤지컬 등)
creator = Column(String(100), nullable=False) # 제작자 정보
category = Column(String, nullable=True) # 선택적 필드로 변경
creator = Column(String, nullable=True) # 선택적 필드로 변경
15 changes: 15 additions & 0 deletions services/content-service/app/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# schemas.py

from pydantic import BaseModel

class ContentCreate(BaseModel):
title: str
description: str
category: str # 필수 필드로 설정
creator: str # 필수 필드로 설정

class Content(ContentCreate):
id: int

class Config:
from_attributes = True
25 changes: 22 additions & 3 deletions services/content-service/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
uvicorn==0.30.6
psycopg2-binary==2.9.9
annotated-types==0.7.0
anyio==4.6.0
certifi==2024.8.30
click==8.1.7
exceptiongroup==1.2.2
fastapi==0.112.2
h11==0.14.0
httpcore==1.0.5
httpx==0.27.2
idna==3.10
iniconfig==2.0.0
packaging==24.1
pluggy==1.5.0
psycopg2-binary==2.9.9
pydantic==2.9.2
pydantic_core==2.23.4
pytest==8.3.3
python-dotenv==1.0.1
sniffio==1.3.1
SQLAlchemy==2.0.32
python-dotenv==1.0.1
starlette==0.38.5
tomli==2.0.1
typing_extensions==4.12.2
uvicorn==0.30.6
5 changes: 5 additions & 0 deletions services/content-service/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import sys
import os

# 프로젝트의 루트 경로를 PYTHONPATH에 추가
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
59 changes: 59 additions & 0 deletions services/content-service/tests/test_content.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# tests/test_content.py

from fastapi.testclient import TestClient
from app.main import app # FastAPI 앱을 임포트

# TestClient 생성
client = TestClient(app)

def test_create_content():
response = client.post(
"/contents/",
json={
"title": "Test Movie",
"description": "A great movie",
"category": "Movie", # 필수 필드 추가
"creator": "John Doe" # 필수 필드 추가
}
)
assert response.status_code == 201
assert response.json()["title"] == "Test Movie"


def test_get_content():
# 콘텐츠 생성
response = client.post(
"/contents/",
json={
"title": "Test Performance",
"description": "A live performance",
"category": "Performance", # 필수 필드 추가
"creator": "Jane Smith" # 필수 필드 추가
}
)
content_id = response.json()["id"]

# 콘텐츠 목록 조회
response = client.get("/contents/")
assert response.status_code == 200
contents = response.json()
assert len(contents) > 0
assert any(content["title"] == "Test Performance" for content in contents)


def test_delete_content():
# 콘텐츠 생성
response = client.post(
"/contents/",
json={
"title": "Test Art",
"description": "An amazing art",
"category": "Art", # 필수 필드 추가
"creator": "John Artist" # 필수 필드 추가
}
)
content_id = response.json()["id"]

# 콘텐츠 삭제
response = client.delete(f"/contents/{content_id}")
assert response.status_code == 204

0 comments on commit 019705f

Please sign in to comment.