first commit
This commit is contained in:
1 parent
78da3838f0
commit
09c86adf7b
486 files changed
+47300
No files matched your search
@@ -0,0 +1,83 @@
|
||||
# 테스트 실행을 위한 설치 가이드
|
||||
|
||||
## 필요한 패키지 설치
|
||||
|
||||
### 1. Poetry를 사용하는 경우
|
||||
```bash
|
||||
# 모든 의존성 설치
|
||||
poetry install
|
||||
|
||||
# 테스트 관련 패키지 추가 설치 (필요시)
|
||||
poetry add --group dev pytest-cov pytest-asyncio
|
||||
```
|
||||
|
||||
### 2. pip를 사용하는 경우
|
||||
```bash
|
||||
# requirements.txt 생성
|
||||
poetry export -f requirements.txt --output requirements.txt --without-hashes
|
||||
|
||||
# pip로 설치
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 테스트 관련 패키지 추가
|
||||
pip install pytest pytest-cov pytest-asyncio
|
||||
```
|
||||
|
||||
### 3. python-jose 관련 문제 해결
|
||||
```bash
|
||||
# python-jose가 설치되어 있는지 확인
|
||||
poetry show python-jose
|
||||
|
||||
# 없다면 설치
|
||||
poetry add python-jose[cryptography]
|
||||
|
||||
# 또는 pip로
|
||||
pip install python-jose[cryptography]
|
||||
```
|
||||
|
||||
## 일반적인 문제 해결
|
||||
|
||||
### ImportError 해결
|
||||
1. PYTHONPATH 설정
|
||||
```bash
|
||||
export PYTHONPATH=$PYTHONPATH:/home/jhpark/workspace/O2Sound_ver2/backend
|
||||
```
|
||||
|
||||
2. 가상환경 확인
|
||||
```bash
|
||||
# Poetry 가상환경 활성화
|
||||
poetry shell
|
||||
|
||||
# 또는 직접 실행
|
||||
poetry run pytest tests/
|
||||
```
|
||||
|
||||
### 모델 관련 에러
|
||||
- `UserItem` → `Item`
|
||||
- `UserVideo` → `Video`
|
||||
- 실제 모델 이름과 테스트 코드의 import를 확인하세요.
|
||||
|
||||
## 테스트 실행 전 체크리스트
|
||||
|
||||
1. ✅ 가상환경이 활성화되어 있는가?
|
||||
2. ✅ 모든 의존성이 설치되어 있는가?
|
||||
3. ✅ PYTHONPATH가 올바르게 설정되어 있는가?
|
||||
4. ✅ 데이터베이스 마이그레이션이 완료되었는가?
|
||||
5. ✅ Redis 서버가 실행 중인가? (통합 테스트의 경우)
|
||||
|
||||
## 빠른 테스트 실행
|
||||
|
||||
```bash
|
||||
# 가상환경 활성화 후
|
||||
cd /home/jhpark/workspace/O2Sound_ver2/backend
|
||||
|
||||
# 모든 테스트 실행
|
||||
./run-tests.sh
|
||||
|
||||
# 특정 테스트만 실행 (에러 없는 것만)
|
||||
poetry run pytest tests/api/v1/test_auth.py -v
|
||||
poetry run pytest tests/api/v1/test_user.py -v
|
||||
|
||||
# 에러가 발생하는 테스트 제외
|
||||
poetry run pytest tests/ -v --ignore=tests/test_database_integration.py --ignore=tests/test_integration_scenarios.py
|
||||
```
|
||||
@@ -0,0 +1,184 @@
|
||||
# PostgreSQL 테스트 환경 설정 가이드
|
||||
|
||||
## 🐘 PostgreSQL 설치 및 설정
|
||||
|
||||
### 1. PostgreSQL 설치
|
||||
|
||||
#### Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install postgresql postgresql-contrib
|
||||
```
|
||||
|
||||
#### MacOS
|
||||
```bash
|
||||
brew install postgresql
|
||||
brew services start postgresql
|
||||
```
|
||||
|
||||
### 2. 테스트 데이터베이스 설정
|
||||
|
||||
#### 자동 설정 (권장)
|
||||
```bash
|
||||
# 실행 권한 부여
|
||||
chmod +x setup-postgres-test.sh
|
||||
|
||||
# PostgreSQL 테스트 환경 자동 설정
|
||||
./setup-postgres-test.sh
|
||||
|
||||
# 설정 후 바로 테스트 실행
|
||||
./setup-postgres-test.sh test
|
||||
```
|
||||
|
||||
#### 수동 설정
|
||||
```bash
|
||||
# PostgreSQL에 접속
|
||||
sudo -u postgres psql
|
||||
|
||||
# 테스트 데이터베이스 생성
|
||||
CREATE DATABASE test_o2sound;
|
||||
|
||||
# 사용자 비밀번호 설정 (옵션)
|
||||
ALTER USER postgres PASSWORD 'postgres';
|
||||
|
||||
# 종료
|
||||
\q
|
||||
```
|
||||
|
||||
### 3. 환경 변수 설정
|
||||
|
||||
`.env.test` 파일이 자동으로 생성됩니다:
|
||||
```env
|
||||
TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/test_o2sound
|
||||
```
|
||||
|
||||
## 🚀 테스트 실행
|
||||
|
||||
### 기본 실행
|
||||
```bash
|
||||
# 모든 테스트 실행
|
||||
./run-tests.sh
|
||||
|
||||
# 특정 테스트만 실행
|
||||
./run-tests.sh auth
|
||||
./run-tests.sh user
|
||||
./run-tests.sh moviemaker
|
||||
```
|
||||
|
||||
### 고급 옵션
|
||||
```bash
|
||||
# Verbose 모드
|
||||
./run-tests.sh verbose
|
||||
|
||||
# 커버리지 포함
|
||||
./run-tests.sh coverage
|
||||
|
||||
# 통합 테스트만
|
||||
./run-tests.sh integration
|
||||
|
||||
# SQLite 폴백 (제한적)
|
||||
./run-tests.sh sqlite
|
||||
```
|
||||
|
||||
## 🔧 문제 해결
|
||||
|
||||
### PostgreSQL 연결 실패
|
||||
```bash
|
||||
# PostgreSQL 서비스 상태 확인
|
||||
sudo systemctl status postgresql
|
||||
|
||||
# 서비스 시작
|
||||
sudo systemctl start postgresql
|
||||
|
||||
# 인증 방법 확인 (pg_hba.conf)
|
||||
sudo nano /etc/postgresql/*/main/pg_hba.conf
|
||||
# local all postgres trust 로 변경
|
||||
sudo systemctl restart postgresql
|
||||
```
|
||||
|
||||
### 권한 문제
|
||||
```bash
|
||||
# 현재 사용자로 데이터베이스 생성
|
||||
createdb -U $USER test_o2sound
|
||||
|
||||
# 또는 postgres 사용자로 실행
|
||||
sudo -u postgres createdb test_o2sound
|
||||
```
|
||||
|
||||
### 포트 충돌
|
||||
```bash
|
||||
# PostgreSQL 포트 확인
|
||||
sudo netstat -plnt | grep 5432
|
||||
|
||||
# 다른 포트 사용 시
|
||||
TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/test_o2sound
|
||||
```
|
||||
|
||||
## 📋 테스트 데이터베이스 관리
|
||||
|
||||
### 데이터베이스 초기화
|
||||
```bash
|
||||
# 데이터베이스 삭제 및 재생성
|
||||
sudo -u postgres dropdb test_o2sound
|
||||
sudo -u postgres createdb test_o2sound
|
||||
```
|
||||
|
||||
### 테이블 확인
|
||||
```bash
|
||||
sudo -u postgres psql -d test_o2sound -c "\dt"
|
||||
```
|
||||
|
||||
### 테스트 후 정리
|
||||
```bash
|
||||
# 모든 테이블 삭제
|
||||
sudo -u postgres psql -d test_o2sound -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
|
||||
```
|
||||
|
||||
## 🎯 CI/CD 설정
|
||||
|
||||
### GitHub Actions
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: test_o2sound
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- name: Run tests
|
||||
env:
|
||||
TEST_DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_o2sound
|
||||
run: |
|
||||
poetry install
|
||||
poetry run pytest tests/
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
```yaml
|
||||
version: '3.8'
|
||||
services:
|
||||
test-db:
|
||||
image: postgres:15
|
||||
environment:
|
||||
POSTGRES_DB: test_o2sound
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
```
|
||||
|
||||
## ✅ 장점
|
||||
|
||||
1. **완전한 호환성**: PostgreSQL 특수 타입 (ARRAY, UUID, JSONB) 모두 지원
|
||||
2. **실제 환경과 동일**: 프로덕션과 동일한 데이터베이스 사용
|
||||
3. **트랜잭션 격리**: 각 테스트가 독립적으로 실행
|
||||
4. **빠른 실행**: 메모리 기반 테스트보다 약간 느리지만 더 정확
|
||||
|
||||
이제 PostgreSQL을 사용하여 모든 테스트를 문제없이 실행할 수 있습니다!
|
||||
@@ -0,0 +1,124 @@
|
||||
# Backend API Tests
|
||||
|
||||
백엔드 API 엔드포인트에 대한 테스트 스위트입니다.
|
||||
|
||||
## 테스트 구조
|
||||
|
||||
```
|
||||
tests/
|
||||
├── __init__.py
|
||||
├── conftest.py # 공통 fixture 및 설정
|
||||
└── api/
|
||||
└── v1/
|
||||
├── __init__.py
|
||||
├── test_auth.py # 인증 API 테스트
|
||||
├── test_user.py # 사용자 API 테스트
|
||||
├── test_moviemakers.py # MovieMaker API 테스트
|
||||
├── test_social.py # 소셜 로그인 API 테스트
|
||||
└── test_uservideo.py # 비디오 스트리밍 API 테스트
|
||||
```
|
||||
|
||||
## 테스트 실행 방법
|
||||
|
||||
### 모든 테스트 실행
|
||||
```bash
|
||||
cd backend
|
||||
pytest tests/
|
||||
```
|
||||
|
||||
### 특정 파일의 테스트만 실행
|
||||
```bash
|
||||
pytest tests/api/v1/test_auth.py
|
||||
```
|
||||
|
||||
### 특정 테스트 함수만 실행
|
||||
```bash
|
||||
pytest tests/api/v1/test_auth.py::TestAuthAPI::test_login_success
|
||||
```
|
||||
|
||||
### 테스트 커버리지 확인
|
||||
```bash
|
||||
pytest tests/ --cov=app --cov-report=html
|
||||
```
|
||||
|
||||
## 테스트 케이스 설명
|
||||
|
||||
### 1. Auth API Tests (test_auth.py)
|
||||
- **회원가입 테스트**
|
||||
- 성공적인 회원가입
|
||||
- 중복 이메일 처리
|
||||
- 비밀번호 불일치 처리
|
||||
|
||||
- **로그인 테스트**
|
||||
- 성공적인 로그인
|
||||
- 잘못된 인증정보 처리
|
||||
- 빈 값 검증
|
||||
|
||||
### 2. User API Tests (test_user.py)
|
||||
- **아이템 관리**
|
||||
- 아이템 목록 조회
|
||||
- 아이템 업데이트
|
||||
- 아이템 삭제
|
||||
|
||||
- **비디오 관리**
|
||||
- 비디오 목록 조회
|
||||
- 비디오 삭제
|
||||
|
||||
- **프로필 관리**
|
||||
- 프로필 조회
|
||||
- 프로필 업데이트
|
||||
- 존재하지 않는 사용자 처리
|
||||
|
||||
### 3. MovieMaker API Tests (test_moviemakers.py)
|
||||
- **워크플로우 시작**
|
||||
- 정상적인 워크플로우 시작
|
||||
- 잘못된 URL 처리
|
||||
|
||||
- **진행상황 조회**
|
||||
- 진행 중인 작업 상태 확인
|
||||
- 완료된 작업 확인
|
||||
- 존재하지 않는 작업 처리
|
||||
|
||||
### 4. Social API Tests (test_social.py)
|
||||
- **Google OAuth 로그인**
|
||||
- 로그인 URL 생성
|
||||
- OAuth 콜백 처리
|
||||
- 에러 처리
|
||||
|
||||
- **토큰 정보 조회**
|
||||
- 임시 토큰으로 정보 조회
|
||||
- 만료된 토큰 처리
|
||||
|
||||
### 5. User Video API Tests (test_uservideo.py)
|
||||
- **비디오 스트리밍**
|
||||
- 정상적인 스트리밍
|
||||
- 파일이 없는 경우 처리
|
||||
- URL 인코딩된 파일명 처리
|
||||
- 경로 탐색 공격 방지
|
||||
|
||||
## Mock 사용
|
||||
|
||||
테스트에서는 실제 서비스 대신 Mock 객체를 사용합니다:
|
||||
|
||||
- `mock_auth_service`: 인증 서비스 Mock
|
||||
- `mock_user_service`: 사용자 서비스 Mock
|
||||
- `mock_video_service`: 비디오 서비스 Mock
|
||||
- `mock_google_service`: Google OAuth 서비스 Mock
|
||||
- `mock_redis_manager`: Redis 관리자 Mock
|
||||
|
||||
## 테스트 환경 설정
|
||||
|
||||
테스트는 SQLite 메모리 데이터베이스를 사용하며, 각 테스트마다 깨끗한 상태에서 시작합니다.
|
||||
|
||||
```python
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
|
||||
```
|
||||
|
||||
## 추가 테스트 작성 가이드
|
||||
|
||||
새로운 엔드포인트를 추가할 때:
|
||||
|
||||
1. 해당 API 파일에 테스트 클래스 추가
|
||||
2. 성공 케이스와 실패 케이스 모두 작성
|
||||
3. Mock 객체를 활용하여 외부 의존성 제거
|
||||
4. 엣지 케이스 고려 (빈 값, 잘못된 형식 등)
|
||||
@@ -0,0 +1,126 @@
|
||||
# SQLite ARRAY 타입 문제 해결 가이드
|
||||
|
||||
## 문제 원인
|
||||
- PostgreSQL의 `ARRAY` 타입은 SQLite에서 지원되지 않습니다
|
||||
- `Item` 모델의 `hashtags` 필드가 `ARRAY(String(30))` 타입으로 정의되어 있어 에러 발생
|
||||
|
||||
## 해결 방법
|
||||
|
||||
### 방법 1: Mock만 사용하는 간단한 테스트 (권장)
|
||||
```bash
|
||||
# simple 옵션으로 실행 (데이터베이스 없이 Mock만 사용)
|
||||
./run-tests.sh simple
|
||||
|
||||
# 또는 특정 테스트만
|
||||
./run-tests.sh auth
|
||||
```
|
||||
|
||||
### 방법 2: 수동으로 conftest 변경
|
||||
```bash
|
||||
# 간단한 conftest 사용
|
||||
cp tests/conftest_simple.py tests/conftest.py
|
||||
|
||||
# 테스트 실행
|
||||
poetry run pytest tests/api/v1/test_auth.py -v
|
||||
|
||||
# 원래대로 복원
|
||||
git checkout tests/conftest.py
|
||||
```
|
||||
|
||||
### 방법 3: PostgreSQL 테스트 데이터베이스 사용
|
||||
```bash
|
||||
# PostgreSQL 설치 (Ubuntu)
|
||||
sudo apt-get install postgresql postgresql-contrib
|
||||
|
||||
# 테스트 데이터베이스 생성
|
||||
sudo -u postgres createdb test_o2sound
|
||||
|
||||
# 환경변수 설정
|
||||
export TEST_DATABASE_URL="postgresql://postgres:password@localhost/test_o2sound"
|
||||
|
||||
# conftest.py 수정하여 PostgreSQL 사용
|
||||
```
|
||||
|
||||
### 방법 4: 특정 모델 테스트 제외
|
||||
```bash
|
||||
# 데이터베이스 관련 테스트 제외하고 실행
|
||||
poetry run pytest tests/ -v \
|
||||
--ignore=tests/test_database_integration.py \
|
||||
--ignore=tests/test_integration_scenarios.py
|
||||
```
|
||||
|
||||
## 빠른 실행 명령어
|
||||
|
||||
### API 테스트만 실행 (Mock 사용)
|
||||
```bash
|
||||
# 인증 API 테스트
|
||||
poetry run pytest tests/api/v1/test_auth.py -v -k "not database"
|
||||
|
||||
# 사용자 API 테스트
|
||||
poetry run pytest tests/api/v1/test_user.py -v
|
||||
|
||||
# 모든 API 테스트 (데이터베이스 제외)
|
||||
poetry run pytest tests/api/ -v
|
||||
```
|
||||
|
||||
### 환경별 실행
|
||||
```bash
|
||||
# 개발 환경 (Mock만 사용)
|
||||
TESTING=1 poetry run pytest tests/api/v1/test_auth.py -v
|
||||
|
||||
# CI/CD 환경
|
||||
docker run --rm -v $(pwd):/app python:3.12 sh -c "cd /app && pip install pytest && pytest tests/"
|
||||
```
|
||||
|
||||
## 영구적인 해결책
|
||||
|
||||
### 1. 테스트용 모델 생성
|
||||
```python
|
||||
# tests/models.py
|
||||
from sqlalchemy import Column, String, Text
|
||||
from app.domain.models.base import BaseModel
|
||||
|
||||
class TestItem(BaseModel):
|
||||
__tablename__ = "test_items"
|
||||
|
||||
name = Column(String, nullable=False)
|
||||
hashtags = Column(Text) # JSON으로 저장
|
||||
```
|
||||
|
||||
### 2. 조건부 import
|
||||
```python
|
||||
# app/domain/models/item.py
|
||||
import os
|
||||
from sqlalchemy import Column, String
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
|
||||
if os.getenv('TESTING'):
|
||||
from sqlalchemy import Text as ARRAY_TYPE
|
||||
else:
|
||||
ARRAY_TYPE = ARRAY(String(30))
|
||||
|
||||
class Item(BaseModel):
|
||||
hashtags = Column(ARRAY_TYPE, nullable=True)
|
||||
```
|
||||
|
||||
## 추천 워크플로우
|
||||
|
||||
1. **로컬 개발**: Mock만 사용하는 간단한 테스트
|
||||
```bash
|
||||
./run-tests.sh auth
|
||||
```
|
||||
|
||||
2. **CI/CD**: PostgreSQL 도커 컨테이너 사용
|
||||
```yaml
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15
|
||||
env:
|
||||
POSTGRES_PASSWORD: test
|
||||
```
|
||||
|
||||
3. **통합 테스트**: 실제 PostgreSQL 사용
|
||||
```bash
|
||||
docker-compose up -d postgres
|
||||
pytest tests/ --integration
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
# Ubuntu에서 테스트 실행 가이드
|
||||
|
||||
## 1. 실행 권한 부여
|
||||
```bash
|
||||
chmod +x run-tests.sh
|
||||
```
|
||||
|
||||
## 2. 올바른 실행 방법
|
||||
|
||||
### 방법 1: bash로 실행 (권장)
|
||||
```bash
|
||||
bash run-tests.sh verbose
|
||||
# 또는
|
||||
./run-tests.sh verbose
|
||||
```
|
||||
|
||||
### 방법 2: sh로 실행하려면 POSIX 호환 스크립트 사용
|
||||
```bash
|
||||
sh run-tests.sh verbose
|
||||
```
|
||||
|
||||
## 3. 필요한 패키지 설치 확인
|
||||
```bash
|
||||
# Poetry가 설치되어 있는지 확인
|
||||
poetry --version
|
||||
|
||||
# 의존성 설치
|
||||
poetry install
|
||||
|
||||
# pytest와 관련 플러그인 설치 확인
|
||||
poetry run pip install pytest-cov pytest-asyncio
|
||||
```
|
||||
|
||||
## 4. 테스트 실행 예제
|
||||
|
||||
### 모든 테스트 실행
|
||||
```bash
|
||||
./run-tests.sh
|
||||
```
|
||||
|
||||
### 상세 출력 모드
|
||||
```bash
|
||||
./run-tests.sh verbose
|
||||
```
|
||||
|
||||
### 커버리지 포함
|
||||
```bash
|
||||
./run-tests.sh coverage
|
||||
```
|
||||
|
||||
### 특정 테스트만 실행
|
||||
```bash
|
||||
./run-tests.sh auth # 인증 테스트만
|
||||
./run-tests.sh user # 사용자 테스트만
|
||||
./run-tests.sh moviemaker # MovieMaker 테스트만
|
||||
./run-tests.sh social # 소셜 로그인 테스트만
|
||||
./run-tests.sh video # 비디오 테스트만
|
||||
```
|
||||
|
||||
## 5. pytest 직접 실행 (Poetry 없이)
|
||||
```bash
|
||||
# 가상환경 활성화 후
|
||||
python -m pytest tests/ -v
|
||||
```
|
||||
|
||||
## 6. 일반적인 문제 해결
|
||||
|
||||
### ImportError 발생 시
|
||||
```bash
|
||||
# PYTHONPATH 설정
|
||||
export PYTHONPATH=$PYTHONPATH:/home/jhpark/workspace/O2Sound_ver2/backend
|
||||
|
||||
# 또는 pytest 실행 시 직접 지정
|
||||
PYTHONPATH=/home/jhpark/workspace/O2Sound_ver2/backend pytest tests/
|
||||
```
|
||||
|
||||
### pytest-cov가 없다는 에러
|
||||
```bash
|
||||
pip install pytest-cov
|
||||
```
|
||||
|
||||
### 권한 문제
|
||||
```bash
|
||||
sudo chmod +x run-tests.sh
|
||||
```
|
||||
Whitespace-only changes.
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)
|
||||
@@ -0,0 +1,165 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 프로젝트 루트를 Python 경로에 추가
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
# 테스트 환경에서는 테스트 설정을 사용하도록 패치
|
||||
os.environ["BE_ENV"] = "local" # 또는 테스트 설정 사용
|
||||
os.environ["ENVIRONMENT"] = "local"
|
||||
|
||||
# .env.test 파일 로드
|
||||
from dotenv import load_dotenv
|
||||
test_env_path = os.path.join(os.path.dirname(__file__), '..', '.env.test')
|
||||
if os.path.exists(test_env_path):
|
||||
load_dotenv(test_env_path)
|
||||
|
||||
from app.main import app
|
||||
from app.core.database import Base, get_db
|
||||
from app.dependencies import get_auth_service, get_user_service, get_video_service, get_google_service
|
||||
from app.core.redis.redis_manager import RedisManager
|
||||
|
||||
# 테스트용 데이터베이스 설정
|
||||
# 환경변수에서 테스트 DB URL 가져오기 (기본값: PostgreSQL)
|
||||
TEST_DATABASE_URL = os.getenv(
|
||||
"TEST_DATABASE_URL",
|
||||
"postgresql://postgres:postgres@localhost:5432/test_o2sound"
|
||||
)
|
||||
|
||||
# SQLite를 사용하려면 USE_SQLITE_TEST=1 환경변수 설정
|
||||
if os.getenv("USE_SQLITE_TEST") == "1":
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
else:
|
||||
# PostgreSQL 사용 (기본값)
|
||||
SQLALCHEMY_DATABASE_URL = TEST_DATABASE_URL
|
||||
engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
|
||||
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# 테스트용 데이터베이스 의존성 오버라이드
|
||||
def override_get_db():
|
||||
try:
|
||||
db = TestingSessionLocal()
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# Mock 서비스 생성
|
||||
def create_mock_auth_service():
|
||||
mock = MagicMock()
|
||||
mock.join = MagicMock()
|
||||
mock.login = MagicMock()
|
||||
return mock
|
||||
|
||||
def create_mock_user_service():
|
||||
mock = MagicMock()
|
||||
mock.get_items = MagicMock()
|
||||
mock.update_item = MagicMock()
|
||||
mock.delete_item = MagicMock()
|
||||
mock.get_user_profile = MagicMock()
|
||||
mock.update_user_profile = MagicMock()
|
||||
return mock
|
||||
|
||||
def create_mock_video_service():
|
||||
mock = MagicMock()
|
||||
mock.get_all_by_user_id = MagicMock()
|
||||
mock.delete_by_video_id = MagicMock()
|
||||
return mock
|
||||
|
||||
def create_mock_google_service():
|
||||
mock = MagicMock()
|
||||
mock.get_login_url = AsyncMock()
|
||||
mock.handle_callback = AsyncMock()
|
||||
mock.get_token_by_temp_id = AsyncMock()
|
||||
return mock
|
||||
|
||||
def create_mock_redis_manager():
|
||||
mock = MagicMock()
|
||||
mock.get = AsyncMock(return_value=None)
|
||||
mock.set = AsyncMock(return_value=True)
|
||||
mock.delete = AsyncMock(return_value=True)
|
||||
mock.exists = AsyncMock(return_value=False)
|
||||
return mock
|
||||
|
||||
# 공통 Fixtures
|
||||
@pytest.fixture(scope="session")
|
||||
def database():
|
||||
"""세션 범위의 데이터베이스 설정"""
|
||||
# 테스트 시작 시 모든 테이블 생성
|
||||
Base.metadata.create_all(bind=engine)
|
||||
yield
|
||||
# 테스트 종료 시 모든 테이블 삭제
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(database):
|
||||
"""각 테스트마다 새로운 트랜잭션 시작"""
|
||||
connection = engine.connect()
|
||||
transaction = connection.begin()
|
||||
session = TestingSessionLocal(bind=connection)
|
||||
|
||||
yield session
|
||||
|
||||
session.close()
|
||||
transaction.rollback()
|
||||
connection.close()
|
||||
|
||||
@pytest.fixture
|
||||
def client(database):
|
||||
"""데이터베이스를 사용하는 테스트 클라이언트"""
|
||||
# 의존성 오버라이드
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_auth_service():
|
||||
return create_mock_auth_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_service():
|
||||
return create_mock_user_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_video_service():
|
||||
return create_mock_video_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_google_service():
|
||||
return create_mock_google_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_redis_manager():
|
||||
return create_mock_redis_manager()
|
||||
|
||||
@pytest.fixture
|
||||
def authenticated_client(client, mock_auth_service):
|
||||
"""인증된 테스트 클라이언트"""
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
# 로그인 성공 시뮬레이션
|
||||
mock_auth_service.login.return_value = {
|
||||
"access_token": "test_access_token",
|
||||
"token_type": "bearer",
|
||||
"user_id": 1
|
||||
}
|
||||
|
||||
# 헤더에 토큰 추가
|
||||
client.headers = {"Authorization": "Bearer test_access_token"}
|
||||
yield client
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
테스트 환경 설정
|
||||
실제 데이터베이스를 사용하지 않고 Mock만 사용하는 간단한 테스트 설정
|
||||
"""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from unittest.mock import MagicMock, AsyncMock
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 프로젝트 루트를 Python 경로에 추가
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.main import app
|
||||
from app.dependencies import get_auth_service, get_user_service, get_video_service, get_google_service
|
||||
from app.core.database import get_db
|
||||
|
||||
# Mock 데이터베이스 세션
|
||||
class MockDB:
|
||||
def __init__(self):
|
||||
self.committed = False
|
||||
self.rolled_back = False
|
||||
|
||||
def commit(self):
|
||||
self.committed = True
|
||||
|
||||
def rollback(self):
|
||||
self.rolled_back = True
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def add(self, obj):
|
||||
pass
|
||||
|
||||
def query(self, model):
|
||||
return MagicMock()
|
||||
|
||||
def refresh(self, obj):
|
||||
pass
|
||||
|
||||
# 테스트용 데이터베이스 의존성 오버라이드
|
||||
def override_get_db():
|
||||
try:
|
||||
db = MockDB()
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# Mock 서비스 생성
|
||||
def create_mock_auth_service():
|
||||
mock = MagicMock()
|
||||
mock.join = MagicMock()
|
||||
mock.login = MagicMock()
|
||||
return mock
|
||||
|
||||
def create_mock_user_service():
|
||||
mock = MagicMock()
|
||||
mock.get_items = MagicMock()
|
||||
mock.update_item = MagicMock()
|
||||
mock.delete_item = MagicMock()
|
||||
mock.get_user_profile = MagicMock()
|
||||
mock.update_user_profile = MagicMock()
|
||||
return mock
|
||||
|
||||
def create_mock_video_service():
|
||||
mock = MagicMock()
|
||||
mock.get_all_by_user_id = MagicMock()
|
||||
mock.delete_by_video_id = MagicMock()
|
||||
return mock
|
||||
|
||||
def create_mock_google_service():
|
||||
mock = MagicMock()
|
||||
mock.get_login_url = AsyncMock()
|
||||
mock.handle_callback = AsyncMock()
|
||||
mock.get_token_by_temp_id = AsyncMock()
|
||||
return mock
|
||||
|
||||
def create_mock_redis_manager():
|
||||
mock = MagicMock()
|
||||
mock.get = AsyncMock(return_value=None)
|
||||
mock.set = AsyncMock(return_value=True)
|
||||
mock.delete = AsyncMock(return_value=True)
|
||||
mock.exists = AsyncMock(return_value=False)
|
||||
return mock
|
||||
|
||||
# 공통 Fixtures
|
||||
@pytest.fixture
|
||||
def client():
|
||||
# 의존성 오버라이드
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_auth_service():
|
||||
return create_mock_auth_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_service():
|
||||
return create_mock_user_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_video_service():
|
||||
return create_mock_video_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_google_service():
|
||||
return create_mock_google_service()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_redis_manager():
|
||||
return create_mock_redis_manager()
|
||||
|
||||
@pytest.fixture
|
||||
def authenticated_client(client, mock_auth_service):
|
||||
"""인증된 테스트 클라이언트"""
|
||||
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
|
||||
# 로그인 성공 시뮬레이션
|
||||
mock_auth_service.login.return_value = {
|
||||
"access_token": "test_access_token",
|
||||
"token_type": "bearer",
|
||||
"user_id": 1
|
||||
}
|
||||
|
||||
# 헤더에 토큰 추가
|
||||
client.headers = {"Authorization": "Bearer test_access_token"}
|
||||
yield client
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,136 @@
|
||||
import pytest
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from app.core.redis.redis_manager import RedisManager
|
||||
from app.shared.progress import Process
|
||||
from app.services.auth_service import AuthService
|
||||
from app.services.user_service import UserService
|
||||
|
||||
class TestAsyncServices:
|
||||
"""비동기 서비스 테스트"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_redis_manager_operations(self):
|
||||
"""Redis Manager 비동기 작업 테스트"""
|
||||
with patch('redis.asyncio.Redis') as mock_redis:
|
||||
# Mock 설정
|
||||
mock_instance = AsyncMock()
|
||||
mock_redis.from_url.return_value = mock_instance
|
||||
|
||||
# RedisManager 인스턴스 생성
|
||||
redis_manager = RedisManager()
|
||||
|
||||
# set 작업 테스트
|
||||
mock_instance.set.return_value = True
|
||||
result = await redis_manager.set("test_key", "test_value", 3600)
|
||||
assert result == True
|
||||
mock_instance.set.assert_called_once_with("test_key", "test_value", 3600)
|
||||
|
||||
# get 작업 테스트
|
||||
mock_instance.get.return_value = b"test_value"
|
||||
result = await redis_manager.get("test_key")
|
||||
assert result == "test_value"
|
||||
|
||||
# exists 작업 테스트
|
||||
mock_instance.exists.return_value = 1
|
||||
result = await redis_manager.exists("test_key")
|
||||
assert result == True
|
||||
|
||||
# delete 작업 테스트
|
||||
mock_instance.delete.return_value = 1
|
||||
result = await redis_manager.delete("test_key")
|
||||
assert result == True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_progress_tracking(self):
|
||||
"""진행상황 추적 테스트"""
|
||||
# Mock RedisManager
|
||||
mock_redis = AsyncMock()
|
||||
mock_redis.set = AsyncMock(return_value=True)
|
||||
mock_redis.get = AsyncMock(return_value='{"metadata": true, "lyrics": false}')
|
||||
|
||||
# Process 인스턴스 생성
|
||||
process = Process(mock_redis)
|
||||
|
||||
# 초기 상태 설정
|
||||
await process.init_task_status("task_123")
|
||||
mock_redis.set.assert_called()
|
||||
|
||||
# 상태 조회
|
||||
status = await process.get_task_status("task_123")
|
||||
assert status["metadata"] == True
|
||||
assert status["lyrics"] == False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_requests(self):
|
||||
"""동시 요청 처리 테스트"""
|
||||
# Mock 서비스
|
||||
mock_service = AsyncMock()
|
||||
mock_service.process_request = AsyncMock(side_effect=lambda x: f"processed_{x}")
|
||||
|
||||
# 동시에 여러 요청 실행
|
||||
tasks = []
|
||||
for i in range(5):
|
||||
task = mock_service.process_request(f"request_{i}")
|
||||
tasks.append(task)
|
||||
|
||||
results = await asyncio.gather(*tasks)
|
||||
|
||||
# 검증
|
||||
assert len(results) == 5
|
||||
for i, result in enumerate(results):
|
||||
assert result == f"processed_request_{i}"
|
||||
assert mock_service.process_request.call_count == 5
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_error_handling_in_async_context(self):
|
||||
"""비동기 컨텍스트에서의 에러 처리 테스트"""
|
||||
mock_service = AsyncMock()
|
||||
mock_service.risky_operation = AsyncMock(side_effect=ValueError("테스트 에러"))
|
||||
|
||||
with pytest.raises(ValueError, match="테스트 에러"):
|
||||
await mock_service.risky_operation()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_context_manager(self):
|
||||
"""비동기 컨텍스트 매니저 테스트"""
|
||||
class AsyncResource:
|
||||
def __init__(self):
|
||||
self.connected = False
|
||||
|
||||
async def __aenter__(self):
|
||||
self.connected = True
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
self.connected = False
|
||||
|
||||
async with AsyncResource() as resource:
|
||||
assert resource.connected == True
|
||||
|
||||
assert resource.connected == False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timeout_handling(self):
|
||||
"""타임아웃 처리 테스트"""
|
||||
async def slow_operation():
|
||||
await asyncio.sleep(2)
|
||||
return "completed"
|
||||
|
||||
# 타임아웃으로 실패해야 함
|
||||
with pytest.raises(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(slow_operation(), timeout=0.1)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_generator(self):
|
||||
"""비동기 제너레이터 테스트"""
|
||||
async def data_generator():
|
||||
for i in range(3):
|
||||
await asyncio.sleep(0.01) # 비동기 작업 시뮬레이션
|
||||
yield i
|
||||
|
||||
results = []
|
||||
async for value in data_generator():
|
||||
results.append(value)
|
||||
|
||||
assert results == [0, 1, 2]
|
||||
@@ -0,0 +1,135 @@
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from app.core.database import Base
|
||||
from app.domain.models import User, Item, Video # UserItem -> Item, UserVideo -> Video
|
||||
from datetime import datetime
|
||||
|
||||
class TestDatabaseIntegration:
|
||||
"""데이터베이스 통합 테스트 예제"""
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(self):
|
||||
"""테스트용 데이터베이스 세션"""
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(bind=engine)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
session = SessionLocal()
|
||||
yield session
|
||||
session.close()
|
||||
|
||||
def test_user_creation(self, db_session):
|
||||
"""사용자 생성 테스트"""
|
||||
# 사용자 생성
|
||||
user = User(
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password_123",
|
||||
name="Test User",
|
||||
is_active=True
|
||||
)
|
||||
db_session.add(user)
|
||||
db_session.commit()
|
||||
|
||||
# 조회
|
||||
saved_user = db_session.query(User).filter_by(email="test@example.com").first()
|
||||
assert saved_user is not None
|
||||
assert saved_user.name == "Test User"
|
||||
assert saved_user.is_active == True
|
||||
|
||||
def test_user_item_relationship(self, db_session):
|
||||
"""사용자-아이템 관계 테스트"""
|
||||
# 사용자 생성
|
||||
user = User(
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password_123",
|
||||
name="Test User"
|
||||
)
|
||||
db_session.add(user)
|
||||
db_session.commit()
|
||||
|
||||
# 아이템 생성
|
||||
item = Item(
|
||||
user_id=user.id,
|
||||
name="Test Item",
|
||||
address="Test Address",
|
||||
url="https://example.com"
|
||||
)
|
||||
db_session.add(item)
|
||||
db_session.commit()
|
||||
|
||||
# 관계 확인
|
||||
user_items = db_session.query(Item).filter_by(user_id=user.id).all()
|
||||
assert len(user_items) == 1
|
||||
assert user_items[0].name == "Test Item"
|
||||
|
||||
def test_cascade_delete(self, db_session):
|
||||
"""Cascade 삭제 테스트"""
|
||||
# 사용자와 아이템 생성
|
||||
user = User(
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password_123",
|
||||
name="Test User"
|
||||
)
|
||||
db_session.add(user)
|
||||
db_session.commit()
|
||||
|
||||
item = Item(
|
||||
user_id=user.id,
|
||||
name="Test Item",
|
||||
address="Test Address",
|
||||
url="https://example.com"
|
||||
)
|
||||
db_session.add(item)
|
||||
db_session.commit()
|
||||
|
||||
# 사용자 삭제
|
||||
db_session.delete(user)
|
||||
db_session.commit()
|
||||
|
||||
# 아이템도 삭제되었는지 확인
|
||||
items = db_session.query(Item).all()
|
||||
assert len(items) == 0
|
||||
|
||||
@pytest.mark.parametrize("item_name,expected_count", [
|
||||
("Restaurant", 2),
|
||||
("Cafe", 1),
|
||||
("Shop", 3)
|
||||
])
|
||||
def test_filter_items_by_name(self, db_session, item_name, expected_count):
|
||||
"""이름별 아이템 필터링 테스트"""
|
||||
# 사용자 생성
|
||||
user = User(
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password_123",
|
||||
name="Test User"
|
||||
)
|
||||
db_session.add(user)
|
||||
db_session.commit()
|
||||
|
||||
# 다양한 타입의 아이템 생성
|
||||
items_data = [
|
||||
("Restaurant", 2),
|
||||
("Cafe", 1),
|
||||
("Shop", 3)
|
||||
]
|
||||
|
||||
for name_prefix, count in items_data:
|
||||
for i in range(count):
|
||||
item = Item(
|
||||
user_id=user.id,
|
||||
name=f"{name_prefix} {i+1}",
|
||||
address=f"Address {name_prefix} {i+1}",
|
||||
url=f"https://example.com/{name_prefix.lower()}{i+1}"
|
||||
)
|
||||
db_session.add(item)
|
||||
|
||||
db_session.commit()
|
||||
|
||||
# 이름으로 필터링
|
||||
filtered_items = db_session.query(Item).filter(
|
||||
Item.user_id == user.id,
|
||||
Item.name.like(f"{item_name}%")
|
||||
).all()
|
||||
|
||||
assert len(filtered_items) == expected_count
|
||||
@@ -0,0 +1,205 @@
|
||||
# 통합 테스트 시나리오
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from tests.utils import TestUtils
|
||||
from app.dependencies import get_auth_service, get_user_service, get_video_service
|
||||
|
||||
class TestIntegrationScenarios:
|
||||
"""엔드투엔드 통합 테스트 시나리오"""
|
||||
|
||||
def test_complete_user_journey(self, client, mock_auth_service, mock_user_service, mock_video_service):
|
||||
"""사용자의 전체 여정 테스트: 회원가입 → 로그인 → 프로필 → 아이템 → 비디오"""
|
||||
utils = TestUtils()
|
||||
|
||||
# 1. 회원가입
|
||||
client.app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
|
||||
mock_auth_service.join.return_value = utils.create_test_user()
|
||||
|
||||
response = client.post("/api/v1/auth/join", json={
|
||||
"email": "newuser@example.com",
|
||||
"password": "NewUser1234!",
|
||||
"password_confirm": "NewUser1234!",
|
||||
"name": "New User"
|
||||
})
|
||||
user_data = utils.assert_response_success(response)
|
||||
user_id = user_data["id"]
|
||||
|
||||
# 2. 로그인
|
||||
mock_auth_service.login.return_value = {
|
||||
"access_token": utils.create_test_token(user_id),
|
||||
"token_type": "bearer",
|
||||
"user_id": user_id
|
||||
}
|
||||
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"email": "newuser@example.com",
|
||||
"password": "NewUser1234!"
|
||||
})
|
||||
login_data = utils.assert_response_success(response)
|
||||
token = login_data["access_token"]
|
||||
|
||||
# 3. 인증 헤더 설정
|
||||
client.headers = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
# 4. 프로필 조회
|
||||
client.app.dependency_overrides[get_user_service] = lambda: mock_user_service
|
||||
mock_user_service.get_user_profile.return_value = {
|
||||
"user_id": user_id,
|
||||
"email": "newuser@example.com",
|
||||
"name": "New User",
|
||||
"bio": None
|
||||
}
|
||||
|
||||
response = client.post("/api/v1/user/profile", json={"user_id": user_id})
|
||||
profile_data = utils.assert_response_success(response)
|
||||
|
||||
# 5. 프로필 업데이트
|
||||
mock_user_service.update_user_profile.return_value = {
|
||||
"user_id": user_id,
|
||||
"name": "Updated User",
|
||||
"bio": "I love making videos!",
|
||||
"updated": True
|
||||
}
|
||||
|
||||
response = client.put("/api/v1/user/profile/update", json={
|
||||
"user_id": user_id,
|
||||
"name": "Updated User",
|
||||
"bio": "I love making videos!"
|
||||
})
|
||||
utils.assert_response_success(response)
|
||||
|
||||
# 6. 아이템 생성 시뮬레이션 (서비스에서 처리)
|
||||
mock_user_service.get_items.return_value = {
|
||||
"items": [utils.create_test_item(1, user_id)],
|
||||
"total": 1
|
||||
}
|
||||
|
||||
response = client.post("/api/v1/user/items", json={
|
||||
"user_id": user_id,
|
||||
"page": 1,
|
||||
"limit": 10
|
||||
})
|
||||
items_data = utils.assert_response_success(response)
|
||||
assert items_data["total"] == 1
|
||||
|
||||
# 7. 비디오 생성 시뮬레이션
|
||||
client.app.dependency_overrides[get_video_service] = lambda: mock_video_service
|
||||
mock_video_service.get_all_by_user_id.return_value = {
|
||||
"videos": [utils.create_test_video(1, user_id)],
|
||||
"total": 1
|
||||
}
|
||||
|
||||
response = client.post("/api/v1/user/videos", json={
|
||||
"user_id": user_id,
|
||||
"page": 1,
|
||||
"limit": 10
|
||||
})
|
||||
videos_data = utils.assert_response_success(response)
|
||||
assert videos_data["total"] == 1
|
||||
|
||||
def test_moviemaker_workflow_complete(self, client, mock_redis_manager):
|
||||
"""MovieMaker 워크플로우 전체 과정 테스트"""
|
||||
utils = TestUtils()
|
||||
|
||||
# 1. 워크플로우 시작
|
||||
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:
|
||||
mock_process = MagicMock()
|
||||
mock_process.init_task_status = AsyncMock(return_value=None)
|
||||
mock_process_class.return_value = mock_process
|
||||
|
||||
# Celery tasks mock
|
||||
with 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'):
|
||||
|
||||
response = client.post("/api/v1/moviemaker/start-workflow", json={
|
||||
"url": "https://example.com/video"
|
||||
})
|
||||
workflow_data = utils.assert_response_success(response)
|
||||
task_id = workflow_data["task_id"]
|
||||
|
||||
# 2. 진행상황 확인 - 초기 상태
|
||||
mock_process.get_task_status = AsyncMock(return_value={
|
||||
"metadata": True,
|
||||
"lyrics": False,
|
||||
"songs": False,
|
||||
"images": False,
|
||||
"movies": False,
|
||||
"combined": False
|
||||
})
|
||||
|
||||
response = client.post("/api/v1/moviemaker/progress", json={
|
||||
"task_id": task_id
|
||||
})
|
||||
progress_data = response.json()
|
||||
assert progress_data["progress"]["metadata"] == True
|
||||
assert progress_data["progress"]["lyrics"] == False
|
||||
|
||||
# 3. 진행상황 확인 - 중간 상태
|
||||
mock_process.get_task_status = AsyncMock(return_value={
|
||||
"metadata": True,
|
||||
"lyrics": True,
|
||||
"songs": True,
|
||||
"images": True,
|
||||
"movies": False,
|
||||
"combined": False
|
||||
})
|
||||
|
||||
response = client.post("/api/v1/moviemaker/progress", json={
|
||||
"task_id": task_id
|
||||
})
|
||||
progress_data = response.json()
|
||||
assert progress_data["progress"]["songs"] == True
|
||||
assert progress_data["progress"]["movies"] == False
|
||||
|
||||
# 4. 진행상황 확인 - 완료 상태
|
||||
mock_process.get_task_status = AsyncMock(return_value={
|
||||
"metadata": True,
|
||||
"lyrics": True,
|
||||
"songs": True,
|
||||
"images": True,
|
||||
"movies": True,
|
||||
"combined": True
|
||||
})
|
||||
|
||||
response = client.post("/api/v1/moviemaker/progress", json={
|
||||
"task_id": task_id
|
||||
})
|
||||
progress_data = response.json()
|
||||
assert all(progress_data["progress"].values()) == True
|
||||
|
||||
def test_google_oauth_flow(self, client, mock_google_service):
|
||||
"""Google OAuth 전체 플로우 테스트"""
|
||||
utils = TestUtils()
|
||||
|
||||
# 1. Google 로그인 URL 요청
|
||||
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"
|
||||
}
|
||||
|
||||
response = client.get("/api/v1/social/google/login?return_url=/dashboard")
|
||||
assert response.status_code == 200
|
||||
|
||||
# 2. Google OAuth 콜백 처리
|
||||
mock_result = MagicMock()
|
||||
mock_result.temp_token_id = "temp_google_token_123"
|
||||
mock_result.return_url = "/dashboard"
|
||||
mock_google_service.handle_callback.return_value = mock_result
|
||||
|
||||
response = client.get("/api/v1/social/google/callback?code=google_auth_code&state=state_data")
|
||||
assert response.status_code == 307 # Redirect
|
||||
assert "temp_google_token_123" in response.headers["location"]
|
||||
|
||||
# 3. 임시 토큰으로 정보 조회
|
||||
google_data = utils.create_google_oauth_data()
|
||||
mock_google_service.get_token_by_temp_id.return_value = google_data
|
||||
|
||||
response = client.get("/api/v1/social/google/token/temp_google_token_123")
|
||||
token_data = utils.assert_response_success(response)
|
||||
assert token_data["user_info"]["email"] == "test@gmail.com"
|
||||
@@ -0,0 +1,60 @@
|
||||
# pytest-mock을 사용한 고급 Mock 예제
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
from datetime import datetime
|
||||
|
||||
class TestAdvancedMocking:
|
||||
"""고급 Mock 패턴 예제"""
|
||||
|
||||
def test_with_datetime_mock(self):
|
||||
"""datetime을 mock하는 예제"""
|
||||
with patch('datetime.datetime') as mock_datetime:
|
||||
mock_datetime.now.return_value = datetime(2024, 1, 1, 12, 0, 0)
|
||||
mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
|
||||
|
||||
# 테스트 코드
|
||||
from datetime import datetime
|
||||
assert datetime.now().year == 2024
|
||||
|
||||
def test_with_context_manager_mock(self):
|
||||
"""Context manager를 mock하는 예제"""
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = "file content"
|
||||
|
||||
with patch('builtins.open', return_value=mock_file):
|
||||
with open('test.txt', 'r') as f:
|
||||
content = f.read()
|
||||
assert content == "file content"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_function_mock(self):
|
||||
"""비동기 함수를 mock하는 예제"""
|
||||
mock_service = AsyncMock()
|
||||
mock_service.get_data.return_value = {"status": "success"}
|
||||
|
||||
result = await mock_service.get_data()
|
||||
assert result["status"] == "success"
|
||||
|
||||
def test_side_effect_with_exception(self):
|
||||
"""side_effect로 예외를 발생시키는 예제"""
|
||||
mock_func = MagicMock()
|
||||
mock_func.side_effect = ValueError("테스트 에러")
|
||||
|
||||
with pytest.raises(ValueError, match="테스트 에러"):
|
||||
mock_func()
|
||||
|
||||
def test_multiple_return_values(self):
|
||||
"""여러 번 호출 시 다른 값을 반환하는 예제"""
|
||||
mock_func = MagicMock()
|
||||
mock_func.side_effect = [1, 2, 3]
|
||||
|
||||
assert mock_func() == 1
|
||||
assert mock_func() == 2
|
||||
assert mock_func() == 3
|
||||
|
||||
def test_property_mock(self):
|
||||
"""Property를 mock하는 예제"""
|
||||
mock_obj = MagicMock()
|
||||
type(mock_obj).name = PropertyMock(return_value="Test Name")
|
||||
|
||||
assert mock_obj.name == "Test Name"
|
||||
@@ -0,0 +1,107 @@
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from app.presentation.schemas.auth_schema import JoinRequest, LoginRequest
|
||||
from app.presentation.schemas.useritems_schema import GetItemsRequest, UpdateItemRequest
|
||||
from app.presentation.schemas.uservideo_schema import GetVideosRequest
|
||||
|
||||
class TestSchemaValidation:
|
||||
"""Pydantic 스키마 검증 테스트"""
|
||||
|
||||
def test_join_request_valid(self):
|
||||
"""유효한 회원가입 요청 스키마 테스트"""
|
||||
request = JoinRequest(
|
||||
email="test@example.com",
|
||||
password="Test1234!",
|
||||
password_confirm="Test1234!",
|
||||
name="Test User"
|
||||
)
|
||||
assert request.email == "test@example.com"
|
||||
assert request.name == "Test User"
|
||||
|
||||
def test_join_request_password_mismatch(self):
|
||||
"""비밀번호 불일치 검증 테스트"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
JoinRequest(
|
||||
email="test@example.com",
|
||||
password="Test1234!",
|
||||
password_confirm="Different1234!",
|
||||
name="Test User"
|
||||
)
|
||||
assert "passwords do not match" in str(exc_info.value).lower()
|
||||
|
||||
def test_join_request_invalid_email(self):
|
||||
"""잘못된 이메일 형식 테스트"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
JoinRequest(
|
||||
email="invalid-email",
|
||||
password="Test1234!",
|
||||
password_confirm="Test1234!",
|
||||
name="Test User"
|
||||
)
|
||||
assert "email" in str(exc_info.value).lower()
|
||||
|
||||
def test_login_request_valid(self):
|
||||
"""유효한 로그인 요청 스키마 테스트"""
|
||||
request = LoginRequest(
|
||||
email="test@example.com",
|
||||
password="Test1234!"
|
||||
)
|
||||
assert request.email == "test@example.com"
|
||||
assert request.password == "Test1234!"
|
||||
|
||||
def test_get_items_request_with_pagination(self):
|
||||
"""페이지네이션이 포함된 아이템 조회 요청 테스트"""
|
||||
request = GetItemsRequest(
|
||||
user_id=1,
|
||||
page=2,
|
||||
limit=20
|
||||
)
|
||||
assert request.user_id == 1
|
||||
assert request.page == 2
|
||||
assert request.limit == 20
|
||||
|
||||
def test_get_items_request_default_values(self):
|
||||
"""기본값을 사용하는 아이템 조회 요청 테스트"""
|
||||
request = GetItemsRequest(user_id=1)
|
||||
assert request.user_id == 1
|
||||
assert request.page == 1 # 기본값
|
||||
assert request.limit == 10 # 기본값
|
||||
|
||||
def test_update_item_request_partial(self):
|
||||
"""부분 업데이트 요청 테스트"""
|
||||
request = UpdateItemRequest(
|
||||
item_id=1,
|
||||
name="Updated Name"
|
||||
# description은 선택적
|
||||
)
|
||||
assert request.item_id == 1
|
||||
assert request.name == "Updated Name"
|
||||
assert request.description is None
|
||||
|
||||
@pytest.mark.parametrize("invalid_data,expected_error", [
|
||||
({"user_id": "not_a_number"}, "user_id"),
|
||||
({"user_id": -1}, "user_id"),
|
||||
({"user_id": 1, "page": 0}, "page"),
|
||||
({"user_id": 1, "limit": 101}, "limit"),
|
||||
])
|
||||
def test_get_items_request_invalid_data(self, invalid_data, expected_error):
|
||||
"""잘못된 데이터로 아이템 조회 요청 테스트"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
GetItemsRequest(**invalid_data)
|
||||
assert expected_error in str(exc_info.value).lower()
|
||||
|
||||
def test_schema_json_serialization(self):
|
||||
"""스키마 JSON 직렬화 테스트"""
|
||||
request = LoginRequest(
|
||||
email="test@example.com",
|
||||
password="Test1234!"
|
||||
)
|
||||
|
||||
# JSON으로 변환
|
||||
json_data = request.model_dump_json()
|
||||
assert "test@example.com" in json_data
|
||||
|
||||
# JSON에서 다시 객체로
|
||||
parsed = LoginRequest.model_validate_json(json_data)
|
||||
assert parsed.email == request.email
|
||||
@@ -0,0 +1,122 @@
|
||||
# 테스트 유틸리티 함수들
|
||||
from typing import Dict, Any
|
||||
from datetime import datetime, timedelta
|
||||
from jose import jwt # python-jose 패키지
|
||||
from passlib.context import CryptContext
|
||||
|
||||
# 비밀번호 해싱 컨텍스트
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
class TestUtils:
|
||||
"""테스트에서 사용할 유틸리티 함수 모음"""
|
||||
|
||||
@staticmethod
|
||||
def create_test_user(user_id: int = 1, email: str = "test@example.com") -> Dict[str, Any]:
|
||||
"""테스트용 사용자 데이터 생성"""
|
||||
return {
|
||||
"id": user_id,
|
||||
"email": email,
|
||||
"name": f"Test User {user_id}",
|
||||
"hashed_password": pwd_context.hash("Test1234!"),
|
||||
"is_active": True,
|
||||
"created_at": datetime.utcnow(),
|
||||
"updated_at": datetime.utcnow()
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def create_test_token(user_id: int = 1, expires_delta: timedelta = None) -> str:
|
||||
"""테스트용 JWT 토큰 생성"""
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(hours=1))
|
||||
payload = {
|
||||
"sub": str(user_id),
|
||||
"exp": expire,
|
||||
"iat": datetime.utcnow()
|
||||
}
|
||||
return jwt.encode(payload, "test_secret_key", algorithm="HS256")
|
||||
|
||||
@staticmethod
|
||||
def create_test_item(item_id: int = 1, user_id: int = 1) -> Dict[str, Any]:
|
||||
"""테스트용 아이템 데이터 생성"""
|
||||
return {
|
||||
"id": item_id,
|
||||
"user_id": user_id,
|
||||
"name": f"Test Item {item_id}",
|
||||
"address": f"Test Address {item_id}",
|
||||
"url": f"https://example.com/item{item_id}",
|
||||
"created_at": datetime.utcnow(),
|
||||
"updated_at": datetime.utcnow()
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def create_test_video(video_id: int = 1, user_id: int = 1) -> Dict[str, Any]:
|
||||
"""테스트용 비디오 데이터 생성"""
|
||||
return {
|
||||
"id": video_id,
|
||||
"user_id": user_id,
|
||||
"title": f"Test Video {video_id}",
|
||||
"description": f"Description for video {video_id}",
|
||||
"url": f"https://example.com/video{video_id}.mp4",
|
||||
"is_uploaded": True,
|
||||
"download_count": 0,
|
||||
"resolution": "1920x1080",
|
||||
"status": "완료됨",
|
||||
"created_at": datetime.utcnow()
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def create_test_workflow_data() -> Dict[str, Any]:
|
||||
"""테스트용 워크플로우 데이터 생성"""
|
||||
return {
|
||||
"task_id": "test_task_123",
|
||||
"url": "https://example.com/test",
|
||||
"status": {
|
||||
"metadata": False,
|
||||
"lyrics": False,
|
||||
"songs": False,
|
||||
"images": False,
|
||||
"movies": False,
|
||||
"combined": False
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def create_google_oauth_data() -> Dict[str, Any]:
|
||||
"""테스트용 Google OAuth 데이터 생성"""
|
||||
return {
|
||||
"access_token": "google_access_token_test",
|
||||
"refresh_token": "google_refresh_token_test",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"user_info": {
|
||||
"id": "google_123",
|
||||
"email": "test@gmail.com",
|
||||
"name": "Google Test User",
|
||||
"picture": "https://example.com/picture.jpg",
|
||||
"verified_email": True
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def assert_response_success(response, expected_data: Dict[str, Any] = None):
|
||||
"""API 응답 성공 검증"""
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
|
||||
if expected_data:
|
||||
for key, value in expected_data.items():
|
||||
assert data["data"][key] == value
|
||||
|
||||
return data["data"]
|
||||
|
||||
@staticmethod
|
||||
def assert_response_error(response, expected_status: int = 400, expected_message: str = None):
|
||||
"""API 응답 에러 검증"""
|
||||
assert response.status_code == expected_status
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
|
||||
if expected_message:
|
||||
assert expected_message in data["message"]
|
||||
|
||||
return data
|
||||
Reference in new issue
Block a user