Ejemplo n.º 1
0
    def test_char_count_after_publication(self):
        """Test the ``get_char_count()`` function.

        Special care should be taken with this function, since:

        - The username of the author is, by default "Firmxxx" where "xxx" depends on the tests before ;
        - The titles (!) also contains a number that also depends on the number of tests before ;
        - The date is ``datetime.now()`` and contains the months, which is never a fixed number of letters.
        """

        author = ProfileFactory().user
        author.username = '******'
        author.save()

        len_date_now = len(date(datetime.now(), 'd F Y'))

        article = PublishedContentFactory(type='ARTICLE', author_list=[author], title='Un titre')
        published = PublishedContent.objects.filter(content=article).first()
        self.assertEqual(published.get_char_count(), 160 + len_date_now)

        tuto = PublishableContentFactory(type='TUTORIAL', author_list=[author], title='Un titre')

        # add a chapter, so it becomes a middle tutorial
        tuto_draft = tuto.load_version()
        chapter1 = ContainerFactory(parent=tuto_draft, db_object=tuto, title='Un chapitre')
        ExtractFactory(container=chapter1, db_object=tuto, title='Un extrait')
        published = publish_content(tuto, tuto_draft, is_major_update=True)

        tuto.sha_public = tuto_draft.current_version
        tuto.sha_draft = tuto_draft.current_version
        tuto.public_version = published
        tuto.save()

        published = PublishedContent.objects.filter(content=tuto).first()
        self.assertEqual(published.get_char_count(), 335 + len_date_now)
class SetLastVisitMiddlewareTest(TestCase):
    def setUp(self):
        self.user = ProfileFactory()

    def test_process_response(self):
        profile_pk = self.user.pk

        # login
        self.client.force_login(self.user.user)

        # set last login to a recent date
        self.user.last_visit = datetime.now() - timedelta(seconds=10)
        self.user.save()

        # load a page
        self.client.get(reverse("homepage"))

        # the date of last visit should not have been updated
        profile = get_object_or_404(Profile, pk=profile_pk)
        self.assertTrue(
            datetime.now() - profile.last_visit > timedelta(seconds=5))

        # set last login to an old date
        self.user.last_visit = datetime.now() - timedelta(seconds=45)
        self.user.save()

        # load a page
        self.client.get(reverse("homepage"))

        # the date of last visit should have been updated
        profile = get_object_or_404(Profile, pk=profile_pk)
        self.assertTrue(
            datetime.now() - profile.last_visit < timedelta(seconds=5))
Ejemplo n.º 3
0
    def test_ban_member_is_not_contactable(self):
        """
        When a member is ban, we hide the button to send a PM.
        """
        user_ban = ProfileFactory()
        user_ban.can_read = False
        user_ban.can_write = False
        user_ban.save()
        user_1 = ProfileFactory()
        user_2 = ProfileFactory()

        phrase = "Envoyer un message privé"

        result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False)
        self.assertNotContains(result, phrase)

        result = self.client.get(reverse('member-detail', args=[user_ban.user.username]), follow=False)
        self.assertNotContains(result, phrase)

        self.assertTrue(self.client.login(username=user_2.user.username, password='******'))
        result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False)
        self.client.logout()
        self.assertContains(result, phrase)

        self.assertTrue(self.client.login(username=user_2.user.username, password='******'))
        result = self.client.get(reverse('member-detail', args=[user_ban.user.username]), follow=False)
        self.client.logout()
        self.assertNotContains(result, phrase)

        self.assertTrue(self.client.login(username=user_1.user.username, password='******'))
        result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False)
        self.client.logout()
        self.assertNotContains(result, phrase)
Ejemplo n.º 4
0
    def test_char_count_after_publication(self):
        """Test the ``get_char_count()`` function.

        Special care should be taken with this function, since:

        - The username of the author is, by default "Firmxxx" where "xxx" depends on the tests before ;
        - The titles (!) also contains a number that also depends on the number of tests before ;
        - The date is ``datetime.now()`` and contains the months, which is never a fixed number of letters.
        """

        author = ProfileFactory().user
        author.username = '******'
        author.save()

        len_date_now = len(date(datetime.now(), 'd F Y'))

        article = PublishedContentFactory(type='ARTICLE', author_list=[author], title='Un titre')
        published = PublishedContent.objects.filter(content=article).first()
        self.assertEqual(published.get_char_count(), 160 + len_date_now)

        tuto = PublishableContentFactory(type='TUTORIAL', author_list=[author], title='Un titre')

        # add a chapter, so it becomes a middle tutorial
        tuto_draft = tuto.load_version()
        chapter1 = ContainerFactory(parent=tuto_draft, db_object=tuto, title='Un chapitre')
        ExtractFactory(container=chapter1, db_object=tuto, title='Un extrait')
        published = publish_content(tuto, tuto_draft, is_major_update=True)

        tuto.sha_public = tuto_draft.current_version
        tuto.sha_draft = tuto_draft.current_version
        tuto.public_version = published
        tuto.save()

        published = PublishedContent.objects.filter(content=tuto).first()
        self.assertEqual(published.get_char_count(), 335 + len_date_now)
class SetLastVisitMiddlewareTest(TestCase):
    def setUp(self):
        self.user = ProfileFactory()

    def test_process_response(self):
        profile_pk = self.user.pk

        # login
        self.assertEqual(
            self.client.login(
                username=self.user.user.username,
                password='******'),
            True)

        # set last login to a recent date
        self.user.last_visit = datetime.now() - timedelta(seconds=10)
        self.user.save()

        # load a page
        self.client.get(reverse('homepage'))

        # the date of last visit should not have been updated
        profile = get_object_or_404(Profile, pk=profile_pk)
        self.assertTrue(datetime.now() - profile.last_visit > timedelta(seconds=5))

        # set last login to an old date
        self.user.last_visit = datetime.now() - timedelta(seconds=45)
        self.user.save()

        # load a page
        self.client.get(reverse('homepage'))

        # the date of last visit should have been updated
        profile = get_object_or_404(Profile, pk=profile_pk)
        self.assertTrue(datetime.now() - profile.last_visit < timedelta(seconds=5))
Ejemplo n.º 6
0
class SubscriptionsTest(TestCase):
    def setUp(self):
        self.userStandard1 = ProfileFactory(email_for_answer=True,
                                            email_for_new_mp=True).user
        self.userOAuth1 = ProfileFactory(email_for_answer=True,
                                         email_for_new_mp=True).user
        self.userOAuth2 = ProfileFactory(email_for_answer=True,
                                         email_for_new_mp=True).user

        self.userOAuth1.email = ""
        self.userOAuth2.email = "this is not an email"

        self.userOAuth1.save()
        self.userOAuth2.save()

    def test_no_emails_for_those_who_have_none(self):
        """
        Test that we do not try to send e-mails to those who have not registered one.
        """
        self.assertEqual(0, len(mail.outbox))
        topic = send_mp(
            author=self.userStandard1,
            users=[self.userOAuth1],
            title="Testing",
            subtitle="",
            text="",
            send_by_mail=True,
            leave=False,
        )

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

        send_message_mp(self.userOAuth1, topic, "", send_by_mail=True)

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

    def test_no_emails_for_those_who_have_other_things_in_that_place(self):
        """
        Test that we do not try to send e-mails to those who have not registered a valid one.
        """
        self.assertEqual(0, len(mail.outbox))
        topic = send_mp(
            author=self.userStandard1,
            users=[self.userOAuth2],
            title="Testing",
            subtitle="",
            text="",
            send_by_mail=True,
            leave=False,
        )

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

        send_message_mp(self.userOAuth2, topic, "", send_by_mail=True)

        self.assertEqual(1, len(mail.outbox))
Ejemplo n.º 7
0
    def test_profiler(self):
        result = self.client.get("/?prof", follow=True)
        self.assertEqual(result.status_code, 200)

        admin = ProfileFactory()
        admin.user.is_superuser = True
        admin.save()
        self.client.force_login(admin.user)

        result = self.client.get("/?prof", follow=True)
        self.assertEqual(result.status_code, 200)
Ejemplo n.º 8
0
    def test_profiler(self):
        result = self.client.get('/?prof', follow=True)
        self.assertEqual(result.status_code, 200)

        admin = ProfileFactory()
        admin.user.is_superuser = True
        admin.save()
        self.assertTrue(self.client.login(username=admin.user.username, password='******'))

        result = self.client.get('/?prof', follow=True)
        self.assertEqual(result.status_code, 200)
Ejemplo n.º 9
0
    def test_profiler(self):
        result = self.client.get('/?prof', follow=True)
        self.assertEqual(result.status_code, 200)

        admin = ProfileFactory()
        admin.user.is_superuser = True
        admin.save()
        self.assertTrue(self.client.login(username=admin.user.username, password='******'))

        result = self.client.get('/?prof', follow=True)
        self.assertEqual(result.status_code, 200)
Ejemplo n.º 10
0
    def test_failure_reaction_karma_with_sanctioned_user(self):
        author = ProfileFactory()
        reaction = ContentReactionFactory(author=author.user, position=1, related_content=self.content)

        profile = ProfileFactory()
        profile.can_read = False
        profile.can_write = False
        profile.save()

        self.assertTrue(self.client.login(username=profile.user.username, password='******'))
        response = self.client.put(reverse('api:content:reaction-karma', args=(reaction.pk,)))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Ejemplo n.º 11
0
def load_member(cli, size, fake, root, *_):
    """
    Load members
    """
    nb_users = size * 10
    cli.stdout.write("Nombres de membres à créer : {}".format(nb_users))
    tps1 = time.time()
    cpt = 1
    # member in settings
    users_set = [
        "admin",
        settings.ZDS_APP["member"]["external_account"],
        settings.ZDS_APP["member"]["anonymous_account"],
    ]
    for default_user in users_set:
        current_user = Profile.objects.filter(
            user__username=default_user).first()
        if current_user is None:
            profile = ProfileFactory(user__username=default_user)
            profile.user.set_password(default_user)
            profile.user.first_name = default_user
            profile.user.email = fake.free_email()
            if default_user == "admin":
                profile.user.is_superuser = True
                profile.user.is_staff = True
            with contextlib.suppress(IntegrityError):
                profile.user.save()
                profile.site = fake.url()
                profile.biography = fake.text(max_nb_chars=200)
                profile.last_ip_address = fake.ipv4()
                profile.save()

    for i in range(0, nb_users):
        while Profile.objects.filter(
                user__username="******".format(root, cpt)).count() > 0:
            cpt += 1
        profile = ProfileFactory(user__username="******".format(root, cpt))
        profile.user.set_password(profile.user.username)
        profile.user.first_name = fake.first_name()
        profile.user.last_name = fake.last_name()
        profile.user.email = fake.free_email()
        profile.user.save()
        profile.site = fake.url()
        profile.biography = fake.text(max_nb_chars=200)
        profile.last_ip_address = fake.ipv4()
        profile.save()
        cpt += 1
        sys.stdout.write(" User {}/{}  \r".format(i + 1, nb_users))
        sys.stdout.flush()
    tps2 = time.time()
    cli.stdout.write("\nFait en {} sec".format(tps2 - tps1))
Ejemplo n.º 12
0
def load_member(cli, size, fake, root):
    """
    Load members
    """
    nb_users = size * 10
    cli.stdout.write(u'Nombres de membres à créer : {}'.format(nb_users))
    tps1 = time.time()
    cpt = 1
    # member in settings
    users_set = [
        'admin', settings.ZDS_APP['member']['external_account'],
        settings.ZDS_APP['member']['anonymous_account']
    ]
    for default_user in users_set:
        current_user = Profile.objects.filter(
            user__username=default_user).first()
        if current_user is None:
            profile = ProfileFactory(user__username=default_user)
            profile.user.set_password(default_user)
            profile.user.first_name = default_user
            profile.user.email = fake.free_email()
            if default_user == 'admin':
                profile.user.is_superuser = True
                profile.user.is_staff = True
            profile.user.save()
            profile.site = fake.url()
            profile.biography = fake.text(max_nb_chars=200)
            profile.last_ip_address = fake.ipv4()
            profile.save()

    for i in range(0, nb_users):
        while Profile.objects.filter(
                user__username='******'.format(root, cpt)).count() > 0:
            cpt += 1
        profile = ProfileFactory(user__username='******'.format(root, cpt))
        profile.user.set_password(profile.user.username)
        profile.user.first_name = fake.first_name()
        profile.user.last_name = fake.last_name()
        profile.user.email = fake.free_email()
        profile.user.save()
        profile.site = fake.url()
        profile.biography = fake.text(max_nb_chars=200)
        profile.last_ip_address = fake.ipv4()
        profile.save()
        cpt += 1
        sys.stdout.write(' User {}/{}  \r'.format(i + 1, nb_users))
        sys.stdout.flush()
    tps2 = time.time()
    cli.stdout.write(u'\nFait en {} sec'.format(tps2 - tps1))
Ejemplo n.º 13
0
    def test_failure_post_karma_with_sanctioned_user(self):
        profile = ProfileFactory()
        category, forum = create_category_and_forum()
        topic = create_topic_in_forum(forum, profile)
        another_profile = ProfileFactory()
        post = PostFactory(topic=topic, author=another_profile.user, position=2)

        profile = ProfileFactory()
        profile.can_read = False
        profile.can_write = False
        profile.save()

        self.assertTrue(self.client.login(username=profile.user.username, password='******'))
        response = self.client.put(reverse('api:forum:post-karma', args=(post.pk,)))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Ejemplo n.º 14
0
class SubscriptionsTest(TestCase):
    def setUp(self):
        self.userStandard1 = ProfileFactory(
            email_for_answer=True,
            email_for_new_mp=True
        ).user
        self.userOAuth1 = ProfileFactory(
            email_for_answer=True,
            email_for_new_mp=True).user
        self.userOAuth2 = ProfileFactory(
            email_for_answer=True,
            email_for_new_mp=True).user

        self.userOAuth1.email = ''
        self.userOAuth2.email = 'this is not an email'

        self.userOAuth1.save()
        self.userOAuth2.save()

    def test_no_emails_for_those_who_have_none(self):
        """
        Test that we do not try to send e-mails to those who have not registered one.
        """
        self.assertEqual(0, len(mail.outbox))
        topic = send_mp(author=self.userStandard1, users=[self.userOAuth1],
                        title='Testing', subtitle='', text='',
                        send_by_mail=True, leave=False)

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

        send_message_mp(self.userOAuth1, topic, '', send_by_mail=True)

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

    def test_no_emails_for_those_who_have_other_things_in_that_place(self):
        """
        Test that we do not try to send e-mails to those who have not registered a valid one.
        """
        self.assertEqual(0, len(mail.outbox))
        topic = send_mp(author=self.userStandard1, users=[self.userOAuth2],
                        title='Testing', subtitle='', text='',
                        send_by_mail=True, leave=False)

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

        send_message_mp(self.userOAuth2, topic, '', send_by_mail=True)

        self.assertEqual(1, len(mail.outbox))
Ejemplo n.º 15
0
class MemberModelsTest(TutorialTestMixin, TestCase):

    def setUp(self):
        self.user1 = ProfileFactory()
        self.staff = StaffProfileFactory()

        # Create a forum for later test
        self.forumcat = CategoryFactory()
        self.forum = ForumFactory(category=self.forumcat)
        self.forumtopic = TopicFactory(forum=self.forum, author=self.staff.user)

    def test_get_absolute_url_for_details_of_member(self):
        self.assertEqual(self.user1.get_absolute_url(), '/membres/voir/{0}/'.format(self.user1.user.username))

    def test_get_avatar_url(self):
        # if no url was specified -> gravatar !
        self.assertEqual(self.user1.get_avatar_url(),
                         'https://secure.gravatar.com/avatar/{0}?d=identicon'.
                         format(md5(self.user1.user.email.lower().encode()).hexdigest()))
        # if an url is specified -> take it !
        user2 = ProfileFactory()
        testurl = 'http://test.com/avatar.jpg'
        user2.avatar_url = testurl
        self.assertEqual(user2.get_avatar_url(), testurl)

        # if url is relative, send absolute url
        gallerie_avtar = GalleryFactory()
        image_avatar = ImageFactory(gallery=gallerie_avtar)
        user2.avatar_url = image_avatar.physical.url
        self.assertNotEqual(user2.get_avatar_url(), image_avatar.physical.url)
        self.assertIn('http', user2.get_avatar_url())

    def test_get_post_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_post_count(), 0)
        # Post !
        PostFactory(topic=self.forumtopic, author=self.user1.user, position=1)
        # Should be 1
        self.assertEqual(self.user1.get_post_count(), 1)

    def test_get_topic_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_topic_count(), 0)
        # Create Topic !
        TopicFactory(forum=self.forum, author=self.user1.user)
        # Should be 1
        self.assertEqual(self.user1.get_topic_count(), 1)

    def test_get_tuto_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_tuto_count(), 0)
        # Create Tuto !
        minituto = PublishableContentFactory(type='TUTORIAL')
        minituto.authors.add(self.user1.user)
        minituto.gallery = GalleryFactory()
        minituto.save()
        # Should be 1
        self.assertEqual(self.user1.get_tuto_count(), 1)

    def test_get_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_tutos()), 0)
        # Create Tuto !
        minituto = PublishableContentFactory(type='TUTORIAL')
        minituto.authors.add(self.user1.user)
        minituto.gallery = GalleryFactory()
        minituto.save()
        # Should be 1
        tutos = self.user1.get_tutos()
        self.assertEqual(len(tutos), 1)
        self.assertEqual(minituto, tutos[0])

    def test_get_draft_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_draft_tutos()), 0)
        # Create Tuto !
        drafttuto = PublishableContentFactory(type='TUTORIAL')
        drafttuto.authors.add(self.user1.user)
        drafttuto.gallery = GalleryFactory()
        drafttuto.save()
        # Should be 1
        drafttutos = self.user1.get_draft_tutos()
        self.assertEqual(len(drafttutos), 1)
        self.assertEqual(drafttuto, drafttutos[0])

    def test_get_public_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_public_tutos()), 0)
        # Create Tuto !
        publictuto = PublishableContentFactory(type='TUTORIAL')
        publictuto.authors.add(self.user1.user)
        publictuto.gallery = GalleryFactory()
        publictuto.sha_public = 'whatever'
        publictuto.save()
        # Should be 0 because publication was not used
        publictutos = self.user1.get_public_tutos()
        self.assertEqual(len(publictutos), 0)
        PublishedContentFactory(author_list=[self.user1.user])
        self.assertEqual(len(self.user1.get_public_tutos()), 1)

    def test_get_validate_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_validate_tutos()), 0)
        # Create Tuto !
        validatetuto = PublishableContentFactory(type='TUTORIAL', author_list=[self.user1.user])
        validatetuto.sha_validation = 'whatever'
        validatetuto.save()
        # Should be 1
        validatetutos = self.user1.get_validate_tutos()
        self.assertEqual(len(validatetutos), 1)
        self.assertEqual(validatetuto, validatetutos[0])

    def test_get_beta_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_beta_tutos()), 0)
        # Create Tuto !
        betatetuto = PublishableContentFactory(type='TUTORIAL')
        betatetuto.authors.add(self.user1.user)
        betatetuto.gallery = GalleryFactory()
        betatetuto.sha_beta = 'whatever'
        betatetuto.save()
        # Should be 1
        betatetutos = self.user1.get_beta_tutos()
        self.assertEqual(len(betatetutos), 1)
        self.assertEqual(betatetuto, betatetutos[0])

    def test_get_article_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_tuto_count(), 0)
        # Create article !
        minituto = PublishableContentFactory(type='ARTICLE')
        minituto.authors.add(self.user1.user)
        minituto.gallery = GalleryFactory()
        minituto.save()
        # Should be 1
        self.assertEqual(self.user1.get_article_count(), 1)

    def test_get_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.save()
        # Should be 1
        articles = self.user1.get_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_public_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_public_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.sha_public = 'whatever'
        article.save()
        # Should be 0
        articles = self.user1.get_public_articles()
        self.assertEqual(len(articles), 0)
        # Should be 1
        PublishedContentFactory(author_list=[self.user1.user], type='ARTICLE')
        self.assertEqual(len(self.user1.get_public_articles()), 1)
        self.assertEqual(len(self.user1.get_public_tutos()), 0)

    def test_get_validate_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_validate_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.sha_validation = 'whatever'
        article.save()
        # Should be 1
        articles = self.user1.get_validate_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_draft_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_draft_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.save()
        # Should be 1
        articles = self.user1.get_draft_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_beta_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_beta_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.sha_beta = 'whatever'
        article.save()
        # Should be 1
        articles = self.user1.get_beta_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_posts(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_posts()), 0)
        # Post !
        apost = PostFactory(topic=self.forumtopic, author=self.user1.user, position=1)
        # Should be 1
        posts = self.user1.get_posts()
        self.assertEqual(len(posts), 1)
        self.assertEqual(apost, posts[0])

    def test_get_hidden_by_staff_posts_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 0)
        # Post and hide it by poster
        PostFactory(topic=self.forumtopic, author=self.user1.user, position=1, is_visible=False, editor=self.user1.user)
        # Should be 0
        self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 0)
        # Post and hide it by staff
        PostFactory(topic=self.forumtopic, author=self.user1.user, position=1, is_visible=False, editor=self.staff.user)
        # Should be 1
        self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 1)

    def test_get_hidden_by_staff_posts_count_staff_poster(self):
        # Start with 0
        self.assertEqual(self.staff.get_hidden_by_staff_posts_count(), 0)
        # Post and hide it by poster which is staff
        PostFactory(topic=self.forumtopic, author=self.staff.user, position=1, is_visible=False, editor=self.staff.user)
        # Should be 0 because even if poster is staff, he is the poster
        self.assertEqual(self.staff.get_hidden_by_staff_posts_count(), 0)

    def test_get_active_alerts_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_active_alerts_count(), 0)
        # Post and Alert it !
        post = PostFactory(topic=self.forumtopic, author=self.user1.user, position=1)
        Alert.objects.create(author=self.user1.user, comment=post, scope='FORUM', pubdate=datetime.now())
        # Should be 1
        self.assertEqual(self.user1.get_active_alerts_count(), 1)

    def test_can_read_now(self):

        profile = ProfileFactory()
        profile.is_active = True
        profile.can_read = True
        self.assertTrue(profile.can_read_now())

        # Was banned in the past, ban no longer active
        profile = ProfileFactory()
        profile.end_ban_read = datetime.now() - timedelta(days=1)
        self.assertTrue(profile.can_read_now())

        profile = ProfileFactory()
        profile.is_active = True
        profile.can_read = False
        self.assertFalse(profile.can_read_now())

        # Ban is active
        profile = ProfileFactory()
        profile.is_active = True
        profile.can_read = False
        profile.end_ban_read = datetime.now() + timedelta(days=1)
        self.assertFalse(profile.can_read_now())

        self.user1.user.is_active = False
        self.assertFalse(self.user1.can_read_now())

    def test_can_write_now(self):

        self.user1.user.is_active = True
        self.user1.user.can_write = True
        self.assertTrue(self.user1.can_write_now())

        # Was banned in the past, ban no longer active
        profile = ProfileFactory()
        profile.can_write = True
        profile.end_ban_read = datetime.now() - timedelta(days=1)
        self.assertTrue(profile.can_write_now())

        profile = ProfileFactory()
        profile.can_write = False
        profile.is_active = True
        self.assertFalse(profile.can_write_now())

        # Ban is active
        profile = ProfileFactory()
        profile.can_write = False
        profile.end_ban_write = datetime.now() + timedelta(days=1)
        self.assertFalse(profile.can_write_now())

        self.user1.user.is_active = False
        self.user1.user.can_write = True
        self.assertFalse(self.user1.can_write_now())

    def test_get_followed_topics(self):
        # Start with 0
        self.assertEqual(len(TopicAnswerSubscription.objects.get_objects_followed_by(self.user1.user)), 0)
        # Follow !
        TopicAnswerSubscription.objects.toggle_follow(self.forumtopic, self.user1.user)
        # Should be 1
        topicsfollowed = TopicAnswerSubscription.objects.get_objects_followed_by(self.user1.user)
        self.assertEqual(len(topicsfollowed), 1)
        self.assertEqual(self.forumtopic, topicsfollowed[0])

    def test_get_city_with_wrong_ip(self):
        # Set a local IP to the user
        self.user1.last_ip_address = '127.0.0.1'
        # Then the get_city is not found and return empty string
        self.assertEqual('', self.user1.get_city())

        # Same goes for IPV6
        # Set a local IP to the user
        self.user1.last_ip_address = '0000:0000:0000:0000:0000:0000:0000:0001'
        # Then the get_city is not found and return empty string
        self.assertEqual('', self.user1.get_city())

    def test_remove_token_on_removing_from_dev_group(self):
        dev = DevProfileFactory()
        dev.github_token = 'test'
        dev.save()
        dev.user.save()

        self.assertEqual('test', dev.github_token)

        # remove dev from dev group
        dev.user.groups.clear()
        dev.user.save()

        self.assertEqual('', dev.github_token)

    def test_reachable_manager(self):
        # profile types
        profile_normal = ProfileFactory()
        profile_superuser = ProfileFactory()
        profile_superuser.user.is_superuser = True
        profile_superuser.user.save()
        profile_inactive = ProfileFactory()
        profile_inactive.user.is_active = False
        profile_inactive.user.save()
        profile_bot = ProfileFactory()
        profile_bot.user.username = settings.ZDS_APP['member']['bot_account']
        profile_bot.user.save()
        profile_anonymous = ProfileFactory()
        profile_anonymous.user.username = settings.ZDS_APP['member']['anonymous_account']
        profile_anonymous.user.save()
        profile_external = ProfileFactory()
        profile_external.user.username = settings.ZDS_APP['member']['external_account']
        profile_external.user.save()
        profile_ban_def = ProfileFactory()
        profile_ban_def.can_read = False
        profile_ban_def.can_write = False
        profile_ban_def.save()
        profile_ban_temp = ProfileFactory()
        profile_ban_temp.can_read = False
        profile_ban_temp.can_write = False
        profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1)
        profile_ban_temp.save()
        profile_unban = ProfileFactory()
        profile_unban.can_read = False
        profile_unban.can_write = False
        profile_unban.end_ban_read = datetime.now() - timedelta(days=1)
        profile_unban.save()
        profile_ls_def = ProfileFactory()
        profile_ls_def.can_write = False
        profile_ls_def.save()
        profile_ls_temp = ProfileFactory()
        profile_ls_temp.can_write = False
        profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1)
        profile_ls_temp.save()

        # groups

        bot = Group(name=settings.ZDS_APP['member']['bot_group'])
        bot.save()

        # associate account to groups
        bot.user_set.add(profile_anonymous.user)
        bot.user_set.add(profile_external.user)
        bot.user_set.add(profile_bot.user)
        bot.save()

        # test reachable user
        profiles_reacheable = Profile.objects.contactable_members().all()
        self.assertIn(profile_normal, profiles_reacheable)
        self.assertIn(profile_superuser, profiles_reacheable)
        self.assertNotIn(profile_inactive, profiles_reacheable)
        self.assertNotIn(profile_anonymous, profiles_reacheable)
        self.assertNotIn(profile_external, profiles_reacheable)
        self.assertNotIn(profile_bot, profiles_reacheable)
        self.assertIn(profile_unban, profiles_reacheable)
        self.assertNotIn(profile_ban_def, profiles_reacheable)
        self.assertNotIn(profile_ban_temp, profiles_reacheable)
        self.assertIn(profile_ls_def, profiles_reacheable)
        self.assertIn(profile_ls_temp, profiles_reacheable)

    def test_remove_hats_linked_to_group(self):
        # create a hat linked to a group
        hat_name = 'Test hat'
        hat, _ = Hat.objects.get_or_create(name__iexact=hat_name, defaults={'name': hat_name})
        group, _ = Group.objects.get_or_create(name='test_hat')
        hat.group = group
        hat.save()
        # add it to a user
        self.user1.hats.add(hat)
        self.user1.save()
        # the user shound't have the hat through their profile
        self.assertNotIn(hat, self.user1.hats.all())
Ejemplo n.º 16
0
    def test_reachable_manager(self):
        # profile types
        profile_normal = ProfileFactory()
        profile_superuser = ProfileFactory()
        profile_superuser.user.is_superuser = True
        profile_superuser.user.save()
        profile_inactive = ProfileFactory()
        profile_inactive.user.is_active = False
        profile_inactive.user.save()
        profile_bot = ProfileFactory()
        profile_bot.user.username = settings.ZDS_APP['member']['bot_account']
        profile_bot.user.save()
        profile_anonymous = ProfileFactory()
        profile_anonymous.user.username = settings.ZDS_APP['member']['anonymous_account']
        profile_anonymous.user.save()
        profile_external = ProfileFactory()
        profile_external.user.username = settings.ZDS_APP['member']['external_account']
        profile_external.user.save()
        profile_ban_def = ProfileFactory()
        profile_ban_def.can_read = False
        profile_ban_def.can_write = False
        profile_ban_def.save()
        profile_ban_temp = ProfileFactory()
        profile_ban_temp.can_read = False
        profile_ban_temp.can_write = False
        profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1)
        profile_ban_temp.save()
        profile_unban = ProfileFactory()
        profile_unban.can_read = False
        profile_unban.can_write = False
        profile_unban.end_ban_read = datetime.now() - timedelta(days=1)
        profile_unban.save()
        profile_ls_def = ProfileFactory()
        profile_ls_def.can_write = False
        profile_ls_def.save()
        profile_ls_temp = ProfileFactory()
        profile_ls_temp.can_write = False
        profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1)
        profile_ls_temp.save()

        # groups

        bot = Group(name=settings.ZDS_APP['member']['bot_group'])
        bot.save()

        # associate account to groups
        bot.user_set.add(profile_anonymous.user)
        bot.user_set.add(profile_external.user)
        bot.user_set.add(profile_bot.user)
        bot.save()

        # test reachable user
        profiles_reacheable = Profile.objects.contactable_members().all()
        self.assertIn(profile_normal, profiles_reacheable)
        self.assertIn(profile_superuser, profiles_reacheable)
        self.assertNotIn(profile_inactive, profiles_reacheable)
        self.assertNotIn(profile_anonymous, profiles_reacheable)
        self.assertNotIn(profile_external, profiles_reacheable)
        self.assertNotIn(profile_bot, profiles_reacheable)
        self.assertIn(profile_unban, profiles_reacheable)
        self.assertNotIn(profile_ban_def, profiles_reacheable)
        self.assertNotIn(profile_ban_temp, profiles_reacheable)
        self.assertIn(profile_ls_def, profiles_reacheable)
        self.assertIn(profile_ls_temp, profiles_reacheable)
Ejemplo n.º 17
0
class MemberModelsTest(TestCase):

    def setUp(self):
        self.user1 = ProfileFactory()
        self.staff = StaffProfileFactory()

        # Create a forum for later test
        self.forumcat = CategoryFactory()
        self.forum = ForumFactory(category=self.forumcat)
        self.forumtopic = TopicFactory(forum=self.forum, author=self.staff.user)

    def test_get_absolute_url_for_details_of_member(self):
        self.assertEqual(self.user1.get_absolute_url(), '/membres/voir/{0}/'.format(self.user1.user.username))

    def test_get_avatar_url(self):
        # if no url was specified -> gravatar !
        self.assertEqual(self.user1.get_avatar_url(),
                         'https://secure.gravatar.com/avatar/{0}?d=identicon'.
                         format(md5(self.user1.user.email.lower().encode()).hexdigest()))
        # if an url is specified -> take it !
        user2 = ProfileFactory()
        testurl = 'http://test.com/avatar.jpg'
        user2.avatar_url = testurl
        self.assertEqual(user2.get_avatar_url(), testurl)

        # if url is relative, send absolute url
        gallerie_avtar = GalleryFactory()
        image_avatar = ImageFactory(gallery=gallerie_avtar)
        user2.avatar_url = image_avatar.physical.url
        self.assertNotEqual(user2.get_avatar_url(), image_avatar.physical.url)
        self.assertIn('http', user2.get_avatar_url())

    def test_get_post_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_post_count(), 0)
        # Post !
        PostFactory(topic=self.forumtopic, author=self.user1.user, position=1)
        # Should be 1
        self.assertEqual(self.user1.get_post_count(), 1)

    def test_get_topic_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_topic_count(), 0)
        # Create Topic !
        TopicFactory(forum=self.forum, author=self.user1.user)
        # Should be 1
        self.assertEqual(self.user1.get_topic_count(), 1)

    def test_get_tuto_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_tuto_count(), 0)
        # Create Tuto !
        minituto = PublishableContentFactory(type='TUTORIAL')
        minituto.authors.add(self.user1.user)
        minituto.gallery = GalleryFactory()
        minituto.save()
        # Should be 1
        self.assertEqual(self.user1.get_tuto_count(), 1)

    def test_get_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_tutos()), 0)
        # Create Tuto !
        minituto = PublishableContentFactory(type='TUTORIAL')
        minituto.authors.add(self.user1.user)
        minituto.gallery = GalleryFactory()
        minituto.save()
        # Should be 1
        tutos = self.user1.get_tutos()
        self.assertEqual(len(tutos), 1)
        self.assertEqual(minituto, tutos[0])

    def test_get_draft_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_draft_tutos()), 0)
        # Create Tuto !
        drafttuto = PublishableContentFactory(type='TUTORIAL')
        drafttuto.authors.add(self.user1.user)
        drafttuto.gallery = GalleryFactory()
        drafttuto.save()
        # Should be 1
        drafttutos = self.user1.get_draft_tutos()
        self.assertEqual(len(drafttutos), 1)
        self.assertEqual(drafttuto, drafttutos[0])

    def test_get_public_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_public_tutos()), 0)
        # Create Tuto !
        publictuto = PublishableContentFactory(type='TUTORIAL')
        publictuto.authors.add(self.user1.user)
        publictuto.gallery = GalleryFactory()
        publictuto.sha_public = 'whatever'
        publictuto.save()
        # Should be 0 because publication was not used
        publictutos = self.user1.get_public_tutos()
        self.assertEqual(len(publictutos), 0)
        PublishedContentFactory(author_list=[self.user1.user])
        self.assertEqual(len(self.user1.get_public_tutos()), 1)

    def test_get_validate_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_validate_tutos()), 0)
        # Create Tuto !
        validatetuto = PublishableContentFactory(type='TUTORIAL', author_list=[self.user1.user])
        validatetuto.sha_validation = 'whatever'
        validatetuto.save()
        # Should be 1
        validatetutos = self.user1.get_validate_tutos()
        self.assertEqual(len(validatetutos), 1)
        self.assertEqual(validatetuto, validatetutos[0])

    def test_get_beta_tutos(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_beta_tutos()), 0)
        # Create Tuto !
        betatetuto = PublishableContentFactory(type='TUTORIAL')
        betatetuto.authors.add(self.user1.user)
        betatetuto.gallery = GalleryFactory()
        betatetuto.sha_beta = 'whatever'
        betatetuto.save()
        # Should be 1
        betatetutos = self.user1.get_beta_tutos()
        self.assertEqual(len(betatetutos), 1)
        self.assertEqual(betatetuto, betatetutos[0])

    def test_get_article_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_tuto_count(), 0)
        # Create article !
        minituto = PublishableContentFactory(type='ARTICLE')
        minituto.authors.add(self.user1.user)
        minituto.gallery = GalleryFactory()
        minituto.save()
        # Should be 1
        self.assertEqual(self.user1.get_article_count(), 1)

    def test_get_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.save()
        # Should be 1
        articles = self.user1.get_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_public_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_public_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.sha_public = 'whatever'
        article.save()
        # Should be 0
        articles = self.user1.get_public_articles()
        self.assertEqual(len(articles), 0)
        # Should be 1
        PublishedContentFactory(author_list=[self.user1.user], type='ARTICLE')
        self.assertEqual(len(self.user1.get_public_articles()), 1)
        self.assertEqual(len(self.user1.get_public_tutos()), 0)

    def test_get_validate_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_validate_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.sha_validation = 'whatever'
        article.save()
        # Should be 1
        articles = self.user1.get_validate_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_draft_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_draft_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.save()
        # Should be 1
        articles = self.user1.get_draft_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_beta_articles(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_beta_articles()), 0)
        # Create article !
        article = PublishableContentFactory(type='ARTICLE')
        article.authors.add(self.user1.user)
        article.sha_beta = 'whatever'
        article.save()
        # Should be 1
        articles = self.user1.get_beta_articles()
        self.assertEqual(len(articles), 1)
        self.assertEqual(article, articles[0])

    def test_get_posts(self):
        # Start with 0
        self.assertEqual(len(self.user1.get_posts()), 0)
        # Post !
        apost = PostFactory(topic=self.forumtopic, author=self.user1.user, position=1)
        # Should be 1
        posts = self.user1.get_posts()
        self.assertEqual(len(posts), 1)
        self.assertEqual(apost, posts[0])

    def test_get_hidden_by_staff_posts_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 0)
        # Post and hide it by poster
        PostFactory(topic=self.forumtopic, author=self.user1.user, position=1, is_visible=False, editor=self.user1.user)
        # Should be 0
        self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 0)
        # Post and hide it by staff
        PostFactory(topic=self.forumtopic, author=self.user1.user, position=1, is_visible=False, editor=self.staff.user)
        # Should be 1
        self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 1)

    def test_get_hidden_by_staff_posts_count_staff_poster(self):
        # Start with 0
        self.assertEqual(self.staff.get_hidden_by_staff_posts_count(), 0)
        # Post and hide it by poster which is staff
        PostFactory(topic=self.forumtopic, author=self.staff.user, position=1, is_visible=False, editor=self.staff.user)
        # Should be 0 because even if poster is staff, he is the poster
        self.assertEqual(self.staff.get_hidden_by_staff_posts_count(), 0)

    def test_get_active_alerts_count(self):
        # Start with 0
        self.assertEqual(self.user1.get_active_alerts_count(), 0)
        # Post and Alert it !
        post = PostFactory(topic=self.forumtopic, author=self.user1.user, position=1)
        Alert.objects.create(author=self.user1.user, comment=post, scope='FORUM', pubdate=datetime.now())
        # Should be 1
        self.assertEqual(self.user1.get_active_alerts_count(), 1)

    def test_can_read_now(self):

        profile = ProfileFactory()
        profile.is_active = True
        profile.can_read = True
        self.assertTrue(profile.can_read_now())

        # Was banned in the past, ban no longer active
        profile = ProfileFactory()
        profile.end_ban_read = datetime.now() - timedelta(days=1)
        self.assertTrue(profile.can_read_now())

        profile = ProfileFactory()
        profile.is_active = True
        profile.can_read = False
        self.assertFalse(profile.can_read_now())

        # Ban is active
        profile = ProfileFactory()
        profile.is_active = True
        profile.can_read = False
        profile.end_ban_read = datetime.now() + timedelta(days=1)
        self.assertFalse(profile.can_read_now())

        self.user1.user.is_active = False
        self.assertFalse(self.user1.can_read_now())

    def test_can_write_now(self):

        self.user1.user.is_active = True
        self.user1.user.can_write = True
        self.assertTrue(self.user1.can_write_now())

        # Was banned in the past, ban no longer active
        profile = ProfileFactory()
        profile.can_write = True
        profile.end_ban_read = datetime.now() - timedelta(days=1)
        self.assertTrue(profile.can_write_now())

        profile = ProfileFactory()
        profile.can_write = False
        profile.is_active = True
        self.assertFalse(profile.can_write_now())

        # Ban is active
        profile = ProfileFactory()
        profile.can_write = False
        profile.end_ban_write = datetime.now() + timedelta(days=1)
        self.assertFalse(profile.can_write_now())

        self.user1.user.is_active = False
        self.user1.user.can_write = True
        self.assertFalse(self.user1.can_write_now())

    def test_get_followed_topics(self):
        # Start with 0
        self.assertEqual(len(TopicAnswerSubscription.objects.get_objects_followed_by(self.user1.user)), 0)
        # Follow !
        TopicAnswerSubscription.objects.toggle_follow(self.forumtopic, self.user1.user)
        # Should be 1
        topicsfollowed = TopicAnswerSubscription.objects.get_objects_followed_by(self.user1.user)
        self.assertEqual(len(topicsfollowed), 1)
        self.assertEqual(self.forumtopic, topicsfollowed[0])

    def test_get_city_with_wrong_ip(self):
        # Set a local IP to the user
        self.user1.last_ip_address = '127.0.0.1'
        # Then the get_city is not found and return empty string
        self.assertEqual('', self.user1.get_city())

        # Same goes for IPV6
        # Set a local IP to the user
        self.user1.last_ip_address = '0000:0000:0000:0000:0000:0000:0000:0001'
        # Then the get_city is not found and return empty string
        self.assertEqual('', self.user1.get_city())

    def test_remove_token_on_removing_from_dev_group(self):
        dev = DevProfileFactory()
        dev.github_token = 'test'
        dev.save()
        dev.user.save()

        self.assertEqual('test', dev.github_token)

        # remove dev from dev group
        dev.user.groups.clear()
        dev.user.save()

        self.assertEqual('', dev.github_token)

    def test_reachable_manager(self):
        # profile types
        profile_normal = ProfileFactory()
        profile_superuser = ProfileFactory()
        profile_superuser.user.is_superuser = True
        profile_superuser.user.save()
        profile_inactive = ProfileFactory()
        profile_inactive.user.is_active = False
        profile_inactive.user.save()
        profile_bot = ProfileFactory()
        profile_bot.user.username = settings.ZDS_APP['member']['bot_account']
        profile_bot.user.save()
        profile_anonymous = ProfileFactory()
        profile_anonymous.user.username = settings.ZDS_APP['member']['anonymous_account']
        profile_anonymous.user.save()
        profile_external = ProfileFactory()
        profile_external.user.username = settings.ZDS_APP['member']['external_account']
        profile_external.user.save()
        profile_ban_def = ProfileFactory()
        profile_ban_def.can_read = False
        profile_ban_def.can_write = False
        profile_ban_def.save()
        profile_ban_temp = ProfileFactory()
        profile_ban_temp.can_read = False
        profile_ban_temp.can_write = False
        profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1)
        profile_ban_temp.save()
        profile_unban = ProfileFactory()
        profile_unban.can_read = False
        profile_unban.can_write = False
        profile_unban.end_ban_read = datetime.now() - timedelta(days=1)
        profile_unban.save()
        profile_ls_def = ProfileFactory()
        profile_ls_def.can_write = False
        profile_ls_def.save()
        profile_ls_temp = ProfileFactory()
        profile_ls_temp.can_write = False
        profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1)
        profile_ls_temp.save()

        # groups

        bot = Group(name=settings.ZDS_APP['member']['bot_group'])
        bot.save()

        # associate account to groups
        bot.user_set.add(profile_anonymous.user)
        bot.user_set.add(profile_external.user)
        bot.user_set.add(profile_bot.user)
        bot.save()

        # test reachable user
        profiles_reacheable = Profile.objects.contactable_members().all()
        self.assertIn(profile_normal, profiles_reacheable)
        self.assertIn(profile_superuser, profiles_reacheable)
        self.assertNotIn(profile_inactive, profiles_reacheable)
        self.assertNotIn(profile_anonymous, profiles_reacheable)
        self.assertNotIn(profile_external, profiles_reacheable)
        self.assertNotIn(profile_bot, profiles_reacheable)
        self.assertIn(profile_unban, profiles_reacheable)
        self.assertNotIn(profile_ban_def, profiles_reacheable)
        self.assertNotIn(profile_ban_temp, profiles_reacheable)
        self.assertIn(profile_ls_def, profiles_reacheable)
        self.assertIn(profile_ls_temp, profiles_reacheable)

    def test_remove_hats_linked_to_group(self):
        # create a hat linked to a group
        hat_name = 'Test hat'
        hat, _ = Hat.objects.get_or_create(name__iexact=hat_name, defaults={'name': hat_name})
        group, _ = Group.objects.get_or_create(name='test_hat')
        hat.group = group
        hat.save()
        # add it to a user
        self.user1.hats.add(hat)
        self.user1.save()
        # the user shound't have the hat through their profile
        self.assertNotIn(hat, self.user1.hats.all())

    def tearDown(self):
        if os.path.isdir(settings.ZDS_APP['content']['repo_private_path']):
            shutil.rmtree(settings.ZDS_APP['content']['repo_private_path'])
        if os.path.isdir(settings.ZDS_APP['content']['repo_public_path']):
            shutil.rmtree(settings.ZDS_APP['content']['repo_public_path'])
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
Ejemplo n.º 18
0
class EditContentLicenseFunctionalTests(TutorialTestMixin, TestCase):
    """Test the detailed behavior of the feature, such as updates of the database or repositories."""
    def setUp(self):
        # Create a user
        self.author = ProfileFactory()

        # Create licenses
        self.license_1 = LicenceFactory()
        self.license_2 = LicenceFactory()

        # Create a content
        self.content = PublishableContentFactory(
            author_list=[self.author.user], add_license=False)

        # Get information to be reused in tests
        self.form_url = reverse('content:edit-license',
                                kwargs={'pk': self.content.pk})

        # Log in with an authorized user (e.g the author of the content) to perform the tests
        login_success = self.client.login(username=self.author.user.username,
                                          password='******')
        self.assertTrue(login_success)

    def test_form_function(self):
        """Test many use cases for the form."""
        test_cases = self.get_test_cases()
        for case_name, case in test_cases.items():
            with self.subTest(msg=case_name):
                self.enforce_preconditions(case['preconditions'])
                self.post_form(case['inputs'])
                self.check_effects(case['expected_outputs'])

    def get_test_cases(self):
        """List test cases for the license editing form."""
        return {
            'from blank to license 1, no preference, no udpate of preferences':
            {
                'preconditions': {
                    'content_license': None,
                    'preferred_license': None
                },
                'inputs': {
                    'license': self.license_1,
                    'update_preferred_license': False
                },
                'expected_outputs': {
                    'content_license': self.license_1,
                    'preferred_license': None
                }
            },
            'from blank to license 1, no preference, udpate of preferences': {
                'preconditions': {
                    'content_license': None,
                    'preferred_license': None
                },
                'inputs': {
                    'license': self.license_1,
                    'update_preferred_license': True
                },
                'expected_outputs': {
                    'content_license': self.license_1,
                    'preferred_license': self.license_1
                }
            },
            'from blank to license 2, no preference, no udpate of preferences':
            {
                'preconditions': {
                    'content_license': None,
                    'preferred_license': None
                },
                'inputs': {
                    'license': self.license_2,
                    'update_preferred_license': False
                },
                'expected_outputs': {
                    'content_license': self.license_2,
                    'preferred_license': None
                }
            },
            'from blank to license 2, no preference, udpate of preferences': {
                'preconditions': {
                    'content_license': None,
                    'preferred_license': None
                },
                'inputs': {
                    'license': self.license_2,
                    'update_preferred_license': True
                },
                'expected_outputs': {
                    'content_license': self.license_2,
                    'preferred_license': self.license_2
                }
            },
            'from blank to license 1, preference, no udpate of preferences': {
                'preconditions': {
                    'content_license': None,
                    'preferred_license': self.license_2
                },
                'inputs': {
                    'license': self.license_1,
                    'update_preferred_license': False
                },
                'expected_outputs': {
                    'content_license': self.license_1,
                    'preferred_license': self.license_2
                }
            },
            'from blank to license 1, preference, udpate of preferences': {
                'preconditions': {
                    'content_license': None,
                    'preferred_license': self.license_2
                },
                'inputs': {
                    'license': self.license_1,
                    'update_preferred_license': True
                },
                'expected_outputs': {
                    'content_license': self.license_1,
                    'preferred_license': self.license_1
                }
            },
            'from license 1 to license 2, no preference, no udpate of preferences':
            {
                'preconditions': {
                    'content_license': self.license_1,
                    'preferred_license': None
                },
                'inputs': {
                    'license': self.license_2,
                    'update_preferred_license': False
                },
                'expected_outputs': {
                    'content_license': self.license_2,
                    'preferred_license': None
                }
            },
            'from license 1 to license 2, no preference, udpate of preferences':
            {
                'preconditions': {
                    'content_license': self.license_1,
                    'preferred_license': None
                },
                'inputs': {
                    'license': self.license_2,
                    'update_preferred_license': True
                },
                'expected_outputs': {
                    'content_license': self.license_2,
                    'preferred_license': self.license_2
                }
            },
        }

    def enforce_preconditions(self, preconditions):
        """Prepare the test environment to match given preconditions"""

        # Enforce preconditions for license in database
        self.content.licence = preconditions['content_license']
        self.content.save()
        self.assertEqual(self.content.licence,
                         preconditions['content_license'])

        # Enforce preconditions for license in repository
        versioned = self.content.load_version()
        versioned.licence = preconditions['content_license']
        sha = versioned.repo_update_top_container('Title', self.content.slug,
                                                  'introduction', 'conclusion')
        updated_versioned = self.content.load_version(sha)
        self.assertEqual(updated_versioned.licence,
                         preconditions['content_license'])

        # Enforce preconditions for preferred license
        self.author.licence = preconditions['preferred_license']
        self.author.save()
        updated_profile = Profile.objects.get(pk=self.author.pk)
        self.assertEqual(updated_profile.licence,
                         preconditions['preferred_license'])

    def post_form(self, inputs):
        """Post the form with given inputs."""
        form_data = {
            'license': inputs['license'].pk,
            'update_preferred_license': inputs['update_preferred_license']
        }
        self.client.post(self.form_url, form_data)

    def check_effects(self, expected_outputs):
        """Check the effects of having sent the form."""

        # Check updating of the database
        updated_content = PublishableContent.objects.get(pk=self.content.pk)
        updated_profile = Profile.objects.get(pk=self.author.pk)
        self.assertEqual(updated_content.licence,
                         expected_outputs['content_license'])
        self.assertEqual(updated_profile.licence,
                         expected_outputs['preferred_license'])

        # Check updating of the repository
        versioned = updated_content.load_version()
        self.assertEqual(versioned.licence,
                         expected_outputs['content_license'])
Ejemplo n.º 19
0
class MemberDetailAPITest(APITestCase):
    def setUp(self):
        self.client = APIClient()
        self.profile = ProfileFactory()

        client_oauth2 = create_oauth2_client(self.profile.user)
        self.client_authenticated = APIClient()
        authenticate_client(self.client_authenticated, client_oauth2,
                            self.profile.user.username, 'hostel77')

        get_cache(extensions_api_settings.DEFAULT_USE_CACHE).clear()

    def test_detail_of_a_member(self):
        """
        Gets all information about a user.
        """
        response = self.client.get(
            reverse('api-member-detail', args=[self.profile.pk]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.profile.pk, response.data.get('pk'))
        self.assertEqual(self.profile.user.username,
                         response.data.get('username'))
        self.assertIsNone(response.data.get('email'))
        self.assertEqual(self.profile.user.is_active,
                         response.data.get('is_active'))
        self.assertIsNotNone(response.data.get('date_joined'))
        self.assertEqual(self.profile.site, response.data.get('site'))
        self.assertEqual(self.profile.get_avatar_url(),
                         response.data.get('avatar_url'))
        self.assertEqual(self.profile.biography,
                         response.data.get('biography'))
        self.assertEqual(self.profile.sign, response.data.get('sign'))
        self.assertFalse(response.data.get('show_email'))
        self.assertEqual(self.profile.show_sign,
                         response.data.get('show_sign'))
        self.assertEqual(self.profile.hover_or_click,
                         response.data.get('hover_or_click'))
        self.assertEqual(self.profile.email_for_answer,
                         response.data.get('email_for_answer'))

    def test_detail_of_a_member_who_accepts_to_show_his_email(self):
        """
        Gets all information about a user but not his email because the request isn't authenticated.
        """
        self.profile.show_email = True
        self.profile.save()

        response = self.client.get(
            reverse('api-member-detail', args=[self.profile.pk]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIsNone(response.data.get('email'))

    def test_detail_of_a_member_who_accepts_to_show_his_email_with_authenticated_request(
            self):
        """
        Gets all information about a user and his email.
        """
        self.profile.show_email = True
        self.profile.save()

        response = self.client_authenticated.get(
            reverse('api-member-detail', args=[self.profile.pk]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(response.data.get('show_email'))
        self.assertEqual(self.profile.user.email, response.data.get('email'))

    def test_detail_of_a_member_not_present(self):
        """
        Gets an error when the user isn't present in the database.
        """
        response = self.client.get(reverse('api-member-detail', args=[42]))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_member_details_without_any_change(self):
        """
        Updates a member but without any changes.
        """
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.profile.pk, response.data.get('pk'))
        self.assertEqual(self.profile.user.username,
                         response.data.get('username'))
        self.assertEqual(self.profile.user.email, response.data.get('email'))
        self.assertEqual(self.profile.user.is_active,
                         response.data.get('is_active'))
        self.assertIsNotNone(response.data.get('date_joined'))
        self.assertEqual(self.profile.site, response.data.get('site'))
        self.assertEqual(self.profile.avatar_url,
                         response.data.get('avatar_url'))
        self.assertEqual(self.profile.biography,
                         response.data.get('biography'))
        self.assertEqual(self.profile.sign, response.data.get('sign'))
        self.assertFalse(response.data.get('show_email'))
        self.assertEqual(self.profile.show_sign,
                         response.data.get('show_sign'))
        self.assertEqual(self.profile.hover_or_click,
                         response.data.get('hover_or_click'))
        self.assertEqual(self.profile.email_for_answer,
                         response.data.get('email_for_answer'))

    def test_update_member_details_not_exist(self):
        """
        Tries to update a member who doesn't exist in the database.
        """
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[42]))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_member_details_with_a_problem_in_authentication(self):
        """
        Tries to update a member with a authentication not valid.
        """
        response = self.client.put(
            reverse('api-member-detail', args=[self.profile.pk]))
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_update_member_details_without_permissions(self):
        """
        Tries to update information about a member when the user isn't the target user.
        """
        another = ProfileFactory()
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[another.pk]))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_update_member_details_username(self):
        """
        Updates username of a member given.
        """
        data = {'username': '******'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('username'), data.get('username'))

    def test_update_member_details_email(self):
        """
        Updates email of a member given.
        """
        data = {'email': '*****@*****.**'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('email'), data.get('email'))

    def test_update_member_details_with_email_malformed(self):
        """
        Gets an error when the user try to update a member given with an email malformed.
        """
        data = {'email': 'wrong email'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_update_member_details_site(self):
        """
        Updates site of a member given.
        """
        data = {'site': 'www.zestedesavoir.com'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('site'), data.get('site'))

    def test_update_member_details_avatar(self):
        """
        Updates url of the member's avatar given.
        """
        data = {'avatar_url': 'www.zestedesavoir.com'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('avatar_url'),
                         data.get('avatar_url'))

    def test_update_member_details_biography(self):
        """
        Updates biography of a member given.
        """
        data = {'biography': 'It is my awesome biography.'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('biography'), data.get('biography'))

    def test_update_member_details_sign(self):
        """
        Updates sign of a member given.
        """
        data = {'sign': 'It is my awesome sign.'}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('sign'), data.get('sign'))

    def test_update_member_details_show_email(self):
        """
        Updates show email of a member given.
        """
        data = {'show_email': True}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('show_email'),
                         data.get('show_email'))

        data = {'show_email': False}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('show_email'),
                         data.get('show_email'))

    def test_update_member_details_show_sign(self):
        """
        Updates show sign of a member given.
        """
        data = {'show_sign': True}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('show_sign'), data.get('show_sign'))

        data = {'show_sign': False}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('show_sign'), data.get('show_sign'))

    def test_update_member_details_hover_or_click(self):
        """
        Updates hover or click of a member given.
        """
        data = {'hover_or_click': True}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('hover_or_click'),
                         data.get('hover_or_click'))

        data = {'hover_or_click': False}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('hover_or_click'),
                         data.get('hover_or_click'))

    def test_update_member_details_email_for_answer(self):
        """
        Updates email for answer of a member given.
        """
        data = {'email_for_answer': True}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('email_for_answer'),
                         data.get('email_for_answer'))

        data = {'email_for_answer': False}
        response = self.client_authenticated.put(
            reverse('api-member-detail', args=[self.profile.pk]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get('email_for_answer'),
                         data.get('email_for_answer'))

    def test_member_detail_url_with_post_method(self):
        """
        Gets an error when the user try to make a request with a method not allowed.
        """
        response = self.client.post(
            reverse('api-member-detail', args=[self.profile.pk]))
        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)

    def test_member_detail_url_with_delete_method(self):
        """
        Gets an error when the user try to make a request with a method not allowed.
        """
        response = self.client.delete(
            reverse('api-member-detail', args=[self.profile.pk]))
        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)
Ejemplo n.º 20
0
    def test_reachable_manager(self):
        # profile types
        profile_normal = ProfileFactory()
        profile_superuser = ProfileFactory()
        profile_superuser.user.is_superuser = True
        profile_superuser.user.save()
        profile_inactive = ProfileFactory()
        profile_inactive.user.is_active = False
        profile_inactive.user.save()
        profile_bot = ProfileFactory()
        profile_bot.user.username = settings.ZDS_APP['member']['bot_account']
        profile_bot.user.save()
        profile_anonymous = ProfileFactory()
        profile_anonymous.user.username = settings.ZDS_APP['member']['anonymous_account']
        profile_anonymous.user.save()
        profile_external = ProfileFactory()
        profile_external.user.username = settings.ZDS_APP['member']['external_account']
        profile_external.user.save()
        profile_ban_def = ProfileFactory()
        profile_ban_def.can_read = False
        profile_ban_def.can_write = False
        profile_ban_def.save()
        profile_ban_temp = ProfileFactory()
        profile_ban_temp.can_read = False
        profile_ban_temp.can_write = False
        profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1)
        profile_ban_temp.save()
        profile_unban = ProfileFactory()
        profile_unban.can_read = False
        profile_unban.can_write = False
        profile_unban.end_ban_read = datetime.now() - timedelta(days=1)
        profile_unban.save()
        profile_ls_def = ProfileFactory()
        profile_ls_def.can_write = False
        profile_ls_def.save()
        profile_ls_temp = ProfileFactory()
        profile_ls_temp.can_write = False
        profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1)
        profile_ls_temp.save()

        # groups

        bot = Group(name=settings.ZDS_APP['member']['bot_group'])
        bot.save()

        # associate account to groups
        bot.user_set.add(profile_anonymous.user)
        bot.user_set.add(profile_external.user)
        bot.user_set.add(profile_bot.user)
        bot.save()

        # test reachable user
        profiles_reacheable = Profile.objects.contactable_members().all()
        self.assertIn(profile_normal, profiles_reacheable)
        self.assertIn(profile_superuser, profiles_reacheable)
        self.assertNotIn(profile_inactive, profiles_reacheable)
        self.assertNotIn(profile_anonymous, profiles_reacheable)
        self.assertNotIn(profile_external, profiles_reacheable)
        self.assertNotIn(profile_bot, profiles_reacheable)
        self.assertIn(profile_unban, profiles_reacheable)
        self.assertNotIn(profile_ban_def, profiles_reacheable)
        self.assertNotIn(profile_ban_temp, profiles_reacheable)
        self.assertIn(profile_ls_def, profiles_reacheable)
        self.assertIn(profile_ls_temp, profiles_reacheable)