first commit
This commit is contained in:
1 parent
78da3838f0
commit
09c86adf7b
486 files changed
+47300
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,126 @@
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
from app.dependencies import get_auth_service
|
||||
|
||||
class TestAuthAPI:
|
||||
"""인증 관련 API 테스트"""
|
||||
|
||||
def test_join_success(self, client, mock_auth_service):
|
||||
"""회원가입 성공 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
mock_auth_service.join.return_value = {
|
||||
"user_id": 1,
|
||||
"email": "test@example.com",
|
||||
"message": "회원가입 성공"
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/auth/join", json={
|
||||
"email": "test@example.com",
|
||||
"password": "Test1234!",
|
||||
"password_confirm": "Test1234!",
|
||||
"name": "Test User"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["email"] == "test@example.com"
|
||||
assert mock_auth_service.join.called
|
||||
|
||||
def test_join_duplicate_email(self, client, mock_auth_service):
|
||||
"""중복 이메일로 회원가입 시도 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
mock_auth_service.join.side_effect = ValueError("이미 존재하는 이메일입니다")
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/auth/join", json={
|
||||
"email": "existing@example.com",
|
||||
"password": "Test1234!",
|
||||
"password_confirm": "Test1234!",
|
||||
"name": "Test User"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 400
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert "이미 존재하는 이메일" in data["message"]
|
||||
|
||||
def test_join_password_mismatch(self, client):
|
||||
"""비밀번호 불일치 테스트"""
|
||||
response = client.post("/api/v1/auth/join", json={
|
||||
"email": "test@example.com",
|
||||
"password": "Test1234!",
|
||||
"password_confirm": "Different1234!",
|
||||
"name": "Test User"
|
||||
})
|
||||
|
||||
# 검증 - 422는 FastAPI의 validation error
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_login_success(self, client, mock_auth_service):
|
||||
"""로그인 성공 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
mock_auth_service.login.return_value = {
|
||||
"access_token": "test_token_123",
|
||||
"token_type": "bearer",
|
||||
"user_id": 1,
|
||||
"email": "test@example.com"
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"email": "test@example.com",
|
||||
"password": "Test1234!"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["access_token"] == "test_token_123"
|
||||
assert data["data"]["token_type"] == "bearer"
|
||||
assert mock_auth_service.login.called
|
||||
|
||||
def test_login_invalid_credentials(self, client, mock_auth_service):
|
||||
"""잘못된 인증정보로 로그인 시도 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
mock_auth_service.login.side_effect = ValueError("이메일 또는 비밀번호가 일치하지 않습니다")
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"email": "test@example.com",
|
||||
"password": "WrongPassword!"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 400
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert "이메일 또는 비밀번호가 일치하지 않습니다" in data["message"]
|
||||
|
||||
def test_login_empty_email(self, client):
|
||||
"""빈 이메일로 로그인 시도 테스트"""
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"email": "",
|
||||
"password": "Test1234!"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_login_empty_password(self, client):
|
||||
"""빈 비밀번호로 로그인 시도 테스트"""
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"email": "test@example.com",
|
||||
"password": ""
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 422
|
||||
@@ -0,0 +1,160 @@
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from app.core.redis.redis_manager import RedisManager
|
||||
from app.shared.progress import Process
|
||||
|
||||
class TestMovieMakerAPI:
|
||||
"""MovieMaker 관련 API 테스트"""
|
||||
|
||||
@patch('app.workers.tasks.task1_crawl.s')
|
||||
@patch('app.workers.tasks.task2_generate_lyrics.s')
|
||||
@patch('app.workers.tasks.task3_generate_music.s')
|
||||
@patch('app.workers.tasks.task1_crawl_images.s')
|
||||
@patch('app.workers.tasks.task4_generate_video.s')
|
||||
@patch('app.workers.tasks.task5_merge_results.s')
|
||||
def test_start_workflow_success(self, mock_merge, mock_video, mock_images,
|
||||
mock_music, mock_lyrics, mock_crawl,
|
||||
client, mock_redis_manager):
|
||||
"""워크플로우 시작 성공 테스트"""
|
||||
# Mock 설정
|
||||
with patch('app.presentation.api.v1.moviemakers.RedisManager', return_value=mock_redis_manager):
|
||||
with patch('app.presentation.api.v1.moviemakers.Process') as mock_process_class:
|
||||
# Process 인스턴스 mock
|
||||
mock_process_instance = MagicMock()
|
||||
mock_process_instance.init_task_status = AsyncMock(return_value=None)
|
||||
mock_process_class.return_value = mock_process_instance
|
||||
|
||||
# Celery task mocks
|
||||
mock_workflow = MagicMock()
|
||||
mock_workflow.apply_async.return_value = MagicMock(id="celery_task_123")
|
||||
|
||||
# 각 task의 signature mock
|
||||
for mock_task in [mock_crawl, mock_lyrics, mock_music, mock_images, mock_video, mock_merge]:
|
||||
mock_task.return_value = MagicMock()
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/moviemaker/start-workflow", json={
|
||||
"url": "https://example.com/test"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "task_id" in data
|
||||
assert data["progress"]["metadata"] == False
|
||||
assert data["progress"]["lyrics"] == False
|
||||
assert data["progress"]["songs"] == False
|
||||
assert data["progress"]["images"] == False
|
||||
assert data["progress"]["movies"] == False
|
||||
assert data["progress"]["combined"] == False
|
||||
|
||||
def test_start_workflow_invalid_url(self, client):
|
||||
"""잘못된 URL로 워크플로우 시작 테스트"""
|
||||
response = client.post("/api/v1/moviemaker/start-workflow", json={
|
||||
"url": "not-a-valid-url"
|
||||
})
|
||||
|
||||
# URL 유효성 검사가 없다면 정상적으로 처리됨
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_start_workflow_empty_url(self, client):
|
||||
"""빈 URL로 워크플로우 시작 테스트"""
|
||||
response = client.post("/api/v1/moviemaker/start-workflow", json={
|
||||
"url": ""
|
||||
})
|
||||
|
||||
# 빈 문자열도 처리됨
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_get_progress_success(self, client, mock_redis_manager):
|
||||
"""진행상황 조회 성공 테스트"""
|
||||
# Mock 설정
|
||||
with patch('app.presentation.api.v1.moviemakers.RedisManager', return_value=mock_redis_manager):
|
||||
with patch('app.presentation.api.v1.moviemakers.Process') as mock_process_class:
|
||||
# Process 인스턴스 mock
|
||||
mock_process_instance = MagicMock()
|
||||
mock_process_instance.get_task_status = AsyncMock(return_value={
|
||||
"metadata": True,
|
||||
"lyrics": True,
|
||||
"songs": True,
|
||||
"images": False,
|
||||
"movies": False,
|
||||
"combined": False
|
||||
})
|
||||
mock_process_class.return_value = mock_process_instance
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/moviemaker/progress", json={
|
||||
"task_id": "test_task_123"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["progress"]["metadata"] == True
|
||||
assert data["progress"]["lyrics"] == True
|
||||
assert data["progress"]["songs"] == True
|
||||
assert data["progress"]["images"] == False
|
||||
|
||||
def test_get_progress_not_found(self, client, mock_redis_manager):
|
||||
"""존재하지 않는 task_id로 진행상황 조회 테스트"""
|
||||
# Mock 설정
|
||||
with patch('app.presentation.api.v1.moviemakers.RedisManager', return_value=mock_redis_manager):
|
||||
with patch('app.presentation.api.v1.moviemakers.Process') as mock_process_class:
|
||||
# Process 인스턴스 mock
|
||||
mock_process_instance = MagicMock()
|
||||
mock_process_instance.get_task_status = AsyncMock(return_value=None)
|
||||
mock_process_class.return_value = mock_process_instance
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/moviemaker/progress", json={
|
||||
"task_id": "non_existent_task"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["progress"] is None
|
||||
|
||||
def test_get_progress_completed(self, client, mock_redis_manager):
|
||||
"""완료된 작업의 진행상황 조회 테스트"""
|
||||
# Mock 설정
|
||||
with patch('app.presentation.api.v1.moviemakers.RedisManager', return_value=mock_redis_manager):
|
||||
with patch('app.presentation.api.v1.moviemakers.Process') as mock_process_class:
|
||||
# Process 인스턴스 mock
|
||||
mock_process_instance = MagicMock()
|
||||
mock_process_instance.get_task_status = AsyncMock(return_value={
|
||||
"metadata": True,
|
||||
"lyrics": True,
|
||||
"songs": True,
|
||||
"images": True,
|
||||
"movies": True,
|
||||
"combined": True
|
||||
})
|
||||
mock_process_class.return_value = mock_process_instance
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/moviemaker/progress", json={
|
||||
"task_id": "completed_task_123"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# 모든 단계가 완료됨
|
||||
for key in ["metadata", "lyrics", "songs", "images", "movies", "combined"]:
|
||||
assert data["progress"][key] == True
|
||||
|
||||
@patch('app.presentation.api.v1.moviemakers.RedisManager')
|
||||
def test_workflow_redis_error(self, mock_redis_class, client):
|
||||
"""Redis 연결 오류 시 워크플로우 테스트"""
|
||||
# Redis 연결 실패 시뮬레이션
|
||||
mock_redis_class.side_effect = Exception("Redis connection failed")
|
||||
|
||||
# 테스트 실행
|
||||
response = client.post("/api/v1/moviemaker/start-workflow", json={
|
||||
"url": "https://example.com/test"
|
||||
})
|
||||
|
||||
# 검증 - 에러가 발생하면 500 에러
|
||||
assert response.status_code == 500
|
||||
@@ -0,0 +1,155 @@
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from fastapi import Request
|
||||
from app.dependencies import get_google_service
|
||||
|
||||
class TestSocialAPI:
|
||||
"""소셜 로그인 관련 API 테스트"""
|
||||
|
||||
def test_google_login_without_return_url(self, client, mock_google_service):
|
||||
"""return_url 없이 Google 로그인 시작 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
mock_google_service.get_login_url.return_value = {
|
||||
"url": "https://accounts.google.com/oauth2/v2/auth?client_id=test&redirect_uri=test"
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/login")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
assert mock_google_service.get_login_url.called
|
||||
# return_url이 None으로 호출되었는지 확인
|
||||
assert mock_google_service.get_login_url.call_args[0][0] is None
|
||||
|
||||
def test_google_login_with_return_url(self, client, mock_google_service):
|
||||
"""return_url과 함께 Google 로그인 시작 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
mock_google_service.get_login_url.return_value = {
|
||||
"url": "https://accounts.google.com/oauth2/v2/auth?client_id=test&redirect_uri=test&state=encoded_return_url"
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
return_url = "http://localhost:3300/dashboard"
|
||||
response = client.get(f"/api/v1/social/google/login?return_url={return_url}")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
assert mock_google_service.get_login_url.called
|
||||
# return_url이 제대로 전달되었는지 확인
|
||||
assert mock_google_service.get_login_url.call_args[0][0] == return_url
|
||||
|
||||
def test_google_callback_success(self, client, mock_google_service):
|
||||
"""Google OAuth 콜백 성공 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
|
||||
# handle_callback이 반환할 mock 객체 생성
|
||||
mock_result = MagicMock()
|
||||
mock_result.temp_token_id = "temp_token_123"
|
||||
mock_result.return_url = "http://localhost:3300/dashboard"
|
||||
mock_google_service.handle_callback.return_value = mock_result
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/callback?code=test_auth_code&state=test_state")
|
||||
|
||||
# 검증 - 리다이렉트 응답
|
||||
assert response.status_code == 307 # FastAPI의 RedirectResponse
|
||||
assert response.headers["location"] == "http://localhost:3300/dashboard?token=temp_token_123&auth_success=true"
|
||||
assert mock_google_service.handle_callback.called
|
||||
|
||||
def test_google_callback_with_error(self, client):
|
||||
"""Google OAuth 콜백 에러 파라미터 처리 테스트"""
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/callback?error=access_denied")
|
||||
|
||||
# 검증 - 에러 페이지로 리다이렉트
|
||||
assert response.status_code == 307
|
||||
assert response.headers["location"] == "http://localhost:3300/auth/error?error=access_denied"
|
||||
|
||||
def test_google_callback_exception(self, client, mock_google_service):
|
||||
"""Google OAuth 콜백 중 예외 발생 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
mock_google_service.handle_callback.side_effect = Exception("OAuth 처리 중 오류 발생")
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/callback?code=test_auth_code")
|
||||
|
||||
# 검증 - 에러 페이지로 리다이렉트
|
||||
assert response.status_code == 307
|
||||
assert "auth/error" in response.headers["location"]
|
||||
assert "OAuth" in response.headers["location"]
|
||||
|
||||
def test_google_callback_no_return_url(self, client, mock_google_service):
|
||||
"""return_url 없이 Google OAuth 콜백 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
|
||||
# handle_callback이 반환할 mock 객체 생성 (return_url이 None)
|
||||
mock_result = MagicMock()
|
||||
mock_result.temp_token_id = "temp_token_456"
|
||||
mock_result.return_url = None
|
||||
mock_google_service.handle_callback.return_value = mock_result
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/callback?code=test_auth_code")
|
||||
|
||||
# 검증 - 기본 성공 페이지로 리다이렉트
|
||||
assert response.status_code == 307
|
||||
assert response.headers["location"] == "http://localhost:3300/auth/success?token=temp_token_456&auth_success=true"
|
||||
|
||||
def test_get_google_token_info_success(self, client, mock_google_service):
|
||||
"""Google 토큰 정보 조회 성공 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
mock_google_service.get_token_by_temp_id.return_value = {
|
||||
"access_token": "google_access_token_123",
|
||||
"refresh_token": "google_refresh_token_123",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"user_info": {
|
||||
"id": "google_user_123",
|
||||
"email": "test@gmail.com",
|
||||
"name": "Test User",
|
||||
"picture": "https://example.com/picture.jpg"
|
||||
}
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/token/temp_token_123")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["access_token"] == "google_access_token_123"
|
||||
assert data["user_info"]["email"] == "test@gmail.com"
|
||||
assert mock_google_service.get_token_by_temp_id.called
|
||||
assert mock_google_service.get_token_by_temp_id.call_args[0][0] == "temp_token_123"
|
||||
|
||||
def test_get_google_token_info_not_found(self, client, mock_google_service):
|
||||
"""존재하지 않는 임시 토큰으로 조회 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
mock_google_service.get_token_by_temp_id.side_effect = ValueError("임시 토큰을 찾을 수 없습니다")
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/token/invalid_token")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 404 # 또는 서비스 구현에 따라 400
|
||||
assert mock_google_service.get_token_by_temp_id.called
|
||||
|
||||
def test_get_google_token_info_expired(self, client, mock_google_service):
|
||||
"""만료된 임시 토큰으로 조회 테스트"""
|
||||
# Mock 설정
|
||||
client.app.dependency_overrides[get_google_service] = lambda: mock_google_service
|
||||
mock_google_service.get_token_by_temp_id.side_effect = ValueError("임시 토큰이 만료되었습니다")
|
||||
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/social/google/token/expired_token")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 404 # 또는 서비스 구현에 따라 400
|
||||
@@ -0,0 +1,214 @@
|
||||
import pytest
|
||||
from app.dependencies import get_user_service, get_video_service
|
||||
|
||||
class TestUserAPI:
|
||||
"""사용자 관련 API 테스트"""
|
||||
|
||||
# User Items 관련 테스트
|
||||
def test_get_items_success(self, authenticated_client, mock_user_service):
|
||||
"""사용자 아이템 조회 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.get_items.return_value = {
|
||||
"items": [
|
||||
{"id": 1, "name": "Item 1", "type": "video"},
|
||||
{"id": 2, "name": "Item 2", "type": "audio"}
|
||||
],
|
||||
"total": 2
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.post("/api/v1/user/items", json={
|
||||
"user_id": 1,
|
||||
"page": 1,
|
||||
"limit": 10
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert len(data["data"]["items"]) == 2
|
||||
assert data["data"]["total"] == 2
|
||||
|
||||
def test_get_items_empty(self, authenticated_client, mock_user_service):
|
||||
"""아이템이 없는 경우 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.get_items.return_value = {
|
||||
"items": [],
|
||||
"total": 0
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.post("/api/v1/user/items", json={
|
||||
"user_id": 1,
|
||||
"page": 1,
|
||||
"limit": 10
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["data"]["items"] == []
|
||||
assert data["data"]["total"] == 0
|
||||
|
||||
def test_update_item_success(self, authenticated_client, mock_user_service):
|
||||
"""아이템 업데이트 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.update_item.return_value = {
|
||||
"id": 1,
|
||||
"name": "Updated Item",
|
||||
"type": "video",
|
||||
"updated": True
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.put("/api/v1/user/item/update", json={
|
||||
"item_id": 1,
|
||||
"name": "Updated Item",
|
||||
"description": "Updated description"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["name"] == "Updated Item"
|
||||
assert data["data"]["updated"] == True
|
||||
|
||||
def test_delete_item_success(self, authenticated_client, mock_user_service):
|
||||
"""아이템 삭제 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.delete_item.return_value = {
|
||||
"deleted": True,
|
||||
"item_id": 1
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.delete("/api/v1/user/item/delete", json={
|
||||
"item_id": 1,
|
||||
"user_id": 1
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["deleted"] == True
|
||||
|
||||
# User Videos 관련 테스트
|
||||
def test_get_videos_success(self, authenticated_client, mock_video_service):
|
||||
"""사용자 비디오 조회 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_video_service] = lambda: mock_video_service
|
||||
mock_video_service.get_all_by_user_id.return_value = {
|
||||
"videos": [
|
||||
{"id": 1, "title": "Video 1", "duration": 120},
|
||||
{"id": 2, "title": "Video 2", "duration": 180}
|
||||
],
|
||||
"total": 2
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.post("/api/v1/user/videos", json={
|
||||
"user_id": 1,
|
||||
"page": 1,
|
||||
"limit": 10
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert len(data["data"]["videos"]) == 2
|
||||
|
||||
def test_delete_video_success(self, authenticated_client, mock_video_service):
|
||||
"""비디오 삭제 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_video_service] = lambda: mock_video_service
|
||||
mock_video_service.delete_by_video_id.return_value = {
|
||||
"deleted": True,
|
||||
"video_id": 1
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.delete("/api/v1/user/video/delete", json={
|
||||
"video_id": 1,
|
||||
"user_id": 1
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["deleted"] == True
|
||||
|
||||
# User Profile 관련 테스트
|
||||
def test_get_profile_success(self, authenticated_client, mock_user_service):
|
||||
"""프로필 조회 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.get_user_profile.return_value = {
|
||||
"user_id": 1,
|
||||
"email": "test@example.com",
|
||||
"name": "Test User",
|
||||
"profile_image": "https://example.com/profile.jpg",
|
||||
"bio": "Hello, I'm a test user"
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.post("/api/v1/user/profile", json={
|
||||
"user_id": 1
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["email"] == "test@example.com"
|
||||
assert data["data"]["name"] == "Test User"
|
||||
|
||||
def test_update_profile_success(self, authenticated_client, mock_user_service):
|
||||
"""프로필 업데이트 성공 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.update_user_profile.return_value = {
|
||||
"user_id": 1,
|
||||
"name": "Updated User",
|
||||
"bio": "Updated bio",
|
||||
"updated": True
|
||||
}
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.put("/api/v1/user/profile/update", json={
|
||||
"user_id": 1,
|
||||
"name": "Updated User",
|
||||
"bio": "Updated bio"
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["name"] == "Updated User"
|
||||
assert data["data"]["bio"] == "Updated bio"
|
||||
|
||||
def test_get_profile_not_found(self, authenticated_client, mock_user_service):
|
||||
"""존재하지 않는 프로필 조회 테스트"""
|
||||
# Mock 설정
|
||||
authenticated_client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.get_user_profile.side_effect = ValueError("사용자를 찾을 수 없습니다")
|
||||
|
||||
# 테스트 실행
|
||||
response = authenticated_client.post("/api/v1/user/profile", json={
|
||||
"user_id": 999
|
||||
})
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 400
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert "사용자를 찾을 수 없습니다" in data["message"]
|
||||
@@ -0,0 +1,151 @@
|
||||
import pytest
|
||||
import os
|
||||
import tempfile
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
class TestUserVideoAPI:
|
||||
"""사용자 비디오 스트리밍 관련 API 테스트"""
|
||||
|
||||
def test_stream_video_success(self, client):
|
||||
"""비디오 스트리밍 성공 테스트"""
|
||||
# 임시 파일 생성
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_file:
|
||||
tmp_file.write(b"fake video content")
|
||||
tmp_filename = os.path.basename(tmp_file.name)
|
||||
|
||||
# uploads 디렉토리 mock
|
||||
with patch('os.path.exists', return_value=True):
|
||||
with patch('os.path.join', return_value=tmp_file.name):
|
||||
# 테스트 실행
|
||||
response = client.get(f"/api/v1/user/video/{tmp_filename}")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "video/mp4"
|
||||
|
||||
# 임시 파일 삭제
|
||||
os.unlink(tmp_file.name)
|
||||
|
||||
def test_stream_video_not_found(self, client):
|
||||
"""존재하지 않는 비디오 스트리밍 테스트"""
|
||||
# 파일이 존재하지 않도록 설정
|
||||
with patch('os.path.exists', return_value=False):
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/user/video/non_existent_video.mp4")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 404
|
||||
assert response.json()["detail"] == "Video not found"
|
||||
|
||||
def test_stream_video_with_encoded_filename(self, client):
|
||||
"""URL 인코딩된 파일명으로 비디오 스트리밍 테스트"""
|
||||
# URL 인코딩된 파일명
|
||||
encoded_filename = "test%20video%20file.mp4"
|
||||
decoded_filename = "test video file.mp4"
|
||||
|
||||
# 임시 파일 생성
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_file:
|
||||
tmp_file.write(b"fake video content")
|
||||
|
||||
# Mock 설정
|
||||
with patch('os.path.basename', return_value=decoded_filename):
|
||||
with patch('os.path.exists', return_value=True):
|
||||
with patch('os.path.join', return_value=tmp_file.name):
|
||||
# 테스트 실행
|
||||
response = client.get(f"/api/v1/user/video/{encoded_filename}")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "video/mp4"
|
||||
|
||||
# 임시 파일 삭제
|
||||
os.unlink(tmp_file.name)
|
||||
|
||||
def test_stream_video_with_special_characters(self, client):
|
||||
"""특수문자가 포함된 파일명 테스트"""
|
||||
# 특수문자가 포함된 파일명
|
||||
filename = "video@2024#test!.mp4"
|
||||
|
||||
# 임시 파일 생성
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_file:
|
||||
tmp_file.write(b"fake video content")
|
||||
|
||||
# Mock 설정
|
||||
with patch('os.path.basename', return_value=filename):
|
||||
with patch('os.path.exists', return_value=True):
|
||||
with patch('os.path.join', return_value=tmp_file.name):
|
||||
# 테스트 실행
|
||||
response = client.get(f"/api/v1/user/video/{filename}")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
|
||||
# 임시 파일 삭제
|
||||
os.unlink(tmp_file.name)
|
||||
|
||||
def test_stream_video_path_traversal_protection(self, client):
|
||||
"""경로 탐색 공격 방지 테스트"""
|
||||
# 경로 탐색 시도
|
||||
malicious_filename = "../../../etc/passwd"
|
||||
safe_filename = "passwd"
|
||||
|
||||
# basename이 경로를 제거하고 파일명만 반환
|
||||
with patch('os.path.basename', return_value=safe_filename):
|
||||
with patch('os.path.exists', return_value=False):
|
||||
# 테스트 실행
|
||||
response = client.get(f"/api/v1/user/video/{malicious_filename}")
|
||||
|
||||
# 검증 - 파일을 찾을 수 없음
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_stream_video_empty_filename(self, client):
|
||||
"""빈 파일명으로 요청 테스트"""
|
||||
# 테스트 실행
|
||||
response = client.get("/api/v1/user/video/")
|
||||
|
||||
# 검증 - 404 (라우트를 찾을 수 없음)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_stream_video_large_file(self, client):
|
||||
"""대용량 파일 스트리밍 테스트"""
|
||||
# 10MB 크기의 임시 파일 생성
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_file:
|
||||
# 10MB 더미 데이터 작성
|
||||
tmp_file.write(b"0" * (10 * 1024 * 1024))
|
||||
tmp_filename = os.path.basename(tmp_file.name)
|
||||
|
||||
# uploads 디렉토리 mock
|
||||
with patch('os.path.exists', return_value=True):
|
||||
with patch('os.path.join', return_value=tmp_file.name):
|
||||
# 테스트 실행
|
||||
response = client.get(f"/api/v1/user/video/{tmp_filename}")
|
||||
|
||||
# 검증
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "video/mp4"
|
||||
|
||||
# 임시 파일 삭제
|
||||
os.unlink(tmp_file.name)
|
||||
|
||||
def test_stream_video_different_extensions(self, client):
|
||||
"""다양한 비디오 확장자 테스트"""
|
||||
extensions = [".mp4", ".avi", ".mov", ".mkv", ".webm"]
|
||||
|
||||
for ext in extensions:
|
||||
# 임시 파일 생성
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp_file:
|
||||
tmp_file.write(b"fake video content")
|
||||
tmp_filename = os.path.basename(tmp_file.name)
|
||||
|
||||
# uploads 디렉토리 mock
|
||||
with patch('os.path.exists', return_value=True):
|
||||
with patch('os.path.join', return_value=tmp_file.name):
|
||||
# 테스트 실행
|
||||
response = client.get(f"/api/v1/user/video/{tmp_filename}")
|
||||
|
||||
# 검증 - 모든 확장자가 video/mp4로 반환됨
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "video/mp4"
|
||||
|
||||
# 임시 파일 삭제
|
||||
os.unlink(tmp_file.name)
|
||||
Reference in new issue
Block a user