50 lines
2.4 KiB
Python
50 lines
2.4 KiB
Python
from unittest.mock import Mock, patch
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.test import TestCase
|
|
from django.urls import reverse
|
|
|
|
from .models import UserSettings
|
|
from .services.notifications import NotificationError, send_notification
|
|
|
|
|
|
class NtfySettingsTests(TestCase):
|
|
def setUp(self):
|
|
self.user = get_user_model().objects.create_user(username='ntfy-user', password='test-password')
|
|
self.client.force_login(self.user)
|
|
self.settings_url = reverse('planner:user-settings')
|
|
self.test_url = reverse('planner:ntfy-test')
|
|
self.topic = 'https://ntfy.example.com/private-topic'
|
|
|
|
def save(self, url=None, enabled=True):
|
|
return self.client.post(self.settings_url, {
|
|
'section': 'ntfy', 'ntfy_url': self.topic if url is None else url,
|
|
'ntfy_enabled': 'on' if enabled else '',
|
|
})
|
|
|
|
def test_enable_requires_successful_test(self):
|
|
response = self.save()
|
|
self.assertContains(response, 'Test this URL successfully')
|
|
self.assertFalse(UserSettings.objects.get(user=self.user).ntfy_enabled)
|
|
|
|
@patch('planner.views.send_ntfy_notification')
|
|
def test_successful_test_allows_enable_and_changed_url_requires_retest(self, sender):
|
|
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': 'invalid'}).status_code, 400)
|
|
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': self.topic}).status_code, 200)
|
|
sender.assert_called_once()
|
|
self.assertEqual(self.save().status_code, 302)
|
|
preferences = UserSettings.objects.get(user=self.user)
|
|
self.assertTrue(preferences.ntfy_enabled)
|
|
self.assertIsNotNone(preferences.ntfy_last_tested_at)
|
|
self.assertContains(self.save(url='https://ntfy.example.com/other'), 'Test this URL successfully')
|
|
|
|
@patch('planner.views.send_ntfy_notification', side_effect=NotificationError('Could not connect.'))
|
|
def test_failed_test_does_not_allow_enable(self, sender):
|
|
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': self.topic}).status_code, 502)
|
|
self.assertContains(self.save(), 'Test this URL successfully')
|
|
|
|
@patch('planner.services.notifications.send_ntfy_notification')
|
|
def test_disabled_preference_suppresses_delivery(self, sender):
|
|
self.assertFalse(send_notification(self.user, 'Title', 'Message'))
|
|
sender.assert_not_called()
|