tests.py 8.91 KB
Newer Older
1 2 3 4 5 6
"""
Unit tests for integration of the django-user-tasks app and its REST API.
"""

from __future__ import absolute_import, print_function, unicode_literals

bmedx committed
7
import logging
8
from uuid import uuid4
9

10 11
import mock
from boto.exception import NoAuthHandlerFound
12
from django.conf import settings
13
from django.contrib.auth.models import User
14
from django.core import mail
15 16
from django.core.urlresolvers import reverse
from django.test import override_settings
17
from rest_framework.test import APITestCase
18 19
from user_tasks.models import UserTaskArtifact, UserTaskStatus
from user_tasks.serializers import ArtifactSerializer, StatusSerializer
20

21
from .signals import user_task_stopped
22 23


bmedx committed
24
class MockLoggingHandler(logging.Handler):
bmedx committed
25 26 27
    """
    Mock logging handler to help check for logging statements
    """
bmedx committed
28 29 30 31 32
    def __init__(self, *args, **kwargs):
        self.reset()
        logging.Handler.__init__(self, *args, **kwargs)

    def emit(self, record):
bmedx committed
33 34 35
        """
        Override to catch messages and store them messages in our internal dicts
        """
bmedx committed
36 37 38
        self.messages[record.levelname.lower()].append(record.getMessage())

    def reset(self):
bmedx committed
39 40 41
        """
        Clear out all messages, also called to initially populate messages dict
        """
bmedx committed
42 43 44 45 46 47 48 49
        self.messages = {
            'debug': [],
            'info': [],
            'warning': [],
            'error': [],
            'critical': [],
        }

50

bmedx committed
51
# Helper functions for stuff that pylint complains about without disable comments
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
def _context(response):
    """
    Get a context dictionary for a serializer appropriate for the given response.
    """
    return {'request': response.wsgi_request}  # pylint: disable=no-member


def _data(response):
    """
    Get the serialized data dictionary from the given REST API test response.
    """
    return response.data  # pylint: disable=no-member


@override_settings(BROKER_URL='memory://localhost/')
class TestUserTasks(APITestCase):
    """
    Tests of the django-user-tasks REST API endpoints.

    Detailed tests of the default authorization rules are in the django-user-tasks code.
    These tests just verify that the API is exposed and functioning.
    """

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('test_user', 'test@example.com', 'password')
        cls.status = UserTaskStatus.objects.create(
            user=cls.user, task_id=str(uuid4()), task_class='test_rest_api.sample_task', name='SampleTask 2',
            total_steps=5)
        cls.artifact = UserTaskArtifact.objects.create(status=cls.status, text='Lorem ipsum')

    def setUp(self):
        super(TestUserTasks, self).setUp()
        self.status.refresh_from_db()
        self.client.force_authenticate(self.user)  # pylint: disable=no-member

    def test_artifact_detail(self):
        """
        Users should be able to access artifacts for tasks they triggered.
        """
        response = self.client.get(reverse('usertaskartifact-detail', args=[self.artifact.uuid]))
        assert response.status_code == 200
        serializer = ArtifactSerializer(self.artifact, context=_context(response))
        assert _data(response) == serializer.data

    def test_artifact_list(self):
        """
        Users should be able to access a list of their tasks' artifacts.
        """
        response = self.client.get(reverse('usertaskartifact-list'))
        assert response.status_code == 200
        serializer = ArtifactSerializer(self.artifact, context=_context(response))
        assert _data(response)['results'] == [serializer.data]

    def test_status_cancel(self):
        """
        Users should be able to cancel tasks they no longer wish to complete.
        """
        response = self.client.post(reverse('usertaskstatus-cancel', args=[self.status.uuid]))
        assert response.status_code == 200
        self.status.refresh_from_db()
        assert self.status.state == UserTaskStatus.CANCELED

    def test_status_delete(self):
        """
        Users should be able to delete their own task status records when they're done with them.
        """
        response = self.client.delete(reverse('usertaskstatus-detail', args=[self.status.uuid]))
        assert response.status_code == 204
        assert not UserTaskStatus.objects.filter(pk=self.status.id).exists()

    def test_status_detail(self):
        """
        Users should be able to access status records for tasks they triggered.
        """
        response = self.client.get(reverse('usertaskstatus-detail', args=[self.status.uuid]))
        assert response.status_code == 200
        serializer = StatusSerializer(self.status, context=_context(response))
        assert _data(response) == serializer.data

    def test_status_list(self):
        """
        Users should be able to access a list of their tasks' status records.
        """
        response = self.client.get(reverse('usertaskstatus-list'))
        assert response.status_code == 200
        serializer = StatusSerializer([self.status], context=_context(response), many=True)
        assert _data(response)['results'] == serializer.data
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172


@override_settings(BROKER_URL='memory://localhost/')
class TestUserTaskStopped(APITestCase):
    """
    Tests of the django-user-tasks signal handling and email integration.
    """

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('test_user', 'test@example.com', 'password')
        cls.status = UserTaskStatus.objects.create(
            user=cls.user, task_id=str(uuid4()), task_class='test_rest_api.sample_task', name='SampleTask 2',
            total_steps=5)

    def setUp(self):
        super(TestUserTaskStopped, self).setUp()
        self.status.refresh_from_db()
        self.client.force_authenticate(self.user)  # pylint: disable=no-member

    def test_email_sent_with_site(self):
        """
        Check the signal receiver and email sending.
        """
        UserTaskArtifact.objects.create(
            status=self.status, name='BASE_URL', url='https://test.edx.org/'
        )
        user_task_stopped.send(sender=UserTaskStatus, status=self.status)

        subject = "{platform_name} {studio_name}: Task Status Update".format(
            platform_name=settings.PLATFORM_NAME, studio_name=settings.STUDIO_NAME
        )
        body_fragments = [
173
            "Your {task_name} task has completed with the status".format(task_name=self.status.name.lower()),
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            "https://test.edx.org/",
            reverse('usertaskstatus-detail', args=[self.status.uuid])
        ]

        self.assertEqual(len(mail.outbox), 1)

        msg = mail.outbox[0]

        self.assertEqual(msg.subject, subject)
        for fragment in body_fragments:
            self.assertIn(fragment, msg.body)

    def test_email_not_sent_for_child(self):
        """
        No email should be send for child tasks in chords, chains, etc.
        """
        child_status = UserTaskStatus.objects.create(
            user=self.user, task_id=str(uuid4()), task_class='test_rest_api.sample_task', name='SampleTask 2',
            total_steps=5, parent=self.status)
        user_task_stopped.send(sender=UserTaskStatus, status=child_status)
        self.assertEqual(len(mail.outbox), 0)

    def test_email_sent_without_site(self):
        """
        Make sure we send a generic email if the BASE_URL artifact doesn't exist
        """
        user_task_stopped.send(sender=UserTaskStatus, status=self.status)

        subject = "{platform_name} {studio_name}: Task Status Update".format(
            platform_name=settings.PLATFORM_NAME, studio_name=settings.STUDIO_NAME
        )
        fragments = [
206
            "Your {task_name} task has completed with the status".format(task_name=self.status.name.lower()),
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
            "Sign in to view the details of your task or download any files created."
        ]

        self.assertEqual(len(mail.outbox), 1)

        msg = mail.outbox[0]
        self.assertEqual(msg.subject, subject)

        for fragment in fragments:
            self.assertIn(fragment, msg.body)

    def test_email_retries(self):
        """
        Make sure we can succeed on retries
        """
        with mock.patch('django.core.mail.send_mail') as mock_exception:
            mock_exception.side_effect = NoAuthHandlerFound()

            with mock.patch('cms_user_tasks.tasks.send_task_complete_email.retry') as mock_retry:
                user_task_stopped.send(sender=UserTaskStatus, status=self.status)
                self.assertTrue(mock_retry.called)
bmedx committed
228 229 230 231 232 233 234 235 236 237 238

    def test_queue_email_failure(self):
        logger = logging.getLogger("cms_user_tasks.signals")
        hdlr = MockLoggingHandler(level="DEBUG")
        logger.addHandler(hdlr)

        with mock.patch('cms_user_tasks.tasks.send_task_complete_email.delay') as mock_delay:
            mock_delay.side_effect = NoAuthHandlerFound()
            user_task_stopped.send(sender=UserTaskStatus, status=self.status)
            self.assertTrue(mock_delay.called)
            self.assertEqual(hdlr.messages['error'][0], u'Unable to queue send_task_complete_email')