58 lines
2.9 KiB
Python
58 lines
2.9 KiB
Python
from datetime import datetime, time
|
|
from unittest.mock import patch
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.test import TestCase
|
|
|
|
from .models import FastingSettings
|
|
from .services.fasting import configure_fasting
|
|
from .services.fasting_notifications import notify_fasting_phase_changes
|
|
from .services.notifications import NotificationError
|
|
|
|
|
|
class FastingNotificationTests(TestCase):
|
|
def setUp(self):
|
|
self.user = get_user_model().objects.create_user(username='phase-user')
|
|
self.at = lambda hour, minute=0: datetime(2026, 10, 3, hour, minute, tzinfo=ZoneInfo('Europe/Amsterdam'))
|
|
configure_fasting(
|
|
self.user, enabled=True, fasting_start_time=time(20),
|
|
fasting_duration_minutes=16 * 60, now=self.at(13),
|
|
)
|
|
|
|
@patch('planner.services.fasting_notifications.send_notification', return_value=True)
|
|
def test_each_phase_is_sent_once(self, sender):
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(19, 59)), 0)
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 1)
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 0)
|
|
self.assertEqual(notify_fasting_phase_changes(datetime(2026, 10, 4, 12, tzinfo=ZoneInfo('Europe/Amsterdam'))), 1)
|
|
self.assertEqual(sender.call_count, 2)
|
|
self.assertEqual(sender.call_args.args[1], 'Eating window started')
|
|
|
|
@patch('planner.services.fasting_notifications.send_notification', side_effect=[NotificationError('failed'), True])
|
|
def test_delivery_failure_is_retried(self, sender):
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 1)
|
|
self.assertEqual(sender.call_count, 2)
|
|
|
|
@patch('planner.services.fasting_notifications.send_notification', return_value=True)
|
|
def test_paused_tracking_and_schedule_changes_do_not_send_old_transition(self, sender):
|
|
configure_fasting(
|
|
self.user, enabled=False, fasting_start_time=time(20),
|
|
fasting_duration_minutes=16 * 60, now=self.at(19),
|
|
)
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
|
|
configure_fasting(
|
|
self.user, enabled=True, fasting_start_time=time(20),
|
|
fasting_duration_minutes=16 * 60, now=self.at(21),
|
|
)
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(21, 1)), 0)
|
|
sender.assert_not_called()
|
|
|
|
@patch('planner.services.fasting_notifications.send_notification', return_value=False)
|
|
def test_disabled_ntfy_does_not_queue_old_phase_for_later(self, sender):
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
|
|
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 0)
|
|
self.assertEqual(sender.call_count, 1)
|
|
self.assertEqual(FastingSettings.objects.get(user=self.user).last_phase_notification_at, self.at(20))
|