Skip to content

[25.07.18 / TASK-225] Test - 주간 뉴스레터 배치 단위 테스트 추가 #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions insight/tasks/weekly_newsletter_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,11 @@ def __init__(
self.today = get_local_date()

def _delete_old_maillogs(self) -> None:
"""7일 이전의 성공한 메일 발송 로그 삭제"""
"""이전 뉴스레터의 성공한 메일 발송 로그 삭제"""
try:
deleted_count = NotiMailLog.objects.filter(
created_at__lt=self.before_a_week,
# 느슨한 시간 적용
sent_at__lt=self.before_a_week + timedelta(days=1),
is_success=True,
).delete()[0]

Expand Down
116 changes: 104 additions & 12 deletions insight/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import sys
import uuid
from datetime import date, timedelta
from unittest.mock import MagicMock

import pytest
from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.http import HttpRequest

Expand All @@ -13,8 +14,25 @@
UserWeeklyTrend,
WeeklyTrend,
WeeklyTrendInsight,
WeeklyUserReminder,
WeeklyUserStats,
WeeklyUserTrendInsight,
)
from insight.schemas import Newsletter
from modules.mail.schemas import EmailMessage
from users.models import User
from utils.utils import get_previous_week_range


@pytest.fixture
def mock_setup_django():
"""setup_django 모듈 모킹"""
sys.modules["setup_django"] = MagicMock()
try:
yield sys.modules["setup_django"]
finally:
# 테스트 후 정리
del sys.modules["setup_django"]


@pytest.fixture
Expand All @@ -26,6 +44,7 @@ def user(db):
refresh_token="test-refresh-token",
group_id=1,
email="[email protected]",
username="test_user",
is_active=True,
)

Expand Down Expand Up @@ -88,6 +107,26 @@ def sample_trending_items():
]


@pytest.fixture
def sample_weekly_user_stats():
"""테스트용 주간 사용자 통계 데이터"""
return WeeklyUserStats(
posts=20,
new_posts=3,
views=100,
likes=10,
)


@pytest.fixture
def sample_weekly_user_reminder():
"""테스트용 주간 사용자 리마인더 데이터"""
return WeeklyUserReminder(
title="Django 20주년 축하하기",
days_ago=12,
)


@pytest.fixture
def sample_weekly_trend_insight(sample_trend_analysis, sample_trending_items):
"""테스트용 주간 트렌드 인사이트 데이터"""
Expand All @@ -97,14 +136,49 @@ def sample_weekly_trend_insight(sample_trend_analysis, sample_trending_items):
)


@pytest.fixture
def sample_weekly_user_trend_insight(
sample_trend_analysis,
sample_trending_items,
sample_weekly_user_stats,
sample_weekly_user_reminder,
):
"""테스트용 사용자 주간 트렌드 인사이트 데이터"""
return WeeklyUserTrendInsight(
trending_summary=sample_trending_items,
trend_analysis=sample_trend_analysis,
user_weekly_stats=sample_weekly_user_stats,
user_weekly_reminder=sample_weekly_user_reminder,
)


@pytest.fixture
def sample_newsletter(user):
"""테스트용 뉴스레터 객체 생성"""
return Newsletter(
user_id=user.id,
email_message=EmailMessage(
to=[user.email],
from_email=settings.DEFAULT_FROM_EMAIL,
subject="Test Newsletter",
text_body="Test content",
html_body="<div>Test content</div>",
),
)


@pytest.fixture
def sample_newsletters(sample_newsletter):
"""테스트용 뉴스레터 리스트 생성"""
return [sample_newsletter]


@pytest.fixture
def weekly_trend(
db, sample_weekly_trend_insight: WeeklyTrendInsight
) -> WeeklyTrend:
"""주간 트렌드 생성"""
today = date.today()
week_start = today - timedelta(days=today.weekday())
week_end = week_start + timedelta(days=6)
week_start, week_end = get_previous_week_range()

return WeeklyTrend.objects.create(
week_start_date=week_start,
Expand All @@ -115,14 +189,14 @@ def weekly_trend(

@pytest.fixture
def user_weekly_trend(
db, user, sample_weekly_trend_insight: WeeklyTrendInsight
db, user, sample_weekly_user_trend_insight: WeeklyUserTrendInsight
) -> UserWeeklyTrend:
"""사용자 주간 트렌드 생성"""
today = date.today()
week_start = today - timedelta(days=today.weekday())
week_end = week_start + timedelta(days=6)
week_start, week_end = get_previous_week_range()

insight_dict = sample_weekly_user_trend_insight.to_json_dict()
insight_dict["user_weekly_reminder"] = {} # 주간 글 작성 사용자

insight_dict = sample_weekly_trend_insight.to_json_dict()
# 사용자 인사이트는 제목을 조금 다르게 설정
if insight_dict["trending_summary"]:
insight_dict["trending_summary"][0]["title"] = "Django 모델 최적화하기"
Expand All @@ -138,12 +212,30 @@ def user_weekly_trend(
)


@pytest.fixture
def inactive_user_weekly_trend(
db, user, sample_weekly_user_trend_insight: WeeklyUserTrendInsight
):
"""주간 글 미작성 사용자 주간 트렌드 생성"""
week_start, week_end = get_previous_week_range()

insight_dict = sample_weekly_user_trend_insight.to_json_dict()
insight_dict["trending_summary"] = []
insight_dict["trend_analysis"] = {}
insight_dict["user_weekly_stats"]["new_posts"] = 0

return UserWeeklyTrend.objects.create(
user=user,
week_start_date=week_start,
week_end_date=week_end,
insight=insight_dict,
)


@pytest.fixture
def empty_insight_weekly_trend(db):
"""빈 인사이트를 가진 주간 트렌드"""
today = date.today()
week_start = today - timedelta(days=today.weekday())
week_end = week_start + timedelta(days=6)
week_start, week_end = get_previous_week_range()

return WeeklyTrend.objects.create(
week_start_date=week_start, week_end_date=week_end, insight={}
Expand Down
Empty file added insight/tests/tasks/__init__.py
Empty file.
Loading