def test_bulk_delete_participation(self) -> None:
        self.set_tenant(0)

        user = self.users[0]
        first_contact = Contact.objects.create(email='*****@*****.**', first_name='First', last_name='Smith')
        second_contact = Contact.objects.create(email='*****@*****.**', first_name='Second', last_name='Smith')

        campaign = Campaign.objects.create(name='cool campaign', owner=user)

        Participation.objects.bulk_create([
            Participation(campaign=campaign, contact=first_contact),
            Participation(campaign=campaign, contact=second_contact),
        ])

        t_client = TenantClient(self.get_current_tenant())
        t_client.handler = ForceAuthClientHandler(enforce_csrf_checks=False)
        t_client.handler._force_user = user
        self.assertTrue(t_client.login(username=user.username, password='******'), 'Test user was not logged in')

        url = reverse.reverse('api:campaigns-contacts-list', args=[campaign.pk, ])
        with modify_settings(ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url}):
            response = t_client.delete(urljoin(url, '?contact__in=%s' % str(first_contact.id)),
                                       content_type='application/json',
                                       )

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT, str(response.content))
        participation = Participation.objects.get(campaign=campaign)
        self.assertEqual(second_contact, participation.contact)
    def test_email_stage_template_validation(self) -> None:
        self.set_tenant(0)

        user = self.users[0]

        campaign = Campaign.objects.create(name='some campaign', owner=user)
        step = Step.objects.create(campaign=campaign, start=datetime.time(9, 45), end=datetime.time(18, 30))

        t_client = TenantClient(self.get_current_tenant())
        t_client.handler = ForceAuthClientHandler(enforce_csrf_checks=False)
        t_client.handler._force_user = user
        self.assertTrue(t_client.login(username=user.username, password='******'), 'Test user was not logged in')

        url = reverse.reverse('api:campaigns-steps-email-list', args=[campaign.pk, step.pk, ])
        with modify_settings(ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url}):
            response = t_client.post(url,
                                     json.dumps(dict(
                                         subject='Hello good fellow',
                                         html_content='Some invalid email template to {{First name}}!',
                                     )),
                                     content_type='application/json',
                                     )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, str(response.content))
        error_data = response.data
        self.assertTrue("Could not parse" in error_data['html_content'][0])
    def test_bulk_post_participation(self) -> None:
        self.set_tenant(0)

        user = self.users[0]
        first_contact = Contact.objects.create(email='*****@*****.**', first_name='First', last_name='Smith')
        second_contact = Contact.objects.create(email='*****@*****.**', first_name='Second', last_name='Smith')

        campaign = Campaign.objects.create(name='cool campaign', owner=user)

        t_client = TenantClient(self.get_current_tenant())
        t_client.handler = ForceAuthClientHandler(enforce_csrf_checks=False)
        t_client.handler._force_user = user
        self.assertTrue(t_client.login(username=user.username, password='******'), 'Test user was not logged in')

        url = reverse.reverse('api:campaigns-contacts-list', args=[campaign.pk, ])
        with modify_settings(ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url}):
            response = t_client.post(url,
                                     json.dumps([
                                         dict(contact=first_contact.id),
                                         dict(contact=second_contact.id),
                                     ]),
                                     content_type='application/json',
                                     )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED, str(response.content))
        self.assertEqual(2, Participation.objects.filter(
            campaign=campaign,
            contact_id__in=(first_contact.id, second_contact.id,),
        ).count())
        contacts = campaign.contacts.all()
        self.assertListEqual([first_contact, second_contact, ], list(contacts))
    def test_contact_by_campaign_filtering(self) -> None:
        self.set_tenant(0)
        user = self.users[0]

        first_contact = Contact.objects.create(email='*****@*****.**', first_name='First', last_name='Smith')
        second_contact = Contact.objects.create(email='*****@*****.**', first_name='Second', last_name='Smith')
        Contact.objects.create(email='*****@*****.**', first_name='Third', last_name='Smith')
        fourth_contact = Contact.objects.create(email='*****@*****.**', first_name='Fourth', last_name='Smith')

        first_campaign = Campaign.objects.create(name='first campaign for filtering test', owner=user)
        second_campaign = Campaign.objects.create(name='second campaign for filtering test', owner=user)

        Participation.objects.bulk_create([
            Participation(campaign=first_campaign, contact=first_contact),
            Participation(campaign=second_campaign, contact=second_contact),
            Participation(campaign=first_campaign, contact=fourth_contact),
            Participation(campaign=second_campaign, contact=fourth_contact),
        ])

        t_client = TenantClient(self.get_current_tenant())
        t_client.handler = ForceAuthClientHandler(enforce_csrf_checks=False)
        t_client.handler._force_user = user
        self.assertTrue(t_client.login(username=user.username, password='******'), 'Test user was not logged in')

        url = reverse.reverse('api:contacts-list')
        with modify_settings(ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url}):
            query = '?campaigns__in=%s' % ','.join(map(str, [first_campaign.id, second_campaign.id]))
            response = t_client.get(urljoin(url, query))

        self.assertEqual(response.status_code, status.HTTP_200_OK, str(response.content))
        contacts_data = response.data
        self.assertEqual(3, len(contacts_data))
        self.assertSetEqual({first_contact.id, second_contact.id, fourth_contact.id},
                            {c['id'] for c in contacts_data})

        with modify_settings(ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url}):
            query = '?campaigns=' + ','.join(map(str, [first_campaign.id, second_campaign.id]))
            response = t_client.get(urljoin(url, query))

        self.assertEqual(response.status_code, status.HTTP_200_OK, str(response.content))
        contacts_data = response.data
        self.assertEqual(1, len(contacts_data))
        self.assertEqual(fourth_contact.id, contacts_data[0]['id'])

        with modify_settings(ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url}):
            query = '?campaigns=%s' % second_campaign.id
            response = t_client.get(urljoin(url, query))

        self.assertEqual(response.status_code, status.HTTP_200_OK, str(response.content))
        contacts_data = response.data
        self.assertEqual(1, len(contacts_data))
        self.assertEqual(second_contact.id, contacts_data[0]['id'])
Exemplo n.º 5
0
class PrimaryViewTests(ViewTestUtilsMixin, TenantTestCase):
    def test_initial_map_generated_on_first_view(self):
        # shouldn't be any maps from the start
        self.assertFalse(CytoScape.objects.exists())

        # log in anoyone
        self.client = TenantClient(self.tenant)
        anyone = User.objects.create_user('anyone', password="******")
        success = self.client.login(username=anyone.username,
                                    password="******")
        self.assertTrue(success)

        # Access the primary map view
        self.assert200('djcytoscape:primary')

        # Should have generated the "Main" map
        self.assertEqual(CytoScape.objects.count(), 1)
        self.assertTrue(CytoScape.objects.filter(name="Main").exists())
Exemplo n.º 6
0
class StudentProfileTestView(StudentProfileViewsTest):
    def setUp(self):
        self.c = TenantClient(self.tenant)
        self.factory = RequestFactory()

    def test_student_list_view(self):
        request = self.factory.get('/account/student/')
        response = self.c.get('/account/student/')
        self.assertEqual(response.status_code,
                         403)  # forbidden for user in group student

    def test_student_detail_view(self):
        request = self.factory.get('/account/student/1/detail/')
        respnonse = self.c.login('/account/student/1/detail/')
        self.assertEqual(response.status_code, 403)

    def test_student_register_view(self):
        # data = {
        #     'user':cls.user,
        #     'photo':'img.jpg',
        # }
        response = self.c.get('/account/student/register/')
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.template, 'account/students/list.html')

        # with self.assertTemplateUsed('solos/solo_detail.html'):
        #     response.render()
        # response = StudentListView.as_view()(
        #     request,
        #     self.user
        # # )
        # self.assertEqual(response, 200)

    def test_student_register_view(self):
        pass

    def test_student_detail_view(self):
        pass

    def test_student_update_view(self):
        pass
Exemplo n.º 7
0
    def test_unread_only_filtering(self):
        self.set_tenant(0)

        now = timezone.now()
        action = NoticeType.objects.first()
        Notification.objects.bulk_create([
            Notification(user=self.user, created=now, action=action),
            Notification(user=self.user,
                         created=now,
                         action=action,
                         read_datetime=now,
                         extra_context=dict(mark=True)),
            Notification(user=self.user, created=now, action=action),
        ])

        t_client = TenantClient(self.get_current_tenant())
        t_client.handler = ForceAuthClientHandler(enforce_csrf_checks=False)
        t_client.handler._force_user = self.user
        self.assertTrue(
            t_client.login(username=self.user.username, password='******'),
            'Test user was not logged in')

        url = reverse.reverse('api:notifications-list')
        with modify_settings(
                ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url
                               }):
            query = '?unread_only=true'
            response = t_client.get(urljoin(url, query))

        self.assertEqual(response.status_code, status.HTTP_200_OK,
                         str(response.content))
        notifications_data = response.data
        self.assertEqual(2, len(notifications_data))
        notifications = Notification.objects.filter(
            extra_context__isnull=True).all()
        self.assertSetEqual({n.id
                             for n in notifications},
                            {n['id']
                             for n in notifications_data})
Exemplo n.º 8
0
    def test_bulk_delete_with_filtering(self) -> None:
        self.set_tenant(0)

        first_contact = Contact.objects.create(email='*****@*****.**',
                                               first_name='First',
                                               last_name='Smith')
        second_contact = Contact.objects.create(email='*****@*****.**',
                                                first_name='Second',
                                                last_name='Smith')
        third_contact = Contact.objects.create(email='*****@*****.**',
                                               first_name='Third',
                                               last_name='Smith')

        t_client = TenantClient(self.get_current_tenant())
        t_client.handler = ForceAuthClientHandler(enforce_csrf_checks=False)
        t_client.handler._force_user = self.user
        self.assertTrue(
            t_client.login(username=self.user.username, password='******'),
            'Test user was not logged in')

        ids_for_delete = [
            first_contact.id,
            third_contact.id,
        ]
        url = reverse.reverse('api:contacts-list')
        with modify_settings(
                ALLOWED_HOSTS={'append': self.get_current_tenant().domain_url
                               }):
            response = t_client.delete(
                urljoin(
                    url,
                    '?id__in=%s' % ','.join(str(pk) for pk in ids_for_delete)))

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT,
                         str(response.content))
        self.assertFalse(
            Contact.objects.filter(id__in=ids_for_delete).exists())
        self.assertTrue(Contact.objects.filter(id=second_contact.id).exists())
Exemplo n.º 9
0
class BaseTest(FastTenantTestCase, TestCase):
    """
    Clase base para las pruebas unitarias.
    """

    MSJ_OBLIGATORIO = 'Este campo es obligatorio.'
    user_factory = UsuarioFactory

    def _pre_setup(self):
        super()._pre_setup()
        self.client = TenantClient(self.tenant)

    def assertRedirects(self, response, expected_url, *args, **kwargs):
        """
        Se sobreescribe metodo para setear el host del tenant por defecto.
        """

        super().assertRedirects(response, expected_url, host=self.tenant.domain_url)

    def crear_arbol(self):
        """
        Crea un arbol para realizar las pruebas. Se muestra el arbol segun los ids de los grupos.

                 100
            |-----|-----|
            |     |     |
           200   300   400
                  |     |
                  |    700
                  |
             |---------|
            500       800
             |
            600
        """

        padre = GrupoRaizFactory(id=100)
        cabeza_red1 = GrupoFactory(id=200, parent=padre, red__nombre='matrimonio')
        cabeza_red2 = GrupoFactory(id=300, parent=padre)
        cabeza_red3 = GrupoFactory(id=400, parent=padre, red__nombre='adultos')

        hijo1_cb2 = GrupoHijoFactory(id=500, parent=cabeza_red2)
        hijo2_cb2 = GrupoHijoFactory(id=800, parent=cabeza_red2)
        hijo11_cb2 = GrupoHijoFactory(id=600, parent=hijo1_cb2)

        hijo1_cb3 = GrupoHijoFactory(id=700, parent=cabeza_red3)

        self.lista_arbol_completo = [
            padre, [cabeza_red1, cabeza_red2, [hijo1_cb2, [hijo11_cb2], hijo2_cb2], cabeza_red3, [hijo1_cb3]]
        ]

        self.lista_arbol_cb2 = [
            cabeza_red2, [hijo1_cb2, [hijo11_cb2], hijo2_cb2]
        ]

    def login_usuario(self, usuario):
        """
        Permite loguear un usuario.
        """

        self.client.login(email=usuario.email, password='******')
Exemplo n.º 10
0
class AnnouncementViewTests(ViewTestUtilsMixin, TenantTestCase):
    def setUp(self):
        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.client = TenantClient(self.tenant)

        self.test_password = "******"
        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)
        self.test_student2 = baker.make(User)

        self.test_announcement = baker.make(Announcement, draft=False)
        self.ann_pk = self.test_announcement.pk

    def test_all_announcement_page_status_codes_for_anonymous(self):
        ''' If not logged in then all views should redirect to home page or admin  '''

        # go home
        self.assertRedirectsLogin('announcements:list')
        self.assertRedirectsLogin('announcements:list2')
        self.assertRedirectsLogin('announcements:comment', args=[1])
        self.assertRedirectsLogin('announcements:list', args=[1])

        # go admin
        self.assertRedirectsAdmin('announcements:create')
        self.assertRedirectsAdmin('announcements:delete', args=[1])
        self.assertRedirectsAdmin('announcements:update', args=[1])
        self.assertRedirectsAdmin('announcements:copy', args=[1])
        self.assertRedirectsAdmin('announcements:publish', args=[1])

    def test_all_announcement_page_status_codes_for_students(self):
        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # all_fields = self.test_announcement._meta.get_fields()
        # for field in all_fields:
        #     print(field, getattr(self.test_announcement, field.name))

        # students should have access to these:
        self.assertEqual(
            self.client.get(reverse('announcements:list')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('announcements:list2')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('announcements:list',
                                    args=[self.ann_pk])).status_code, 200)

        # Announcement from setup() should appear in the list
        self.assertContains(self.client.get(reverse('announcements:list')),
                            self.test_announcement.title)

        comment_response_get = self.client.get(
            reverse('announcements:comment', args=[self.ann_pk]))
        self.assertEqual(comment_response_get.status_code,
                         404)  # Comments via POST only

        # Posting a comment redirects to the announcement commented on
        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:comment', args=[self.ann_pk])),
            expected_url=reverse('announcements:list', args=[self.ann_pk]),
        )

        # These views should redirect to admin login
        self.assertRedirectsAdmin('announcements:create')
        self.assertRedirectsAdmin('announcements:delete', args=[1])
        self.assertRedirectsAdmin('announcements:update', args=[1])
        self.assertRedirectsAdmin('announcements:copy', args=[1])
        self.assertRedirectsAdmin('announcements:publish', args=[1])

    def test_all_announcement_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        self.assert200('announcements:list')
        self.assert200('announcements:list2')
        self.assert200('announcements:list', args=[self.ann_pk])

        # Announcement from setup() should appear in the list
        self.assertContains(self.client.get(reverse('announcements:list')),
                            self.test_announcement.title)

        comment_response_get = self.client.get(
            reverse('announcements:comment', args=[self.ann_pk]))
        self.assertEqual(comment_response_get.status_code,
                         404)  # Comments via POST only

        # Posting a comment redirects to the announcement commented on
        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:comment', args=[self.ann_pk])),
            expected_url=reverse('announcements:list', args=[self.ann_pk]),
        )

        # These staff views should work
        self.assert200('announcements:create')
        self.assert200('announcements:update', args=[self.ann_pk])
        self.assert200('announcements:copy', args=[self.ann_pk])
        self.assert200('announcements:delete', args=[self.ann_pk])

        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:publish', args=[self.ann_pk])),
            expected_url=reverse('announcements:list', args=[self.ann_pk]),
        )

    def test_draft_announcement(self):
        draft_announcement = baker.make(Announcement)  # default is draft
        self.assertTrue(draft_announcement.draft)

        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # Students shoudn't see draft announcements in the list
        self.assertNotContains(self.client.get(reverse('announcements:list')),
                               draft_announcement.title)

        # set draft to false
        draft_announcement.draft = False
        draft_announcement.save()

        # Student can now see it
        self.assertContains(self.client.get(reverse('announcements:list')),
                            draft_announcement.title)

    # @patch('announcements.views.publish_announcement.apply_async')
    def test_publish_announcement(self):
        draft_announcement = baker.make(Announcement)

        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # draft announcement should appear with a link to publish it.  TODO This is crude, should be checking HTML?
        publish_link = reverse('announcements:publish',
                               args=[draft_announcement.pk])
        self.assertContains(self.client.get(reverse('announcements:list')),
                            publish_link)

        # publish the announcement
        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:publish',
                        args=[draft_announcement.pk])),
            expected_url=reverse('announcements:list',
                                 args=[draft_announcement.pk]),
        )

        # Should probably mock the task in above code, but don't know how...
        # Fake mock...?
        draft_announcement.draft = False
        draft_announcement.save()

        # publish link for this announcement should no longer appear in the list:
        self.assertNotContains(self.client.get(reverse('announcements:list')),
                               publish_link)

    def test_create_announcement_from_past_date_auto_publish(self):
        draft_announcement = baker.make(
            Announcement,
            datetime_released=timezone.now() - timedelta(days=3),
            auto_publish=True,
        )
        form = AnnouncementForm(data=model_to_dict(draft_announcement))
        self.assertFalse(form.is_valid())

    def test_comment_on_announcement_by_student(self):
        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        form_data = {
            'comment_text': "test comment",
        }
        response = self.client.post(
            reverse('announcements:comment', args=[self.test_announcement.id]),
            form_data)
        self.assertEqual(response.status_code, 404)  # invalid submit button

        # make sure it was submitted with the 'comment_button'
        form_data['comment_button'] = True
        response = self.client.post(reverse('announcements:comment',
                                            args=[self.test_announcement.id]),
                                    data=form_data)

        # Empty comment strings should be replaced with blank string or we get an error
        # WHY? THIS SEEMS SILLY! THE FORM SHOULDN'T VALIDATE IF THERE IS NO COMMENT!
        # Old code not relevant any more?
        # form_data['comment_text'] = None
        # response = self.client.post(
        #     reverse('announcements:comment', args=[self.test_announcement.id]),
        #     data=form_data
        # )
        # self.assertRedirects(response, self.test_announcement.get_absolute_url())

    def test_copy_announcement(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # hit the view as a get request first, to load a copy of the announcement in the form
        response = self.client.get(
            reverse('announcements:copy', args=[self.test_announcement.id]), )
        self.assertEqual(response.status_code, 200)

        # Don't know how to get the form data from the get request...
        # https://stackoverflow.com/questions/61532873/how-to-plug-the-reponse-of-a-django-view-get-request-into-the-same-view-as-a-pos

        # So, instead we'll manually create valid form data for post request:
        form_data = {
            'title': "Copy test",
            'content': "test content",
            'datetime_released':
            "2006-10-25 14:30:59"  # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-DATETIME_INPUT_FORMATS
        }

        response = self.client.post(reverse('announcements:copy',
                                            args=[self.test_announcement.id]),
                                    data=form_data)

        # Get the newest announcement
        new_ann = Announcement.objects.latest('datetime_created')
        self.assertEqual(new_ann.title, "Copy test")
        # if successful, should redirect to the new announcement
        self.assertRedirects(response, new_ann.get_absolute_url())
Exemplo n.º 11
0
class SubmissionViewTests(TenantTestCase):

    # includes some basic model data
    # fixtures = ['initial_data.json']

    def setUp(self):
        self.client = TenantClient(self.tenant)
        User = get_user_model()

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user('test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user('test_student', password=self.test_password)
        self.test_student2 = mommy.make(User)

        self.quest1 = mommy.make(Quest)
        self.quest2 = mommy.make(Quest)

        self.sub1 = mommy.make(QuestSubmission, user=self.test_student1, quest=self.quest1)
        self.sub2 = mommy.make(QuestSubmission, quest=self.quest1)
        self.sub3 = mommy.make(QuestSubmission, quest=self.quest2)

    def test_all_submission_page_status_codes_for_students(self):
        # log in a student
        success = self.client.login(username=self.test_student1.username, password=self.test_password)
        self.assertTrue(success)

        s1_pk = self.sub1.pk
        s2_pk = self.sub2.pk

        # Student's own submission
        self.assertEqual(self.client.get(reverse('quests:submission', args=[s1_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:drop', args=[s1_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:submission_past', args=[s1_pk])).status_code, 200)

        # Students shouldn't have access to these
        self.assertEqual(self.client.get(reverse('quests:flagged')).status_code, 302)

        # Student's own submission
        self.assertEqual(self.client.get(reverse('quests:skip', args=[s1_pk])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:approve', args=[s1_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:submission_past', args=[s1_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:flag', args=[s1_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:unflag', args=[s1_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:complete', args=[s1_pk])).status_code, 404)

        # Not this student's submission
        self.assertEqual(self.client.get(reverse('quests:submission', args=[s2_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:drop', args=[s2_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:skip', args=[s2_pk])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:submission_past', args=[s2_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:complete', args=[s2_pk])).status_code, 404)

        # Non existent submissions
        self.assertEqual(self.client.get(reverse('quests:submission', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:drop', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:skip', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:submission_past', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:complete', args=[0])).status_code, 404)

        # These Needs to be completed via POST
        self.assertEqual(self.client.get(reverse('quests:complete', args=[s1_pk])).status_code, 404)

    def test_all_submission_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username, password=self.test_password)
        self.assertTrue(success)

        s1_pk = self.sub1.pk
        # s2_pk = self.sub2.pk

        self.assertEqual(self.client.get(reverse('quests:flagged')).status_code, 200)

        # View it
        self.assertEqual(self.client.get(reverse('quests:submission', args=[s1_pk])).status_code, 200)
        # Flag it
        # self.assertEqual(self.client.get(reverse('quests:flag', args=[s1_pk])).status_code, 200)
        self.assertRedirects(
            response=self.client.get(reverse('quests:flag', args=[s1_pk])),
            expected_url=reverse('quests:approvals'),
        )
        # TODO Why does this fail? Why is self.sub1.flagged_by == None
        # self.assertEqual(self.sub1.flagged_by, self.test_teacher)

        # Unflag it
        self.assertRedirects(
            response=self.client.get(reverse('quests:unflag', args=[s1_pk])),
            expected_url=reverse('quests:approvals'),
        )
        self.assertIsNone(self.sub1.flagged_by)

        # self.assertEqual(self.client.get(reverse('quests:drop', args=[s1_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:submission_past', args=[s1_pk])).status_code, 200)

        # Non existent submissions
        self.assertEqual(self.client.get(reverse('quests:submission', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:drop', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:skip', args=[0])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:submission_past', args=[0])).status_code, 404)

        # These Needs to be completed via POST
        # self.assertEqual(self.client.get(reverse('quests:complete', args=[s1_pk])).status_code, 404)
        self.assertEqual(self.client.get(reverse('quests:skip', args=[s1_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:approve', args=[s1_pk])).status_code, 404)

    def test_student_quest_completion(self):
        # self.sub1 = mommy.make(QuestSubmission, user=self.test_student1, quest=self.quest1)

        # self.assertRedirects(
        #     response=self.client.post(reverse('quests:complete', args=[self.sub1.id])),
        #     expected_url=reverse('quests:quests'),
        # )

        # TODO self.assertEqual(self.client.get(reverse('quests:complete', args=[s1_pk])).status_code, 404)
        pass

    def test_submission_when_quest_not_visible(self):
        """When a quest is hidden from students, they should still be able to to see their submission in a static way"""
        # log in a student
        success = self.client.login(username=self.test_student1.username, password=self.test_password)
        self.assertTrue(success)

        # Make quest invisible to students
        self.quest1.visible_to_students = False
        self.quest1.save()
        self.assertFalse(self.quest1.visible_to_students)

        # TODO: should redirect, not 404?
        self.assertEqual(self.client.get(reverse('quests:submission', args=[self.sub1.pk])).status_code, 404)

    def test_ajax_save_draft(self):
        # loging required for this view
        self.client.force_login(self.test_student1)
        quest = mommy.make(Quest, name="TestSaveDrafts")
        sub = mommy.make(QuestSubmission, quest=quest)
        draft_comment = "Test draft comment"
        # Send some draft data via the ajax view, which should save it.
        ajax_data = {
            'comment': draft_comment,
            'submission_id': sub.id,
        }

        response = self.client.post(
            reverse('quests:ajax_save_draft'),
            data=ajax_data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['result'], "Draft saved")

        sub.refresh_from_db()
        self.assertEqual(draft_comment, sub.draft_text)  # fAILS CUS MODEL DIDN'T SAVE! aRGH..
Exemplo n.º 12
0
class ViewTests(ViewTestUtilsMixin, TenantTestCase):
    def setUp(self):
        self.client = TenantClient(self.tenant)

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)

        self.map = baker.make('djcytoscape.CytoScape')

    def test_all_page_status_codes_for_anonymous(self):
        ''' If not logged in then all views should redirect to home page  '''

        self.assertRedirectsLogin('djcytoscape:index')

        self.assertRedirectsLogin('djcytoscape:primary')
        self.assertRedirectsLogin('djcytoscape:quest_map', args=[1])
        self.assertRedirectsLogin('djcytoscape:quest_map_personalized',
                                  args=[1, 1])
        self.assertRedirectsLogin('djcytoscape:quest_map_interlink',
                                  args=[1, 1, 1])

        self.assertRedirectsLogin('djcytoscape:list')
        self.assertRedirectsAdmin('djcytoscape:regenerate', args=[1])
        self.assertRedirectsAdmin('djcytoscape:regenerate_all')
        self.assertRedirectsAdmin('djcytoscape:generate_map',
                                  kwargs={
                                      'quest_id': 1,
                                      'scape_id': 1
                                  })
        self.assertRedirectsAdmin('djcytoscape:generate_unseeded')
        self.assertRedirectsAdmin('djcytoscape:update', args=[1])
        self.assertRedirectsAdmin('djcytoscape:delete', args=[1])

    def test_all_page_status_codes_for_students(self):
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        self.assert200('djcytoscape:index')
        self.assert200('djcytoscape:quest_map_personalized',
                       args=[self.map.id, self.test_student1.id])
        # need to build  interlinked maps to test this.  Do in own test
        # self.assert200('djcytoscape:quest_map_interlink', args=[1, 1, 1])
        self.assert200('djcytoscape:list')
        self.assert200('djcytoscape:primary')
        self.assert200('djcytoscape:quest_map', args=[self.map.id])

        self.assertRedirectsAdmin('djcytoscape:update', args=[self.map.id])
        self.assertRedirectsAdmin('djcytoscape:delete', args=[self.map.id])
        self.assertRedirectsAdmin('djcytoscape:regenerate', args=[self.map.id])
        self.assertRedirectsAdmin('djcytoscape:regenerate_all')
        self.assertRedirectsAdmin('djcytoscape:generate_map',
                                  kwargs={
                                      'quest_id': 1,
                                      'scape_id': 1
                                  })
        self.assertRedirectsAdmin('djcytoscape:generate_unseeded')

    def test_all_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        self.assert200('djcytoscape:index')
        self.assert200('djcytoscape:quest_map_personalized',
                       args=[self.map.id, self.test_student1.id])
        # need to build  interlinked maps to test this.  Do in own test
        # self.assert200('djcytoscape:quest_map_interlink', args=[1, 1, 1])
        self.assert200('djcytoscape:list')
        self.assert200('djcytoscape:primary')
        self.assert200('djcytoscape:quest_map', args=[self.map.id])

        self.assert200('djcytoscape:update', args=[self.map.id])
        self.assert200('djcytoscape:delete', args=[self.map.id])
Exemplo n.º 13
0
class AnnouncementViewTests(TenantTestCase):
    def setUp(self):
        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.client = TenantClient(self.tenant)

        self.test_password = "******"
        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)
        self.test_student2 = mommy.make(User)

        self.test_announcement = mommy.make(Announcement, draft=False)
        self.ann_pk = self.test_announcement.pk

    def assertRedirectsHome(self, url_name, args=None):
        self.assertRedirects(
            response=self.client.get(reverse(url_name, args=args)),
            expected_url='%s?next=%s' %
            (reverse('home'), reverse(url_name, args=args)),
        )

    def assertRedirectsAdmin(self, url_name, args=None):
        self.assertRedirects(
            response=self.client.get(reverse(url_name, args=args)),
            expected_url='{}?next={}'.format('/admin/login/',
                                             reverse(url_name, args=args)),
        )

    def assert200(self, url_name, args=None):
        self.assertEqual(
            self.client.get(reverse(url_name, args=args)).status_code, 200)

    def test_all_announcement_page_status_codes_for_anonymous(self):
        ''' If not logged in then all views should redirect to home page or admin  '''

        # go home
        self.assertRedirectsHome('announcements:list')
        self.assertRedirectsHome('announcements:list2')
        self.assertRedirectsHome('announcements:comment', args=[1])
        self.assertRedirectsHome('announcements:list', args=[1])

        # go admin
        self.assertRedirectsAdmin('announcements:create')
        self.assertRedirectsAdmin('announcements:delete', args=[1])
        self.assertRedirectsAdmin('announcements:update', args=[1])
        self.assertRedirectsAdmin('announcements:copy', args=[1])
        self.assertRedirectsAdmin('announcements:publish', args=[1])

    def test_all_announcement_page_status_codes_for_students(self):
        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # all_fields = self.test_announcement._meta.get_fields()
        # for field in all_fields:
        #     print(field, getattr(self.test_announcement, field.name))

        # students should have access to these:
        self.assertEqual(
            self.client.get(reverse('announcements:list')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('announcements:list2')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('announcements:list',
                                    args=[self.ann_pk])).status_code, 200)

        # Announcement from setup() should appear in the list
        self.assertContains(self.client.get(reverse('announcements:list')),
                            self.test_announcement.title)

        comment_response_get = self.client.get(
            reverse('announcements:comment', args=[self.ann_pk]))
        self.assertEqual(comment_response_get.status_code,
                         404)  # Comments via POST only

        # Posting a comment redirects to the announcement commented on
        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:comment', args=[self.ann_pk])),
            expected_url=reverse('announcements:list', args=[self.ann_pk]),
        )

        # These views should redirect to admin login
        self.assertRedirectsAdmin('announcements:create')
        self.assertRedirectsAdmin('announcements:delete', args=[1])
        self.assertRedirectsAdmin('announcements:update', args=[1])
        self.assertRedirectsAdmin('announcements:copy', args=[1])
        self.assertRedirectsAdmin('announcements:publish', args=[1])

    def test_all_announcement_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        self.assertEqual(
            self.client.get(reverse('announcements:list')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('announcements:list2')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('announcements:list',
                                    args=[self.ann_pk])).status_code, 200)

        # Announcement from setup() should appear in the list
        self.assertContains(self.client.get(reverse('announcements:list')),
                            self.test_announcement.title)

        comment_response_get = self.client.get(
            reverse('announcements:comment', args=[self.ann_pk]))
        self.assertEqual(comment_response_get.status_code,
                         404)  # Comments via POST only

        # Posting a comment redirects to the announcement commented on
        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:comment', args=[self.ann_pk])),
            expected_url=reverse('announcements:list', args=[self.ann_pk]),
        )

        # These staff views should work
        self.assert200('announcements:create')
        self.assert200('announcements:update', args=[self.ann_pk])
        self.assert200('announcements:copy', args=[self.ann_pk])
        self.assert200('announcements:delete', args=[self.ann_pk])

        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:publish', args=[self.ann_pk])),
            expected_url=reverse('announcements:list', args=[self.ann_pk]),
        )

    def test_draft_announcement(self):
        draft_announcement = mommy.make(Announcement)  # default is draft
        self.assertTrue(draft_announcement.draft)

        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # Students shoudn't see draft announcements in the list
        self.assertNotContains(self.client.get(reverse('announcements:list')),
                               draft_announcement.title)

        # set draft to false
        draft_announcement.draft = False
        draft_announcement.save()

        # Student can now see it
        self.assertContains(self.client.get(reverse('announcements:list')),
                            draft_announcement.title)

    # @patch('announcements.views.publish_announcement.apply_async')
    def test_publish_announcement(self):
        draft_announcement = mommy.make(Announcement)

        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # draft announcement should appear with a link to publish it.  TODO This is crude, should be checking HTML?
        publish_link = reverse('announcements:publish',
                               args=[draft_announcement.pk])
        self.assertContains(self.client.get(reverse('announcements:list')),
                            publish_link)

        # publish the announcement
        self.assertRedirects(
            response=self.client.post(
                reverse('announcements:publish',
                        args=[draft_announcement.pk])),
            expected_url=reverse('announcements:list',
                                 args=[draft_announcement.pk]),
        )

        # Should probably mock the task in above code, but don't know how...
        # Fake mock...?
        draft_announcement.draft = False
        draft_announcement.save()

        # publish link for this announcement should no longer appear in the list:
        self.assertNotContains(self.client.get(reverse('announcements:list')),
                               publish_link)

    def test_create_announcement_form_past_date_auto_publish(self):
        draft_announcement = mommy.make(
            Announcement,
            datetime_released=timezone.now() - timedelta(days=3),
            auto_publish=True,
        )
        form = AnnouncementForm(data=model_to_dict(draft_announcement))
        self.assertFalse(form.is_valid())
Exemplo n.º 14
0
class QuestViewTests(TenantTestCase):

    # includes some basic model data
    # fixtures = ['initial_data.json']

    def setUp(self):
        self.client = TenantClient(self.tenant)
        User = get_user_model()
        self.sem = SiteConfig.get().active_semester

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user('test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user('test_student', password=self.test_password)
        self.test_student2 = mommy.make(User)

        self.quest1 = mommy.make(Quest)
        self.quest2 = mommy.make(Quest)

        # self.sub1 = mommy.make(QuestSubmission, user=self.test_student1, quest=self.quest1)
        # self.sub2 = mommy.make(QuestSubmission, quest=self.quest1)

    def test_all_quest_page_status_codes_for_anonymous(self):
        """ If not logged in then all views should redirect to home page  """

        self.assertRedirects(
            response=self.client.get(reverse('quests:quests')),
            expected_url='%s?next=%s' % (reverse('home'), reverse('quests:quests')),
        )

    def test_all_quest_page_status_codes_for_students(self):
        # log in a student
        success = self.client.login(username=self.test_student1.username, password=self.test_password)
        self.assertTrue(success)

        q_pk = self.quest1.pk
        q2_pk = self.quest2.pk

        self.assertEqual(self.client.get(reverse('quests:quests')).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:available')).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:available2')).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:inprogress')).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:completed')).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:past')).status_code, 200)
        # anyone can view drafts if they figure out the url, but it will be blank for them
        self.assertEqual(self.client.get(reverse('quests:drafts')).status_code, 200)

        self.assertEqual(self.client.get(reverse('quests:quest_detail', args=[q_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:quest_detail', args=[q_pk])).status_code, 200)

        #  students shouldn't have access to these and should be redirected to login
        self.assertEqual(self.client.get(reverse('quests:submitted')).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:submitted_all')).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:returned')).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:approved')).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:skipped')).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:submitted_for_quest', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:returned_for_quest', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:approved_for_quest', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:approved_for_quest_all', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:skipped_for_quest', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:quest_create')).status_code, 403)
        self.assertEqual(self.client.get(reverse('quests:quest_update', args=[q_pk])).status_code, 403)

        self.assertEqual(self.client.get(reverse('quests:quest_copy', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:quest_delete', args=[q_pk])).status_code, 403)
        self.assertEqual(self.client.get(reverse('quests:start', args=[q2_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:hide', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:unhide', args=[q_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('quests:skip_for_quest', args=[q_pk])).status_code, 404)

    def test_all_quest_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username, password=self.test_password)
        self.assertTrue(success)

        s_pk = self.test_student1.profile.pk
        # s2_pk = self.test_student2.pk

        q_pk = self.quest1.pk
        q2_pk = self.quest2.pk

        self.assertEqual(self.client.get(reverse('profiles:profile_detail', args=[s_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('profiles:profile_update', args=[s_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('profiles:profile_list')).status_code, 200)
        self.assertEqual(self.client.get(reverse('profiles:profile_list_current')).status_code, 200)
        self.assertEqual(self.client.get(reverse('profiles:comment_ban', args=[s_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('profiles:comment_ban_toggle', args=[s_pk])).status_code, 302)
        self.assertEqual(self.client.get(reverse('profiles:GameLab_toggle', args=[s_pk])).status_code, 302)
        # self.assertEqual(self.client.get(reverse('profiles:recalculate_xp_current')).status_code, 302)

        self.assertEqual(self.client.get(reverse('quests:quest_delete', args=[q2_pk])).status_code, 200)
        self.assertEqual(self.client.get(reverse('quests:quest_copy', args=[q_pk])).status_code, 200)
Exemplo n.º 15
0
class ProfileViewTests(ViewTestUtilsMixin, TenantTestCase):

    # includes some basic model data
    # fixtures = ['initial_data.json']

    def setUp(self):
        self.client = TenantClient(self.tenant)
        User = get_user_model()

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)
        self.test_student2 = baker.make(User)

        # create semester with pk of default semester
        # this seems backward, but no semesters should exist yet in the test, so their shouldn't be any conflicts.
        self.active_sem = SiteConfig.get().active_semester

    def test_all_profile_page_status_codes_for_anonymous(self):
        """ If not logged in then all views should redirect to home page  """

        self.assertRedirectsLogin('profiles:profile_list')

    def test_all_profile_page_status_codes_for_students(self):

        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        s_pk = self.test_student1.profile.pk
        s2_pk = self.test_student2.profile.pk

        self.assert200('profiles:profile_detail', args=[s_pk])
        self.assert200('profiles:profile_update', args=[s_pk])

        self.assert200('profiles:profile_list_current')

        # students shouldn't have access to these and should be redirected to login or permission denied
        self.assert403('profiles:profile_list')

        # viewing the profile of another student
        self.assertRedirectsQuests('profiles:profile_detail', args=[s2_pk])

        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban_toggle',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:GameLab_toggle',
                                    args=[s_pk])).status_code, 302)
        # self.assertEqual(self.client.get(reverse('profiles:recalculate_xp_current')).status_code, 302)

        self.assert404('profiles:profile_update', args=[s2_pk])

    def test_all_profile_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        s_pk = self.test_student1.profile.pk
        # s2_pk = self.test_student2.pk

        self.assert200('profiles:profile_detail', args=[s_pk])
        self.assert200('profiles:profile_update', args=[s_pk])
        self.assert200('profiles:profile_list')
        self.assert200('profiles:profile_list_current')
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban_toggle',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:GameLab_toggle',
                                    args=[s_pk])).status_code, 302)
        # self.assertEqual(self.client.get(reverse('profiles:recalculate_xp_current')).status_code, 302)

    def test_profile_recalculate_xp_status_codes(self):
        """Need to test this view with students in an active course"""
        # why testing this here?
        self.assertEqual(self.active_sem.pk,
                         SiteConfig.get().active_semester.pk)

        self.assertEqual(
            self.client.get(
                reverse('profiles:recalculate_xp_current')).status_code, 302)

    def test_student_marks_button(self):
        """
        Student should be able to see marks button when `display_marks_calculation` is True.
        Otherwise, they should not be able to see it.
        """

        # Login a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # View profile page
        s_pk = self.test_student1.profile.pk

        # `display_marks_calculation` is disabled by default. Student should not be able to view it
        response = self.client.get(
            reverse('profiles:profile_detail', args=[s_pk]))
        self.assertNotContains(response, 'View your Mark Calculations')

        config = SiteConfig.get()
        config.display_marks_calculation = True
        config.save()

        # Student should be able to view marks calculation
        response = self.client.get(
            reverse('profiles:profile_detail', args=[s_pk]))
        self.assertContains(response, 'View your Mark Calculations')

    def test_student_view_marks_404_if_disabled(self):
        """
        Student marks should return 404 if disabled by admin.
        """

        # Login a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        self.assert404('courses:my_marks')
Exemplo n.º 16
0
class NotificationViewTests(ViewTestUtilsMixin, TenantTestCase):

    # includes some basic model data
    # fixtures = ['initial_data.json']

    def setUp(self):
        self.client = TenantClient(self.tenant)

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user('test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user('test_student', password=self.test_password)
        self.test_student2 = baker.make(User)

    def test_all_notification_page_status_codes_for_anonymous(self):
        ''' If not logged in then all views should redirect to home page '''

        self.assertRedirectsLogin('notifications:list')
        self.assertRedirectsLogin('notifications:list_unread')
        self.assertRedirectsLogin('notifications:read', kwargs={'id': 1})
        self.assertRedirectsLogin('notifications:read_all')

        self.assertRedirectsLogin('notifications:ajax')  # this doesn't make sense.  Should 404
        self.assertRedirectsLogin('notifications:ajax_mark_read')  # this doesn't make sense.  Should 404

    def test_all_notification_page_status_codes_for_students(self):
        # log in student1
        success = self.client.login(username=self.test_student1.username, password=self.test_password)
        self.assertTrue(success)

        # Accessible views:
        self.assertEqual(self.client.get(reverse('notifications:list')).status_code, 200)
        self.assertEqual(self.client.get(reverse('notifications:list_unread')).status_code, 200)

        self.assertRedirects(  
            response=self.client.get(reverse('notifications:read_all')),
            expected_url=reverse('notifications:list'),
        )

        # Inaccessible views:
        self.assertEqual(self.client.get(reverse('notifications:ajax_mark_read')).status_code, 404)  # requires AJAX
        self.assertEqual(self.client.get(reverse('notifications:ajax')).status_code, 404)  # requires POST

    def test_all_notification_page_status_codes_for_teachers(self):
        # log in student1
        success = self.client.login(username=self.test_teacher.username, password=self.test_password)
        self.assertTrue(success)

        # Accessible views:
        self.assertEqual(self.client.get(reverse('notifications:list')).status_code, 200)
        self.assertEqual(self.client.get(reverse('notifications:list_unread')).status_code, 200)

        self.assertRedirects(  
            response=self.client.get(reverse('notifications:read_all')),
            expected_url=reverse('notifications:list'),
        )

        # Inaccessible views:
        self.assertEqual(self.client.get(reverse('notifications:ajax_mark_read')).status_code, 404)  # requires POST
        self.assertEqual(self.client.get(reverse('notifications:ajax')).status_code, 404)  # requires POST

    def test_ajax_mark_read(self):
        """ Marks a Notification as read via Ajax (by setting unread = FALSE)
        """
        # log in student1
        success = self.client.login(username=self.test_student1.username, password=self.test_password)
        self.assertTrue(success)

        notification = baker.make('notifications.Notification', recipient=self.test_student1)
        # make sure it is unread
        self.assertTrue(notification.unread)

        # mark it as read via the view being tested
        ajax_data = {
            'id': notification.id,
        }
        response = self.client.post(
            reverse('notifications:ajax_mark_read'),
            data=ajax_data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response.status_code, 200)

    def test_ajax(self):
        # log in student1
        success = self.client.login(username=self.test_student1.username, password=self.test_password)
        self.assertTrue(success)

        response = self.client.post(
            reverse('notifications:ajax'),
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response.status_code, 200)
Exemplo n.º 17
0
class ProfileViewTests(TenantTestCase):

    # includes some basic model data
    # fixtures = ['initial_data.json']

    def setUp(self):
        self.client = TenantClient(self.tenant)
        User = get_user_model()

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)
        self.test_student2 = mommy.make(User)

        # create semester with pk of default semester
        # this seems backward, but no semesters should exist yet in the test, so their shouldn't be any conflicts.
        self.active_sem = SiteConfig.get().active_semester

    def test_all_profile_page_status_codes_for_anonymous(self):
        """ If not logged in then all views should redirect to home page  """

        self.assertRedirects(
            response=self.client.get(reverse('profiles:profile_list')),
            expected_url='%s?next=%s' %
            (reverse('home'), reverse('profiles:profile_list')),
        )

    def test_all_profile_page_status_codes_for_students(self):

        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        s_pk = self.test_student1.profile.pk
        s2_pk = self.test_student2.profile.pk

        # self.assertEqual(self.client.get(reverse('profiles:profile_detail')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('profiles:profile_detail',
                                    args=[s_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('profiles:profile_update',
                                    args=[s_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('profiles:profile_list')).status_code, 200)
        self.assertEqual(
            self.client.get(
                reverse('profiles:profile_list_current')).status_code, 200)

        # students shouldn't have access to these and should be redirected to login
        self.assertEqual(
            self.client.get(reverse('profiles:profile_detail',
                                    args=[s2_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban_toggle',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:GameLab_toggle',
                                    args=[s_pk])).status_code, 302)
        # self.assertEqual(self.client.get(reverse('profiles:recalculate_xp_current')).status_code, 302)

        self.assertEqual(
            self.client.get(reverse('profiles:profile_update',
                                    args=[s2_pk])).status_code, 404)

    def test_all_profile_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        s_pk = self.test_student1.profile.pk
        # s2_pk = self.test_student2.pk

        self.assertEqual(
            self.client.get(reverse('profiles:profile_detail',
                                    args=[s_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('profiles:profile_update',
                                    args=[s_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('profiles:profile_list')).status_code, 200)
        self.assertEqual(
            self.client.get(
                reverse('profiles:profile_list_current')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:comment_ban_toggle',
                                    args=[s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('profiles:GameLab_toggle',
                                    args=[s_pk])).status_code, 302)
        # self.assertEqual(self.client.get(reverse('profiles:recalculate_xp_current')).status_code, 302)

    def test_profile_recalculate_xp_status_codes(self):
        """Need to test this view with students in an active course"""
        # why testing this here?
        self.assertEqual(self.active_sem.pk,
                         SiteConfig.get().active_semester.pk)

        self.assertEqual(
            self.client.get(
                reverse('profiles:recalculate_xp_current')).status_code, 302)
Exemplo n.º 18
0
class BadgeViewTests(ViewTestUtilsMixin, TenantTestCase):
    def setUp(self):
        self.client = TenantClient(self.tenant)

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)
        self.test_student2 = baker.make(User)

        # needed because BadgeAssertions use a default that might not exist yet
        self.sem = SiteConfig.get().active_semester

        self.test_badge = baker.make(Badge, )
        self.test_badge_type = baker.make(BadgeType)
        self.test_assertion = baker.make(BadgeAssertion)

    def test_all_badge_page_status_codes_for_anonymous(self):
        ''' If not logged in then all views should redirect to home or admin page  '''
        b_pk = self.test_badge.pk
        a_pk = self.test_assertion.pk
        s_pk = self.test_student1.pk

        self.assertRedirectsLogin('badges:list')
        self.assertRedirectsLogin('badges:badge_detail', args=[b_pk])
        self.assertRedirectsLogin('badges:badge_create')

        self.assertRedirectsAdmin('badges:badge_update', args=[b_pk])
        self.assertRedirectsAdmin('badges:badge_copy', args=[b_pk])
        self.assertRedirectsAdmin('badges:badge_delete', args=[b_pk])
        self.assertRedirectsAdmin('badges:grant', args=[b_pk, s_pk])
        self.assertRedirectsAdmin('badges:bulk_grant_badge', args=[b_pk])
        self.assertRedirectsAdmin('badges:bulk_grant')
        self.assertRedirectsAdmin('badges:revoke', args=[a_pk])

    def test_all_badge_page_status_codes_for_students(self):

        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        b_pk = self.test_badge.pk
        # a_pk = self.test_assertion.pk
        s_pk = self.test_student1.pk

        self.assert200('badges:list')
        self.assert200('badges:badge_detail', args=[b_pk])

        # students shouldn't have access to these and should be redirected

        self.assertRedirectsQuests('badges:badge_create', follow=True),
        self.assertRedirectsAdmin('badges:badge_update', args=[b_pk])
        self.assertRedirectsAdmin('badges:badge_copy', args=[b_pk])
        self.assertRedirectsAdmin('badges:badge_delete', args=[b_pk])
        self.assertRedirectsAdmin('badges:grant', args=[b_pk, s_pk])
        self.assertRedirectsAdmin('badges:bulk_grant_badge', args=[b_pk])
        self.assertRedirectsAdmin('badges:bulk_grant')
        self.assertRedirectsAdmin('badges:revoke', args=[s_pk])

    def test_all_badge_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        b_pk = self.test_badge.pk
        a_pk = self.test_assertion.pk
        s_pk = self.test_student1.pk

        self.assert200('badges:list')
        self.assert200('badges:badge_detail', args=[b_pk])
        self.assert200('badges:badge_create')
        self.assert200('badges:badge_update', args=[b_pk])
        self.assert200('badges:badge_copy', args=[b_pk])
        self.assert200('badges:badge_delete', args=[b_pk])
        self.assert200('badges:grant', args=[b_pk, s_pk])
        self.assert200('badges:bulk_grant_badge', args=[b_pk])
        self.assert200('badges:bulk_grant')
        self.assert200('badges:revoke', args=[a_pk])

    def test_badge_create(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        form_data = {
            'name': "badge test",
            'xp': 5,
            'content': "test content",
            'badge_type': self.test_badge_type.id,
            'author': self.test_teacher.id,
            'import_id': uuid.uuid4()
        }

        response = self.client.post(reverse('badges:badge_create'),
                                    data=form_data)
        self.assertRedirects(response, reverse("badges:list"))

        # Get the newest object
        new_badge = Badge.objects.latest('datetime_created')
        self.assertEqual(new_badge.name, "badge test")

    def test_badge_copy(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        form_data = {
            'name': "badge copy test",
            'xp': 5,
            'content': "test content",
            'badge_type': self.test_badge_type.id,
            'author': self.test_teacher.id,
            'import_id': uuid.uuid4()
        }

        response = self.client.post(reverse('badges:badge_copy',
                                            args=[self.test_badge.id]),
                                    data=form_data)
        self.assertRedirects(response, reverse("badges:list"))

        # Get the newest object
        new_badge = Badge.objects.latest('datetime_created')
        self.assertEqual(new_badge.name, "badge copy test")

    def test_assertion_create_and_delete(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # test: assertion_create()
        form_data = {
            'badge': self.test_badge.id,
            'user': self.test_student1.id
        }

        response = self.client.post(reverse('badges:grant',
                                            kwargs={
                                                'user_id':
                                                self.test_student1.id,
                                                'badge_id': self.test_badge.id
                                            }),
                                    data=form_data)
        self.assertRedirects(response, reverse("badges:list"))

        new_assertion = BadgeAssertion.objects.latest('timestamp')
        self.assertEqual(new_assertion.user, self.test_student1)
        self.assertEqual(new_assertion.badge, self.test_badge)

        # test: assertion_delete()
        response = self.client.post(
            reverse('badges:revoke', args=[new_assertion.id]), )
        self.assertRedirects(
            response,
            reverse("profiles:profile_detail",
                    args=[self.test_student1.profile.id]))

        # shouldn't exist anymore now that we deleted it!
        with self.assertRaises(BadgeAssertion.DoesNotExist):
            BadgeAssertion.objects.get(id=new_assertion.id)

    def test_bulk_assertion_create(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        # compare total granted before to after:
        badge_assertions_before = BadgeAssertion.objects.all().count()

        # this form uses students in the active semester, so need to give them a course in the active semester!
        baker.make('courses.CourseStudent',
                   user=self.test_student1,
                   semester=self.sem)
        baker.make('courses.CourseStudent',
                   user=self.test_student2,
                   semester=self.sem)

        form_data = {
            'badge':
            self.test_badge.id,
            'students':
            [self.test_student1.profile.id, self.test_student2.profile.id]
        }
        response = self.client.post(reverse('badges:bulk_grant'),
                                    data=form_data)

        self.assertRedirects(response, reverse("badges:list"))

        # we just bulk granted 2 badges, so there should be two more than before!
        badge_assertions_after = BadgeAssertion.objects.all().count()
        self.assertEqual(badge_assertions_after, badge_assertions_before + 2)
Exemplo n.º 19
0
class ViewTests(TenantTestCase):

    # includes some basic model data
    # fixtures = ['initial_data.json']

    def setUp(self):
        self.client = TenantClient(self.tenant)
        User = get_user_model()

        # need a teacher and a student with known password so tests can log in as each, or could use force_login()?
        self.test_password = "******"

        # need a teacher before students can be created or the profile creation will fail when trying to notify
        self.test_teacher = User.objects.create_user(
            'test_teacher', password=self.test_password, is_staff=True)
        self.test_student1 = User.objects.create_user(
            'test_student', password=self.test_password)
        self.test_student2 = mommy.make(User)

        # needed because BadgeAssertions use a default that might not exist yet
        self.sem = SiteConfig.get().active_semester

        self.test_badge = mommy.make(Badge)
        self.test_assertion = mommy.make(BadgeAssertion)

    def test_all_badge_page_status_codes_for_anonymous(self):
        ''' If not logged in then all views should redirect to home page  '''

        self.assertRedirects(
            response=self.client.get(reverse('badges:list')),
            expected_url='%s?next=%s' %
            (reverse('home'), reverse('badges:list')),
        )

        # for path in urlpatterns:
        #     name = 'badges:%s' % path.name
        #     # path.name
        #     # print(url)
        #     self.assertRedirects(
        #         response=self.client.get(reverse(name)),
        #         expected_url='%s?next=%s' % (reverse('home'), reverse(name)),
        #         msg_prefix=name,
        #     )

    def test_all_badge_page_status_codes_for_students(self):

        # log in a student
        success = self.client.login(username=self.test_student1.username,
                                    password=self.test_password)
        self.assertTrue(success)

        b_pk = self.test_badge.pk
        # a_pk = self.test_assertion.pk
        s_pk = self.test_student1.pk

        self.assertEqual(
            self.client.get(reverse('badges:list')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:badge_detail',
                                    args=[b_pk])).status_code, 200)

        # students shouldn't have access to these and should be redirected
        self.assertEqual(
            self.client.get(reverse('badges:badge_create')).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:badge_update',
                                    args=[b_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:badge_copy',
                                    args=[b_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:badge_delete',
                                    args=[b_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:grant',
                                    args=[b_pk, s_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:bulk_grant_badge',
                                    args=[b_pk])).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:bulk_grant')).status_code, 302)
        self.assertEqual(
            self.client.get(reverse('badges:revoke', args=[s_pk])).status_code,
            302)

    def test_all_badge_page_status_codes_for_teachers(self):
        # log in a teacher
        success = self.client.login(username=self.test_teacher.username,
                                    password=self.test_password)
        self.assertTrue(success)

        b_pk = self.test_badge.pk
        a_pk = self.test_assertion.pk
        s_pk = self.test_student1.pk

        self.assertEqual(
            self.client.get(reverse('badges:list')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:badge_detail',
                                    args=[b_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:badge_create')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:badge_update',
                                    args=[b_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:badge_copy',
                                    args=[b_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:badge_delete',
                                    args=[b_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:grant',
                                    args=[b_pk, s_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:bulk_grant_badge',
                                    args=[b_pk])).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:bulk_grant')).status_code, 200)
        self.assertEqual(
            self.client.get(reverse('badges:revoke', args=[a_pk])).status_code,
            200)