~netlandish/django-wiki

aa5f0564cf99730899342eb1bc6bdaf67699b80f — Mads Jensen 5 years ago d3f4342
Added some tests for notifications plugin.
M .gitignore => .gitignore +1 -0
@@ 43,6 43,7 @@ pip-log.txt
htmlcov
.tox
.cache
htmlcov

#Eclipse
.project

M src/wiki/plugins/notifications/forms.py => src/wiki/plugins/notifications/forms.py +15 -18
@@ 1,3 1,5 @@
import pdb

from django import forms
from django.contrib.contenttypes.models import ContentType
from django.forms.models import BaseModelFormSet, modelformset_factory


@@ 38,8 40,7 @@ class SettingsModelForm(forms.ModelForm):
        if instance:
            self.__editing_instance = True
            self.fields['delete_subscriptions'] = ArticleSubscriptionModelMultipleChoiceField(
                models.ArticleSubscription.objects.filter(
                    subscription__settings=instance),
                models.ArticleSubscription.objects.filter(subscription__settings=instance),
                label=gettext("Remove subscriptions"),
                required=False,
                help_text=gettext("Select article subscriptions to remove from notifications"),


@@ 117,11 118,12 @@ class SubscriptionForm(PluginSettingsFormMixin, forms.Form):
        widget=forms.CheckboxInput(
            attrs={
                'onclick':
                mark_safe(
                    "$('#id_edit').attr('checked', $(this).is(':checked'));")}))
                mark_safe("$('#id_edit').attr('checked', $(this).is(':checked'));")
            }
        )
    )

    def __init__(self, article, request, *args, **kwargs):

        self.article = article
        self.user = request.user
        initial = kwargs.pop('initial', None)


@@ 140,11 142,8 @@ class SubscriptionForm(PluginSettingsFormMixin, forms.Form):
                0].subscription.settings
        if not initial:
            initial = {
                'edit': bool(
                    self.edit_notifications),
                'edit_email': bool(
                    self.edit_notifications.filter(
                        subscription__send_emails=True)),
                'edit': bool(self.edit_notifications),
                'edit_email': bool(self.edit_notifications.filter(subscription__send_emails=True)),
                'settings': self.default_settings,
            }
        kwargs['initial'] = initial


@@ 161,30 160,28 @@ class SubscriptionForm(PluginSettingsFormMixin, forms.Form):
                'Your notification settings were unchanged, so nothing saved.')

    def save(self, *args, **kwargs):

        cd = self.cleaned_data
        if not self.changed_data:
            return
        if cd['edit']:
        if self.cleaned_data['edit']:
            try:
                edit_notification = models.ArticleSubscription.objects.get(
                    subscription__notification_type=self.notification_type,
                    article=self.article,
                    subscription__settings=cd['settings'],
                    subscription__settings=self.cleaned_data['settings'],
                )
                edit_notification.subscription.send_emails = cd['edit_email']
                edit_notification.subscription.send_emails = self.cleaned_data['edit_email']
                edit_notification.subscription.save()
            except models.ArticleSubscription.DoesNotExist:
                subscription, __ = Subscription.objects.get_or_create(
                    settings=cd['settings'],
                    settings=self.cleaned_data['settings'],
                    notification_type=self.notification_type,
                    object_id=self.article.id,
                )
                edit_notification = models.ArticleSubscription.objects.create(
                models.ArticleSubscription.objects.create(
                    subscription=subscription,
                    article=self.article,
                )
                subscription.send_emails = cd['edit_email']
                subscription.send_emails = self.cleaned_data['edit_email']
                subscription.save()

        else:

M src/wiki/plugins/notifications/models.py => src/wiki/plugins/notifications/models.py +4 -9
@@ 88,24 88,19 @@ for plugin in registry.get_plugins():
        def plugin_notification(instance, **kwargs):
            if notification_dict.get('ignore', lambda x: False)(instance):
                return
            if kwargs.get(
                    'created',
                    False) == notification_dict.get(
                    'created',
                    True):
                url = None
            if kwargs.get('created', False) == notification_dict.get('created', True):
                if 'get_url' in notification_dict:
                    url = notification_dict['get_url'](instance)
                else:
                    url = default_url(
                        notification_dict['get_article'](instance))
                    url = default_url(notification_dict['get_article'](instance))

                message = notification_dict['message'](instance)
                notify(
                    message,
                    notification_dict['key'],
                    target_object=notification_dict['get_article'](instance),
                    url=url)
                    url=url,
                )

        signals.post_save.connect(
            plugin_notification,

M src/wiki/plugins/notifications/views.py => src/wiki/plugins/notifications/views.py +1 -7
@@ 46,14 46,8 @@ class NotificationSettings(FormView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if 'form' not in context:
            context['form'] = self.get_form()
        context['formset'] = context['form']
        for form in context['formset']:
            if form.instance:
                setattr(
                    form.instance,
                    'articlesubscriptions',
                    self.get_article_subscriptions(form.instance)
                )
                form.instance.articlesubscriptions = self.get_article_subscriptions(form.instance)
        return context

A tests/plugins/notifications/__init__.py => tests/plugins/notifications/__init__.py +0 -0
A tests/plugins/notifications/test_forms.py => tests/plugins/notifications/test_forms.py +11 -0
@@ 0,0 1,11 @@
from django.test import TestCase
from django_nyt.forms import SettingsForm

from tests.base import RequireSuperuserMixin
from wiki.plugins.notifications.forms import SettingsFormSet


class SettingsFormTests(RequireSuperuserMixin, TestCase):
    def test_formset(self):
        formset = SettingsFormSet(user=self.superuser1)


A tests/plugins/notifications/test_views.py => tests/plugins/notifications/test_views.py +43 -0
@@ 0,0 1,43 @@
from django.shortcuts import resolve_url

from tests.base import RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase


class NotificationSettingsTests(RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase):

    def test_login_required(self):
        self.client.logout()
        response = self.client.get(resolve_url('wiki:notification_settings'))
        self.assertEqual(response.status_code, 302)

    def test_when_logged_in(self):
        response = self.client.get(resolve_url('wiki:notification_settings'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wiki/plugins/notifications/settings.html')

    def test_change_settings(self):
        url = resolve_url('wiki:notification_settings')

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        data = {'csrf_token': response.context['csrf_token']}

        # management form information, needed because of the formset
        management_form = response.context['form'].management_form
        for i in 'TOTAL_FORMS', 'INITIAL_FORMS', 'MIN_NUM_FORMS', 'MAX_NUM_FORMS':
            data['%s-%s' % (management_form.prefix, i)] = management_form[i].value()

        for i in range(response.context['form'].total_form_count()):
            # get form index 'i'
            current_form = response.context['form'].forms[i]

            # retrieve all the fields
            for field_name in current_form.fields:
                value = current_form[field_name].value()
                data['%s-%s' % (current_form.prefix, field_name)] = value if value is not None else ''

        data['form-TOTAL_FORMS'] = 1
        data['form-0-email'] = 2
        # post the request without any change
        response = self.client.post(url, data)
        self.root_article.refresh_from_db()