예제 #1
0
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(category=self.category,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()
예제 #2
0
def split_posts_to_new_thread(request, thread, validated_data):
    new_thread = Thread(
        category=validated_data['category'],
        started_on=thread.started_on,
        last_post_on=thread.last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    for post in validated_data['posts']:
        post.move(new_thread)
        post.save()

    thread.synchronize()
    thread.save()

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    thread.category.synchronize()
    thread.category.save()

    if new_thread.category != thread.category:
        new_thread.category.synchronize()
        new_thread.category.save()
예제 #3
0
    def create(self, request):
        allow_use_private_threads(request.user)
        if not request.user.acl_cache['can_start_private_threads']:
            raise PermissionDenied(_("You can't start private threads."))

        request.user.lock()

        # Initialize empty instances for new thread
        thread = Thread()
        post = Post(thread=thread)

        # Put them through posting pipeline
        posting = PostingEndpoint(
            request,
            PostingEndpoint.START,
            tree_name=PRIVATE_THREADS_ROOT_NAME,
            thread=thread,
            post=post,
        )

        if posting.is_valid():
            posting.save()

            return Response({
                'id': thread.pk,
                'title': thread.title,
                'url': thread.get_absolute_url(),
            })
        else:
            return Response(posting.errors, status=400)
예제 #4
0
    def create(self, request):
        # Initialize empty instances for new thread
        thread = Thread()
        post = Post(thread=thread)
        tag = Tag(thread=thread)

        # Put them through posting pipeline
        posting = PostingEndpoint(
            request,
            PostingEndpoint.START,
            tree_name=THREADS_ROOT_NAME,
            thread=thread,
            post=post,
            tag=tag,
        )

        if posting.is_valid():
            posting.save()

            return Response({
                'id': thread.pk,
                'title': thread.title,
                'url': thread.get_absolute_url(),
            })
        else:
            return Response(posting.errors, status=400)
예제 #5
0
    def setUp(self):
        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(forum=self.forum,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(forum=self.forum,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()
예제 #6
0
def split_posts_to_new_thread(request, thread, validated_data, posts):
    new_thread = Thread(
        category=validated_data['category'],
        started_on=thread.started_on,
        last_post_on=thread.last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    for post in posts:
        post.move(new_thread)
        post.save()

    thread.synchronize()
    thread.save()

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    thread.category.synchronize()
    thread.category.save()

    if new_thread.category != thread.category:
        new_thread.category.synchronize()
        new_thread.category.save()
예제 #7
0
파일: test_events.py 프로젝트: Didan/Misago
class EventsAPITests(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        add_acl(self.user, self.category)
        add_acl(self.user, self.thread)

    def test_record_event(self):
        """record_event registers event in thread"""
        message = "%(user)s has changed this thread to announcement."
        event = record_event(self.user, self.thread, "announcement", message, {
            'user': (u"Łob", self.user.get_absolute_url())
        })

        self.assertTrue(event.is_valid)
        self.assertTrue(event.message.endswith(message[8:]))
        self.assertTrue(self.thread.has_events)

    def test_add_events_to_posts(self):
        """add_events_to_posts makes posts event-aware"""
        message = "Test event was recorded."

        for p in xrange(2):
            reply_thread(self.thread, posted_on=timezone.now())
        event = record_event(self.user, self.thread, "check", message)
        for p in xrange(2):
            reply_thread(self.thread, posted_on=timezone.now())

        posts = [p for p in self.thread.post_set.all().order_by('id')]
        add_events_to_posts(self.user, self.thread, posts)

        for i, post in enumerate(posts):
            if i == 1:
                self.assertEqual(post.events[0].message, message)
            else:
                self.assertEqual(post.events, [])
예제 #8
0
class EventsApiTests(TestCase):
    def setUp(self):
        self.user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                                  "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        add_acl(self.user, self.category)
        add_acl(self.user, self.thread)

    def test_record_event_with_context(self):
        """record_event registers event with context in thread"""
        request = MockRequest(self.user)
        context = {'user': '******'}
        event = record_event(request, self.thread, 'announcement', context)

        event_post = self.thread.post_set.order_by('-id')[:1][0]
        self.assertEqual(self.thread.last_post, event_post)
        self.assertTrue(self.thread.has_events)
        self.assertTrue(self.thread.last_post_is_event)

        self.assertEqual(event.pk, event_post.pk)
        self.assertTrue(event_post.is_event)
        self.assertEqual(event_post.event_type, 'announcement')
        self.assertEqual(event_post.event_context, context)
        self.assertEqual(event_post.poster_id, request.user.pk)

    def test_record_event_is_read(self):
        """record_event makes recorded event read to its author"""
        request = MockRequest(self.user)
        event = record_event(request, self.thread, 'announcement')

        self.user.postread_set.get(
            category=self.category,
            thread=self.thread,
            post=event,
        )
예제 #9
0
class EventsAPITests(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        add_acl(self.user, self.category)
        add_acl(self.user, self.thread)

    def test_record_event(self):
        """record_event registers event in thread"""
        message = "%(user)s has changed this thread to announcement."
        event = record_event(self.user, self.thread, "announcement", message,
                             {'user': (u"Łob", self.user.get_absolute_url())})

        self.assertTrue(event.is_valid)
        self.assertTrue(event.message.endswith(message[8:]))
        self.assertTrue(self.thread.has_events)

    def test_add_events_to_posts(self):
        """add_events_to_posts makes posts event-aware"""
        message = "Test event was recorded."

        for p in xrange(2):
            reply_thread(self.thread, posted_on=timezone.now())
        event = record_event(self.user, self.thread, "check", message)
        for p in xrange(2):
            reply_thread(self.thread, posted_on=timezone.now())

        posts = [p for p in self.thread.post_set.all().order_by('id')]
        add_events_to_posts(self.user, self.thread, posts)

        for i, post in enumerate(posts):
            if i == 1:
                self.assertEqual(post.events[0].message, message)
            else:
                self.assertEqual(post.events, [])
예제 #10
0
    def find_mode(self, request, *args, **kwargs):
        """
        First step: guess from request what kind of view we are
        """
        is_submit = request.method == 'POST' and 'submit' in request.POST
        if is_submit:
            request.user.lock()

        forum = self.get_forum(request, lock=is_submit, **kwargs)

        thread = None
        post = None

        if 'thread_id' in kwargs:
            thread = self.get_thread(request,
                                     lock=is_submit,
                                     queryset=forum.thread_set,
                                     **kwargs)

        if thread:
            mode = REPLY
        else:
            mode = START
            thread = Thread(forum=forum)

        if not post:
            post = Post(forum=forum, thread=thread)

        return mode, forum, thread, post
예제 #11
0
    def setUp(self):
        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(
            forum=self.forum,
            weight=0,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()
예제 #12
0
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime
        )

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()
예제 #13
0
def create_thread(forum):
    thread = Thread()
    thread.forum = forum
    thread.name = 'Test Thread'
    thread.slug = 'test-thread'
    thread.start = timezone.now()
    thread.last = timezone.now()
    thread.save(force_insert=True)
    return thread
예제 #14
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()
예제 #15
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(forum=self.forum,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()
예제 #16
0
    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=other_thread,
            poster_name='Admin',
            poster_ip='127.0.0.1',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")
예제 #17
0
class EventModelTests(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

    def test_is_event_valid(self):
        """event is_valid flag returns valid value"""
        event = Event.objects.create(
            category=self.category,
            thread=self.thread,
            author=self.user,
            message="Lorem ipsum",
            author_name=self.user.username,
            author_slug=self.user.slug
        )

        update_event_checksum(event)

        self.assertTrue(is_event_valid(event))
        self.assertTrue(event.is_valid)

        event.message = "Ipsum lorem"

        self.assertFalse(is_event_valid(event))
        self.assertFalse(event.is_valid)
class EventsAPITests(TestCase):
    def setUp(self):
        self.user = UserModel.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        add_acl(self.user, self.category)
        add_acl(self.user, self.thread)

    def test_record_event_with_context(self):
        """record_event registers event with context in thread"""
        request = MockRequest(self.user)
        context = {'user': '******'}
        event = record_event(request, self.thread, 'announcement', context)

        event_post = self.thread.post_set.order_by('-id')[:1][0]
        self.assertEqual(self.thread.last_post, event_post)
        self.assertTrue(self.thread.has_events)
        self.assertTrue(self.thread.last_post_is_event)

        self.assertEqual(event.pk, event_post.pk)
        self.assertTrue(event_post.is_event)
        self.assertEqual(event_post.event_type, 'announcement')
        self.assertEqual(event_post.event_context, context)
        self.assertEqual(event_post.poster_id, request.user.pk)
        self.assertEqual(event_post.poster_ip, request.user_ip)
    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=other_thread,
            poster_name='Admin',
            poster_ip='127.0.0.1',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")
예제 #20
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        self.post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime
        )

        update_post_checksum(self.post)
        self.post.save(update_fields=['checksum'])

        self.thread.first_post = self.post
        self.thread.last_post = self.post
        self.thread.save()
예제 #21
0
class EventModelTests(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(forum=self.forum,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

    def test_is_event_valid(self):
        """event is_valid flag returns valid value"""
        event = Event.objects.create(forum=self.forum,
                                     thread=self.thread,
                                     author=self.user,
                                     message="Lorem ipsum",
                                     author_name=self.user.username,
                                     author_slug=self.user.slug)

        update_event_checksum(event)

        self.assertTrue(is_event_valid(event))
        self.assertTrue(event.is_valid)

        event.message = "Ipsum lorem"

        self.assertFalse(is_event_valid(event))
        self.assertFalse(event.is_valid)
예제 #22
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(
            forum=self.forum,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()
예제 #23
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()
예제 #24
0
파일: posting.py 프로젝트: qhhonx/Misago
    def find_mode(self, request, *args, **kwargs):
        """
        First step: guess from request what kind of view we are
        """
        is_post = request.method == 'POST'

        if 'forum_id' in kwargs:
            mode = START
            user = request.user

            forum = self.get_forum(request, lock=is_post, **kwargs)
            thread = Thread(forum=forum)
            post = Post(forum=forum, thread=thread)
            quote = Post(0)
        elif 'thread_id' in kwargs:
            thread = self.get_thread(request, lock=is_post, **kwargs)
            forum = thread.forum

        return mode, forum, thread, post, quote
예제 #25
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(
            forum=self.forum,
            weight=0,
            started_on=datetime,
            starter_name="Tester",
            starter_slug="tester",
            last_post_on=datetime,
            last_poster_name="Tester",
            last_poster_slug="tester",
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        self.post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip="127.0.0.1",
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        update_post_checksum(self.post)
        self.post.save(update_fields=["checksum"])

        self.thread.first_post = self.post
        self.thread.last_post = self.post
        self.thread.save()
예제 #26
0
class ThreadModelTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(
            forum=self.forum,
            weight=0,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_synchronize(self):
        """synchronize method updates thread data to reflect its contents"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        self.assertEqual(self.thread.replies, 0)

        datetime = timezone.now() + timedelta(5)
        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        # first sync call, updates last thread
        self.thread.synchronize()

        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 1)

        # add moderated post
        moderated_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(5),
            updated_on=datetime + timedelta(5),
            is_moderated=True)

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 1)

        # add hidden post
        hidden_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(10),
            updated_on=datetime + timedelta(10),
            is_hidden=True)

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_moderated_posts)
        self.assertTrue(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 2)

        # unhide post
        hidden_post.is_hidden = False
        hidden_post.save()

        # last post changed to unhidden one
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 2)

        # unmoderate post
        moderated_post.is_moderated = False
        moderated_post.save()

        # last post not changed, but flags and count did
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 3)

    def test_set_first_post(self):
        """set_first_post sets first post and poster data on thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.set_first_post(post)
        self.assertEqual(self.thread.first_post, post)
        self.assertEqual(self.thread.started_on, post.posted_on)
        self.assertEqual(self.thread.starter, user)
        self.assertEqual(self.thread.starter_name, user.username)
        self.assertEqual(self.thread.starter_slug, user.slug)

    def test_set_last_post(self):
        """set_last_post sets first post and poster data on thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.set_last_post(post)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)

    def test_move(self):
        """move(new_forum) moves thread to other forum"""
        # pick category instead of forum (so we don't have to create one)
        new_forum = Forum.objects.filter(role="category")[:1][0]

        self.thread.move(new_forum)
        self.assertEqual(self.thread.forum, new_forum)

        for post in self.thread.post_set.all():
            self.assertEqual(post.forum_id, new_forum.id)

    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            forum=self.forum,
            weight=0,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            forum=self.forum,
            thread=other_thread,
            poster_name='Admin',
            poster_ip='127.0.0.1',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")
예제 #27
0
class ThreadParticipantTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime
        )

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_delete_participant(self):
        """delete_participant deletes participant from thread"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")
        other_user = User.objects.create_user(
            "Bob2", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.add_participant(self.thread, user)
        ThreadParticipant.objects.add_participant(self.thread, other_user)
        self.assertEqual(self.thread.participants.count(), 2)

        ThreadParticipant.objects.remove_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        with self.assertRaises(ThreadParticipant.DoesNotExist):
            participation = ThreadParticipant.objects.get(
                thread=self.thread, user=user)

    def test_add_participant(self):
        """add_participant adds participant to thread"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.add_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        participation = ThreadParticipant.objects.get(
            thread=self.thread, user=user)
        self.assertFalse(participation.is_owner)

        ThreadParticipant.objects.add_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 2)

    def test_set_owner(self):
        """set_owner makes user thread owner"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.set_owner(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        participation = ThreadParticipant.objects.get(
            thread=self.thread, user=user)
        self.assertTrue(participation.is_owner)
        self.assertEqual(user, participation.user)

        other_user = User.objects.create_user(
            "Bob2", "*****@*****.**", "Pass.123")
        ThreadParticipant.objects.set_owner(self.thread, other_user)
        self.assertEqual(self.thread.participants.count(), 2)

        participation = ThreadParticipant.objects.get(
            thread=self.thread, user=user)
        self.assertFalse(participation.is_owner)
예제 #28
0
class PostModelTests(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        self.post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime
        )

        update_post_checksum(self.post)
        self.post.save(update_fields=['checksum'])

        self.thread.first_post = self.post
        self.thread.last_post = self.post
        self.thread.save()

    def test_merge_invalid(self):
        """see if attempts for invalid merges fail"""
        with self.assertRaises(ValueError):
            self.post.merge(self.post)

        User = get_user_model()
        other_user = User.objects.create_user("Jeff", "*****@*****.**", "Pass.123")

        other_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=other_user,
            poster_name=other_user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5)
        )

        with self.assertRaises(ValueError):
            self.post.merge(other_post)

        other_thread = Thread.objects.create(
            category=self.category,
            started_on=timezone.now(),
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=timezone.now(),
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        other_post = Post.objects.create(
            category=self.category,
            thread=other_thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5)
        )

        with self.assertRaises(ValueError):
            self.post.merge(other_post)

        other_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name=other_user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5)
        )

        with self.assertRaises(ValueError):
            self.post.merge(other_post)
        with self.assertRaises(ValueError):
            other_post.merge(self.post)

    def test_merge(self):
        """merge method merges two posts into one"""
        other_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="I am other message!",
            parsed="<p>I am other message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5)
        )

        other_post.merge(self.post)

        self.assertIn(other_post.original, self.post.original)
        self.assertIn(other_post.parsed, self.post.parsed)
        self.assertTrue(self.post.is_valid)

    def test_move(self):
        """move method moves post to other thread"""
        new_thread = Thread.objects.create(
            category=self.category,
            started_on=timezone.now(),
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=timezone.now(),
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.post.move(new_thread)

        self.assertEqual(self.post.thread, new_thread)
예제 #29
0
class ThreadModelTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name='Tester',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.synchronize()
        self.thread.save()

    def test_synchronize(self):
        """synchronize method updates thread data to reflect its contents"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")

        self.assertEqual(self.thread.replies, 0)

        datetime = timezone.now() + timedelta(5)
        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        # first sync call, updates last thread
        self.thread.synchronize()

        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 1)

        # add unapproved post
        unapproved_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(5),
            updated_on=datetime + timedelta(5),
            is_unapproved=True,
        )

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 1)

        # add hidden post
        hidden_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(10),
            updated_on=datetime + timedelta(10),
            is_hidden=True,
        )

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_unapproved_posts)
        self.assertTrue(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 2)

        # unhide post
        hidden_post.is_hidden = False
        hidden_post.save()

        # last post changed to unhidden one
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 2)

        # unmoderate post
        unapproved_post.is_unapproved = False
        unapproved_post.save()

        # last post not changed, but flags and count did
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 3)

        # add event post
        event = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="-",
            parsed="-",
            checksum="nope",
            posted_on=datetime + timedelta(10),
            updated_on=datetime + timedelta(10),
            is_event=True,
        )

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, event)
        self.assertEqual(self.thread.last_post_on, event.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertTrue(self.thread.last_post_is_event)
        self.assertTrue(self.thread.has_events)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        # events don't count to reply count
        self.assertEqual(self.thread.replies, 3)

        # create another post to provoke other has_events resolution path
        Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.synchronize()
        self.assertFalse(self.thread.last_post_is_event)
        self.assertTrue(self.thread.has_events)

        # remove event
        event.delete()

        self.thread.synchronize()
        self.assertFalse(self.thread.last_post_is_event)
        self.assertFalse(self.thread.has_events)

        # has poll flag
        self.assertFalse(self.thread.has_poll)

        Poll.objects.create(
            thread=self.thread,
            category=self.category,
            poster_name='test',
            poster_slug='test',
            choices=[],
        )

        self.thread.synchronize()
        self.assertTrue(self.thread.has_poll)

    def test_set_first_post(self):
        """set_first_post sets first post and poster data on thread"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.set_first_post(post)
        self.assertEqual(self.thread.first_post, post)
        self.assertEqual(self.thread.started_on, post.posted_on)
        self.assertEqual(self.thread.starter, user)
        self.assertEqual(self.thread.starter_name, user.username)
        self.assertEqual(self.thread.starter_slug, user.slug)

    def test_set_last_post(self):
        """set_last_post sets first post and poster data on thread"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.set_last_post(post)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)

    def test_set_best_answer(self):
        """set_best_answer sets best answer and setter data on thread"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")

        best_answer = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now(),
            updated_on=timezone.now(),
            is_protected=True,
        )

        self.thread.synchronize()
        self.thread.save()

        self.thread.set_best_answer(user, best_answer)
        self.thread.save()

        self.assertEqual(self.thread.best_answer, best_answer)
        self.assertTrue(self.thread.has_best_answer)
        self.assertTrue(self.thread.best_answer_is_protected)
        self.assertTrue(self.thread.best_answer_marked_on)
        self.assertEqual(self.thread.best_answer_marked_by, user)
        self.assertEqual(self.thread.best_answer_marked_by_name, user.username)
        self.assertEqual(self.thread.best_answer_marked_by_slug, user.slug)

        # clear best answer
        self.thread.clear_best_answer()

        self.assertIsNone(self.thread.best_answer)
        self.assertFalse(self.thread.has_best_answer)
        self.assertFalse(self.thread.best_answer_is_protected)
        self.assertIsNone(self.thread.best_answer_marked_on)
        self.assertIsNone(self.thread.best_answer_marked_by)
        self.assertIsNone(self.thread.best_answer_marked_by_name)
        self.assertIsNone(self.thread.best_answer_marked_by_slug)

    def test_set_invalid_best_answer(self):
        """set_best_answer implements some assertions for data integrity"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")

        other_thread = testutils.post_thread(self.category)
        with self.assertRaises(ValueError):
            self.thread.set_best_answer(user, other_thread.first_post)

        with self.assertRaises(ValueError):
            self.thread.set_best_answer(user, self.thread.first_post)

        with self.assertRaises(ValueError):
            reply = testutils.reply_thread(self.thread, is_hidden=True)
            self.thread.set_best_answer(user, reply)

        with self.assertRaises(ValueError):
            reply = testutils.reply_thread(self.thread, is_unapproved=True)
            self.thread.set_best_answer(user, reply)

    def test_move(self):
        """move(new_category) moves thread to other category"""
        root_category = Category.objects.root_category()
        Category(
            name='New Category',
            slug='new-category',
        ).insert_at(
            root_category,
            position='last-child',
            save=True,
        )
        new_category = Category.objects.get(slug='new-category')

        self.thread.move(new_category)
        self.assertEqual(self.thread.category, new_category)

        for post in self.thread.post_set.all():
            self.assertEqual(post.category_id, new_category.id)

    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=other_thread,
            poster_name='Admin',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")

    def test_delete_private_thread(self):
        """
        private thread gets deleted automatically
        when there are no participants left in it
        """
        user_a = UserModel.objects.create_user("Bob", "*****@*****.**",
                                               "Pass.123")
        user_b = UserModel.objects.create_user("Weebl", "*****@*****.**",
                                               "Pass.123")

        ThreadParticipant.objects.add_participants(self.thread,
                                                   [user_a, user_b])
        self.assertEqual(self.thread.participants.count(), 2)

        user_a.delete()
        Thread.objects.get(id=self.thread.id)

        user_b.delete()
        with self.assertRaises(Thread.DoesNotExist):
            Thread.objects.get(id=self.thread.id)
class ThreadModelTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_synchronize(self):
        """synchronize method updates thread data to reflect its contents"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        self.assertEqual(self.thread.replies, 0)

        datetime = timezone.now() + timedelta(5)
        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        # first sync call, updates last thread
        self.thread.synchronize()

        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 1)

        # add unapproved post
        unapproved_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(5),
            updated_on=datetime + timedelta(5),
            is_unapproved=True,
        )

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 1)

        # add hidden post
        hidden_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(10),
            updated_on=datetime + timedelta(10),
            is_hidden=True,
        )

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_unapproved_posts)
        self.assertTrue(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 2)

        # unhide post
        hidden_post.is_hidden = False
        hidden_post.save()

        # last post changed to unhidden one
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 2)

        # unmoderate post
        unapproved_post.is_unapproved = False
        unapproved_post.save()

        # last post not changed, but flags and count did
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertEqual(self.thread.replies, 3)

        # add event post
        event = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="-",
            parsed="-",
            checksum="nope",
            posted_on=datetime + timedelta(10),
            updated_on=datetime + timedelta(10),
            is_event=True,
        )

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, event)
        self.assertEqual(self.thread.last_post_on, event.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertTrue(self.thread.last_post_is_event)
        self.assertTrue(self.thread.has_events)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_unapproved_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        # events don't count to reply count
        self.assertEqual(self.thread.replies, 3)

        # create another post to provoke other has_events resolution path
        Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.synchronize()
        self.assertFalse(self.thread.last_post_is_event)
        self.assertTrue(self.thread.has_events)

        # remove event
        event.delete()

        self.thread.synchronize()
        self.assertFalse(self.thread.last_post_is_event)
        self.assertFalse(self.thread.has_events)

        # has poll flag
        self.assertFalse(self.thread.has_poll)

        Poll.objects.create(
            thread=self.thread,
            category=self.category,
            poster_name='test',
            poster_slug='test',
            poster_ip='127.0.0.1',
            choices=[],
        )

        self.thread.synchronize()
        self.assertTrue(self.thread.has_poll)

    def test_set_first_post(self):
        """set_first_post sets first post and poster data on thread"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.set_first_post(post)
        self.assertEqual(self.thread.first_post, post)
        self.assertEqual(self.thread.started_on, post.posted_on)
        self.assertEqual(self.thread.starter, user)
        self.assertEqual(self.thread.starter_name, user.username)
        self.assertEqual(self.thread.starter_slug, user.slug)

    def test_set_last_post(self):
        """set_last_post sets first post and poster data on thread"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.set_last_post(post)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)

    def test_move(self):
        """move(new_category) moves thread to other category"""
        # pick category instead of category (so we don't have to create one)
        root_category = Category.objects.root_category()
        Category(
            name='New Category',
            slug='new-category',
        ).insert_at(
            root_category,
            position='last-child',
            save=True,
        )
        new_category = Category.objects.get(slug='new-category')

        self.thread.move(new_category)
        self.assertEqual(self.thread.category, new_category)

        for post in self.thread.post_set.all():
            self.assertEqual(post.category_id, new_category.id)

    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=other_thread,
            poster_name='Admin',
            poster_ip='127.0.0.1',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")

    def test_delete_private_thread(self):
        """
        private thread gets deleted automatically
        when there are no participants left in it
        """
        user_a = UserModel.objects.create_user("Bob", "*****@*****.**", "Pass.123")
        user_b = UserModel.objects.create_user("Weebl", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.add_participants(self.thread, [user_a, user_b])
        self.assertEqual(self.thread.participants.count(), 2)

        user_a.delete()
        Thread.objects.get(id=self.thread.id)

        user_b.delete()
        with self.assertRaises(Thread.DoesNotExist):
            Thread.objects.get(id=self.thread.id)
예제 #31
0
class ThreadModelTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(
            forum=self.forum,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_synchronize(self):
        """synchronize method updates thread data to reflect its contents"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        self.assertEqual(self.thread.replies, 0)

        datetime = timezone.now() + timedelta(5)
        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        # first sync call, updates last thread
        self.thread.synchronize()

        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertFalse(self.thread.has_events)
        self.assertEqual(self.thread.replies, 1)

        # add moderated post
        moderated_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(5),
            updated_on=datetime + timedelta(5),
            is_moderated=True)

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertFalse(self.thread.has_events)
        self.assertEqual(self.thread.replies, 1)

        # add hidden post
        hidden_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime + timedelta(10),
            updated_on=datetime + timedelta(10),
            is_hidden=True)

        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_moderated_posts)
        self.assertTrue(self.thread.has_hidden_posts)
        self.assertFalse(self.thread.has_events)
        self.assertEqual(self.thread.replies, 2)

        # unhide post
        hidden_post.is_hidden = False
        hidden_post.save()

        # last post changed to unhidden one
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertTrue(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertFalse(self.thread.has_events)
        self.assertEqual(self.thread.replies, 2)

        # unmoderate post
        moderated_post.is_moderated = False
        moderated_post.save()

        # last post not changed, but flags and count did
        self.thread.synchronize()
        self.assertEqual(self.thread.last_post, hidden_post)
        self.assertEqual(self.thread.last_post_on, hidden_post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)
        self.assertFalse(self.thread.has_reported_posts)
        self.assertFalse(self.thread.has_moderated_posts)
        self.assertFalse(self.thread.has_hidden_posts)
        self.assertFalse(self.thread.has_events)
        self.assertEqual(self.thread.replies, 3)

        # add event
        event = Event.objects.create(
            forum=self.forum,
            thread=self.thread,
            author_name=user.username,
            author_slug=user.slug,
            message="How bout nope?")

        # sync set has_events flag
        self.thread.synchronize()
        self.assertTrue(self.thread.has_events)

        # sync unsetset has_events flag after only event was deleted
        event.delete()
        self.thread.synchronize()
        self.assertFalse(self.thread.has_events)

    def test_set_first_post(self):
        """set_first_post sets first post and poster data on thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.set_first_post(post)
        self.assertEqual(self.thread.first_post, post)
        self.assertEqual(self.thread.started_on, post.posted_on)
        self.assertEqual(self.thread.starter, user)
        self.assertEqual(self.thread.starter_name, user.username)
        self.assertEqual(self.thread.starter_slug, user.slug)

    def test_set_last_post(self):
        """set_last_post sets first post and poster data on thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now() + timedelta(5)

        post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=user,
            poster_name=user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        self.thread.set_last_post(post)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster, user)
        self.assertEqual(self.thread.last_poster_name, user.username)
        self.assertEqual(self.thread.last_poster_slug, user.slug)

    def test_move(self):
        """move(new_forum) moves thread to other forum"""
        # pick category instead of forum (so we don't have to create one)
        new_forum = Forum.objects.filter(role="category")[:1][0]

        self.thread.move(new_forum)
        self.assertEqual(self.thread.forum, new_forum)

        for post in self.thread.post_set.all():
            self.assertEqual(post.forum_id, new_forum.id)

    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            forum=self.forum,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            forum=self.forum,
            thread=other_thread,
            poster_name='Admin',
            poster_ip='127.0.0.1',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")

    def test_delete_private_thread(self):
        """
        private thread gets deleted automatically
        when there are no participants left in it
        """
        User = get_user_model()
        user_a = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")
        user_b = User.objects.create_user(
            "Weebl", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.add_participant(self.thread, user_a)
        ThreadParticipant.objects.add_participant(self.thread, user_b)
        self.assertEqual(self.thread.participants.count(), 2)

        user_a.delete()
        Thread.objects.get(id=self.thread.id)

        user_b.delete()
        with self.assertRaises(Thread.DoesNotExist):
            Thread.objects.get(id=self.thread.id)
예제 #32
0
    def handle(self, *args, **options):
        try:
            fake_threads_to_create = int(args[0])
        except IndexError:
            fake_threads_to_create = 5
        except ValueError:
            self.stderr.write("\nOptional argument should be integer.")
            sys.exit(1)

        forums = [f for f in Forum.objects.all_forums().filter(role='forum')]

        fake = Factory.create()

        User = get_user_model()
        total_users = User.objects.count()

        self.stdout.write('Creating fake threads...\n')

        message = '\nSuccessfully created %s fake threads'

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, fake_threads_to_create)
        for i in xrange(fake_threads_to_create):
            with atomic():
                datetime = timezone.now()
                forum = random.choice(forums)
                user = User.objects.order_by('?')[:1][0]

                thread_is_moderated = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(
                    forum=forum,
                    started_on=datetime,
                    starter_name='-',
                    starter_slug='-',
                    last_post_on=datetime,
                    last_poster_name='-',
                    last_poster_slug='-',
                    replies=random.randint(0, 2000),
                    is_moderated=thread_is_moderated,
                    is_hidden=thread_is_hidden,
                    is_closed=thread_is_closed)
                thread.set_title(fake.sentence())
                thread.save()

                fake_message = "\n\n".join(fake.paragraphs())
                post = Post.objects.create(
                    forum=forum,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    poster_ip=fake.ipv4(),
                    original=fake_message,
                    parsed=linebreaks_filter(fake_message),
                    posted_on=datetime,
                    updated_on=datetime)
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                forum.threads += 1
                forum.posts += 1
                forum.set_last_thread(thread)
                forum.save()

                user.threads += 1
                user.posts += 1
                user.save()

                created_threads += 1
                show_progress(
                    self, created_threads, fake_threads_to_create, start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        for i in xrange(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            thread.is_pinned = True
            thread.save()

        self.stdout.write(message % created_threads)
예제 #33
0
def merge_threads(request, validated_data, threads, poll):
    new_thread = Thread(
        category=validated_data['category'],
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(
            request,
            new_thread,
            'merged',
            {
                'merged_thread': thread.title,
            },
            commit=False,
        )

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    add_acl(request.user, new_thread)
    return new_thread
예제 #34
0
class ParticipantsTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(forum=self.forum,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(forum=self.forum,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_thread_has_participants(self):
        """thread_has_participants returns true if thread has participants"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")
        other_user = User.objects.create_user("Bob2", "*****@*****.**",
                                              "Pass.123")

        self.assertFalse(thread_has_participants(self.thread))

        ThreadParticipant.objects.add_participant(self.thread, user)
        self.assertTrue(thread_has_participants(self.thread))

        ThreadParticipant.objects.add_participant(self.thread, other_user)
        self.assertTrue(thread_has_participants(self.thread))

        self.thread.threadparticipant_set.all().delete()
        self.assertFalse(thread_has_participants(self.thread))

    def test_make_thread_participants_aware(self):
        """
        make_thread_participants_aware sets participants_list and participant
        adnotations on thread model
        """
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")
        other_user = User.objects.create_user("Bob2", "*****@*****.**",
                                              "Pass.123")

        self.assertFalse(hasattr(self.thread, 'participants_list'))
        self.assertFalse(hasattr(self.thread, 'participant'))

        make_thread_participants_aware(user, self.thread)

        self.assertTrue(hasattr(self.thread, 'participants_list'))
        self.assertTrue(hasattr(self.thread, 'participant'))

        self.assertEqual(self.thread.participants_list, [])
        self.assertIsNone(self.thread.participant)

        ThreadParticipant.objects.add_participant(self.thread, user, True)
        ThreadParticipant.objects.add_participant(self.thread, other_user)

        make_thread_participants_aware(user, self.thread)

        self.assertEqual(self.thread.participant.user, user)
        for participant in self.thread.participants_list:
            if participant.user == user:
                break
        else:
            self.fail("thread.participants_list didn't contain user")

    def test_set_thread_owner(self):
        """set_thread_owner sets user as thread owner"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        set_thread_owner(self.thread, user)

        owner = self.thread.threadparticipant_set.get(is_owner=True)
        self.assertEqual(user, owner.user)

    def test_set_user_unread_private_threads_sync(self):
        """
        set_user_unread_private_threads_sync sets sync_unread_private_threads
        flag on user model to true
        """
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        self.assertFalse(user.sync_unread_private_threads)

        set_user_unread_private_threads_sync(user)
        self.assertTrue(user.sync_unread_private_threads)

        db_user = User.objects.get(pk=user.pk)
        self.assertTrue(db_user.sync_unread_private_threads)

    def test_add_owner(self):
        """add_owner adds user as thread owner"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        add_owner(self.thread, user)
        self.assertTrue(user.sync_unread_private_threads)

        owner = self.thread.threadparticipant_set.get(is_owner=True)
        self.assertEqual(user, owner.user)

    def test_remove_participant(self):
        """remove_participant removes user from thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        add_owner(self.thread, user)
        remove_participant(self.thread, user)

        with self.assertRaises(ThreadParticipant.DoesNotExist):
            self.thread.threadparticipant_set.get(user=user)

        set_user_unread_private_threads_sync(user)
        self.assertTrue(user.sync_unread_private_threads)

        db_user = User.objects.get(pk=user.pk)
        self.assertTrue(db_user.sync_unread_private_threads)
예제 #35
0
class ThreadParticipantTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(category=self.category,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_delete_participant(self):
        """delete_participant deletes participant from thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")
        other_user = User.objects.create_user("Bob2", "*****@*****.**",
                                              "Pass.123")

        ThreadParticipant.objects.add_participant(self.thread, user)
        ThreadParticipant.objects.add_participant(self.thread, other_user)
        self.assertEqual(self.thread.participants.count(), 2)

        ThreadParticipant.objects.remove_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        with self.assertRaises(ThreadParticipant.DoesNotExist):
            participation = ThreadParticipant.objects.get(thread=self.thread,
                                                          user=user)

    def test_add_participant(self):
        """add_participant adds participant to thread"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.add_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        participation = ThreadParticipant.objects.get(thread=self.thread,
                                                      user=user)
        self.assertFalse(participation.is_owner)

        ThreadParticipant.objects.add_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 2)

    def test_set_owner(self):
        """set_owner makes user thread owner"""
        User = get_user_model()
        user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        ThreadParticipant.objects.set_owner(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        participation = ThreadParticipant.objects.get(thread=self.thread,
                                                      user=user)
        self.assertTrue(participation.is_owner)
        self.assertEqual(user, participation.user)

        other_user = User.objects.create_user("Bob2", "*****@*****.**",
                                              "Pass.123")
        ThreadParticipant.objects.set_owner(self.thread, other_user)
        self.assertEqual(self.thread.participants.count(), 2)

        participation = ThreadParticipant.objects.get(thread=self.thread,
                                                      user=user)
        self.assertFalse(participation.is_owner)
예제 #36
0
class PostModelTests(TestCase):
    def setUp(self):
        self.user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                                  "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        self.post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        update_post_checksum(self.post)
        self.post.save(update_fields=['checksum'])

        self.thread.first_post = self.post
        self.thread.last_post = self.post
        self.thread.save()

    def test_merge_invalid(self):
        """see if attempts for invalid merges fail"""
        # can't merge with itself
        with self.assertRaises(ValueError):
            self.post.merge(self.post)

        other_user = UserModel.objects.create_user("Jeff", "*****@*****.**",
                                                   "Pass.123")

        other_thread = Thread.objects.create(
            category=self.category,
            started_on=timezone.now(),
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=timezone.now(),
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        # can't merge with other users posts
        with self.assertRaises(ValueError):
            self.post.merge(
                Post.objects.create(
                    category=self.category,
                    thread=self.thread,
                    poster=other_user,
                    poster_name=other_user.username,
                    original="Hello! I am test message!",
                    parsed="<p>Hello! I am test message!</p>",
                    checksum="nope",
                    posted_on=timezone.now() + timedelta(minutes=5),
                    updated_on=timezone.now() + timedelta(minutes=5),
                ))

        # can't merge across threads
        with self.assertRaises(ValueError):
            self.post.merge(
                Post.objects.create(
                    category=self.category,
                    thread=other_thread,
                    poster=self.user,
                    poster_name=self.user.username,
                    original="Hello! I am test message!",
                    parsed="<p>Hello! I am test message!</p>",
                    checksum="nope",
                    posted_on=timezone.now() + timedelta(minutes=5),
                    updated_on=timezone.now() + timedelta(minutes=5),
                ))

        # can't merge with events
        with self.assertRaises(ValueError):
            self.post.merge(
                Post.objects.create(
                    category=self.category,
                    thread=self.thread,
                    poster=self.user,
                    poster_name=self.user.username,
                    original="Hello! I am test message!",
                    parsed="<p>Hello! I am test message!</p>",
                    checksum="nope",
                    posted_on=timezone.now() + timedelta(minutes=5),
                    updated_on=timezone.now() + timedelta(minutes=5),
                    is_event=True,
                ))

    def test_merge(self):
        """merge method merges two posts into one"""
        other_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            original="I am other message!",
            parsed="<p>I am other message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5),
        )

        other_post.merge(self.post)

        self.assertIn(other_post.original, self.post.original)
        self.assertIn(other_post.parsed, self.post.parsed)
        self.assertTrue(self.post.is_valid)

    def test_merge_best_answer(self):
        """merge method merges best answer into post"""
        best_answer = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            original="I am other message!",
            parsed="<p>I am other message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5),
        )

        self.thread.set_best_answer(self.user, best_answer)
        self.thread.save()

        best_answer.merge(self.post)
        self.assertEqual(self.thread.best_answer, self.post)

    def test_merge_in_best_answer(self):
        """merge method merges post into best answert"""
        best_answer = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            original="I am other message!",
            parsed="<p>I am other message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5),
        )

        other_post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            original="I am other message!",
            parsed="<p>I am other message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5),
        )

        self.thread.set_best_answer(self.user, best_answer)
        self.thread.save()

        other_post.merge(best_answer)
        self.assertEqual(self.thread.best_answer, best_answer)

    def test_move(self):
        """move method moves post to other thread"""
        new_thread = Thread.objects.create(
            category=self.category,
            started_on=timezone.now(),
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=timezone.now(),
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.post.move(new_thread)

        self.assertEqual(self.post.thread, new_thread)
예제 #37
0
    def handle(self, *args, **options):
        items_to_create = options['threads']

        categories = list(Category.objects.all_categories())

        fake = Factory.create()

        User = get_user_model()
        total_users = User.objects.count()

        self.stdout.write('Creating fake threads...\n')

        message = '\nSuccessfully created %s fake threads in %s'

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, items_to_create)

        while created_threads < items_to_create:
            with atomic():
                datetime = timezone.now()
                category = random.choice(categories)
                user = User.objects.order_by('?')[:1][0]

                thread_is_unapproved = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(
                    category=category,
                    started_on=datetime,
                    starter_name='-',
                    starter_slug='-',
                    last_post_on=datetime,
                    last_poster_name='-',
                    last_poster_slug='-',
                    replies=0,
                    is_unapproved=thread_is_unapproved,
                    is_hidden=thread_is_hidden,
                    is_closed=thread_is_closed
                )
                thread.set_title(fake.sentence())
                thread.save()

                fake_message = "\n\n".join(fake.paragraphs())
                post = Post.objects.create(
                    category=category,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    poster_ip=fake.ipv4(),
                    original=fake_message,
                    parsed=linebreaks_filter(fake_message),
                    posted_on=datetime,
                    updated_on=datetime
                )
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                user.threads += 1
                user.posts += 1
                user.save()

                thread_type = random.randint(0, 100)
                if thread_type > 95:
                    thread_replies = random.randint(200, 2500)
                elif thread_type > 50:
                    thread_replies = random.randint(5, 30)
                else:
                    thread_replies = random.randint(0, 10)

                for x in range(thread_replies):
                    datetime = timezone.now()
                    user = User.objects.order_by('?')[:1][0]
                    fake_message = "\n\n".join(fake.paragraphs())

                    is_unapproved = random.randint(0, 100) > 97

                    post = Post.objects.create(
                        category=category,
                        thread=thread,
                        poster=user,
                        poster_name=user.username,
                        poster_ip=fake.ipv4(),
                        original=fake_message,
                        parsed=linebreaks_filter(fake_message),
                        is_unapproved=is_unapproved,
                        posted_on=datetime,
                        updated_on=datetime
                    )

                    if not is_unapproved:
                        is_hidden = random.randint(0, 100) > 97
                    else:
                        is_hidden = False

                    if is_hidden:
                        post.is_hidden = True

                        if random.randint(0, 100) < 80:
                            user = User.objects.order_by('?')[:1][0]
                            post.hidden_by = user
                            post.hidden_by_name = user.username
                            post.hidden_by_slug = user.username
                        else:
                            post.hidden_by_name = fake.first_name()
                            post.hidden_by_slug = post.hidden_by_name.lower()

                    update_post_checksum(post)
                    post.save()

                    user.posts += 1
                    user.save()

                thread.synchronize()
                thread.save()

                created_threads += 1
                show_progress(
                    self, created_threads, items_to_create, start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        for i in range(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            if random.randint(0, 100) > 75:
                thread.weight = 2
            else:
                thread.weight = 1
            thread.save()

        for category in categories:
            category.synchronize()
            category.save()

        total_time = time.time() - start_time
        total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
        self.stdout.write(message % (created_threads, total_humanized))
예제 #38
0
class ParticipantsTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name='Tester',
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime
        )

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_thread_has_participants(self):
        """thread_has_participants returns true if thread has participants"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")
        other_user = User.objects.create_user(
            "Bob2", "*****@*****.**", "Pass.123")

        self.assertFalse(thread_has_participants(self.thread))

        ThreadParticipant.objects.add_participant(self.thread, user)
        self.assertTrue(thread_has_participants(self.thread))

        ThreadParticipant.objects.add_participant(self.thread, other_user)
        self.assertTrue(thread_has_participants(self.thread))

        self.thread.threadparticipant_set.all().delete()
        self.assertFalse(thread_has_participants(self.thread))

    def test_make_thread_participants_aware(self):
        """
        make_thread_participants_aware sets participants_list and participant
        adnotations on thread model
        """
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")
        other_user = User.objects.create_user(
            "Bob2", "*****@*****.**", "Pass.123")

        self.assertFalse(hasattr(self.thread, 'participants_list'))
        self.assertFalse(hasattr(self.thread, 'participant'))

        make_thread_participants_aware(user, self.thread)

        self.assertTrue(hasattr(self.thread, 'participants_list'))
        self.assertTrue(hasattr(self.thread, 'participant'))

        self.assertEqual(self.thread.participants_list, [])
        self.assertIsNone(self.thread.participant)

        ThreadParticipant.objects.add_participant(self.thread, user, True)
        ThreadParticipant.objects.add_participant(self.thread, other_user)

        make_thread_participants_aware(user, self.thread)

        self.assertEqual(self.thread.participant.user, user)
        for participant in self.thread.participants_list:
            if participant.user == user:
                break
        else:
            self.fail("thread.participants_list didn't contain user")

    def test_set_thread_owner(self):
        """set_thread_owner sets user as thread owner"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")

        set_thread_owner(self.thread, user)

        owner = self.thread.threadparticipant_set.get(is_owner=True)
        self.assertEqual(user, owner.user)

    def test_set_user_unread_private_threads_sync(self):
        """
        set_user_unread_private_threads_sync sets sync_unread_private_threads
        flag on user model to true
        """
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")

        self.assertFalse(user.sync_unread_private_threads)

        set_user_unread_private_threads_sync(user)
        self.assertTrue(user.sync_unread_private_threads)

        db_user = User.objects.get(pk=user.pk)
        self.assertTrue(db_user.sync_unread_private_threads)

    def test_add_owner(self):
        """add_owner adds user as thread owner"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")

        add_owner(self.thread, user)
        self.assertTrue(user.sync_unread_private_threads)

        owner = self.thread.threadparticipant_set.get(is_owner=True)
        self.assertEqual(user, owner.user)

    def test_remove_participant(self):
        """remove_participant removes user from thread"""
        User = get_user_model()
        user = User.objects.create_user(
            "Bob", "*****@*****.**", "Pass.123")

        add_owner(self.thread, user)
        remove_participant(self.thread, user)

        with self.assertRaises(ThreadParticipant.DoesNotExist):
            self.thread.threadparticipant_set.get(user=user)

        set_user_unread_private_threads_sync(user)
        self.assertTrue(user.sync_unread_private_threads)

        db_user = User.objects.get(pk=user.pk)
        self.assertTrue(db_user.sync_unread_private_threads)
예제 #39
0
def merge_threads(request, validated_data, threads, poll):
    new_thread = Thread(category=validated_data['category'],
                        started_on=threads[0].started_on,
                        last_post_on=threads[0].last_post_on)

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(request,
                     new_thread,
                     'merged', {
                         'merged_thread': thread.title,
                     },
                     commit=False)

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    # add top category to thread
    if validated_data.get('top_category'):
        categories = list(Category.objects.all_categories().filter(
            id__in=request.user.acl['visible_categories']))
        add_categories_to_items(validated_data['top_category'], categories,
                                [new_thread])
    else:
        new_thread.top_category = None

    add_acl(request.user, new_thread)
    return new_thread
예제 #40
0
    def handle(self, *args, **options):
        items_to_create = options['threads']

        categories = list(Category.objects.all_categories())

        fake = Factory.create()

        User = get_user_model()
        total_users = User.objects.count()

        self.stdout.write('Creating fake threads...\n')

        message = '\nSuccessfully created %s fake threads in %s'

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, items_to_create)

        while created_threads < items_to_create:
            with atomic():
                datetime = timezone.now()
                category = random.choice(categories)
                user = User.objects.order_by('?')[:1][0]

                thread_is_unapproved = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(
                    category=category,
                    started_on=datetime,
                    starter_name='-',
                    starter_slug='-',
                    last_post_on=datetime,
                    last_poster_name='-',
                    last_poster_slug='-',
                    replies=0,
                    is_unapproved=thread_is_unapproved,
                    is_hidden=thread_is_hidden,
                    is_closed=thread_is_closed
                )
                thread.set_title(fake.sentence())
                thread.save()

                fake_message = "\n\n".join(fake.paragraphs())
                post = Post.objects.create(
                    category=category,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    poster_ip=fake.ipv4(),
                    original=fake_message,
                    parsed=linebreaks_filter(fake_message),
                    posted_on=datetime,
                    updated_on=datetime
                )
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                user.threads += 1
                user.posts += 1
                user.save()

                thread_type = random.randint(0, 100)
                if thread_type > 95:
                    thread_replies = random.randint(200, 2500)
                elif thread_type > 50:
                    thread_replies = random.randint(5, 30)
                else:
                    thread_replies = random.randint(0, 10)

                for x in range(thread_replies):
                    datetime = timezone.now()
                    user = User.objects.order_by('?')[:1][0]
                    fake_message = "\n\n".join(fake.paragraphs())

                    is_unapproved = random.randint(0, 100) > 97
                    if not is_unapproved:
                        is_hidden = random.randint(0, 100) > 97
                    else:
                        is_hidden = False

                    post = Post.objects.create(
                        category=category,
                        thread=thread,
                        poster=user,
                        poster_name=user.username,
                        poster_ip=fake.ipv4(),
                        original=fake_message,
                        parsed=linebreaks_filter(fake_message),
                        is_hidden=is_hidden,
                        is_unapproved=is_unapproved,
                        posted_on=datetime,
                        updated_on=datetime
                    )
                    update_post_checksum(post)
                    post.save(update_fields=['checksum'])

                    user.posts += 1
                    user.save()

                thread.synchronize()
                thread.save()

                created_threads += 1
                show_progress(
                    self, created_threads, items_to_create, start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        for i in range(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            if random.randint(0, 100) > 75:
                thread.weight = 2
            else:
                thread.weight = 1
            thread.save()

        for category in categories:
            category.synchronize()
            category.save()

        total_time = time.time() - start_time
        total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
        self.stdout.write(message % (created_threads, total_humanized))
예제 #41
0
def threads_merge_endpoint(request):
    serializer = MergeThreadsSerializer(
        data=request.data,
        context={'user': request.user},
    )

    serializer.is_valid(raise_exception=True)

    threads = serializer.validated_data['threads']

    data = serializer.validated_data
    threads = data['threads']

    new_thread = Thread(
        category=data['category'],
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(data['title'])
    new_thread.save()

    # handle merge conflict
    best_answer = data.get('best_answer')
    if best_answer:
        new_thread.best_answer_id = best_answer.best_answer_id
        new_thread.best_answer_is_protected = best_answer.best_answer_is_protected
        new_thread.best_answer_marked_on = best_answer.best_answer_marked_on
        new_thread.best_answer_marked_by_id = best_answer.best_answer_marked_by_id
        new_thread.best_answer_marked_by_name = best_answer.best_answer_marked_by_name
        new_thread.best_answer_marked_by_slug = best_answer.best_answer_marked_by_slug

    poll = data.get('poll')
    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(
            request,
            new_thread,
            'merged',
            {'merged_thread': thread.title},
            commit=False,
        )

    new_thread.synchronize()
    new_thread.save()

    if data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    add_acl(request.user, new_thread)

    return Response(ThreadsListSerializer(new_thread).data)
예제 #42
0
파일: merge.py 프로젝트: mayblue9/Misago
def merge_threads(user, validated_data, threads):
    new_thread = Thread(
        category=validated_data['category'],
        weight=validated_data.get('weight', 0),
        is_closed=validated_data.get('is_closed', False),
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

    new_thread.synchronize()
    new_thread.save()

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    # add top category to thread
    if validated_data.get('top_category'):
        categories = list(Category.objects.all_categories().filter(
            id__in=user.acl['visible_categories']
        ))
        add_categories_to_threads(
            validated_data['top_category'], categories, [new_thread])
    else:
        new_thread.top_category = None

    new_thread.save()

    add_acl(user, new_thread)
    return new_thread
예제 #43
0
    def action_split(self, request, posts):
        if posts[0].id == self.thread.first_post_id:
            message = _("You can't split thread's first post.")
            raise moderation.ModerationError(message)

        form = SplitThreadForm(acl=request.user.acl)

        if 'submit' in request.POST or 'follow' in request.POST:
            form = SplitThreadForm(request.POST, acl=request.user.acl)
            if form.is_valid():
                split_thread = Thread()
                split_thread.forum = form.cleaned_data['forum']
                split_thread.set_title(
                    form.cleaned_data['thread_title'])
                split_thread.starter_name = "-"
                split_thread.starter_slug = "-"
                split_thread.last_poster_name = "-"
                split_thread.last_poster_slug = "-"
                split_thread.started_on = timezone.now()
                split_thread.last_post_on = timezone.now()
                split_thread.save()

                for post in posts:
                    post.move(split_thread)
                    post.save()

                split_thread.synchronize()
                split_thread.save()

                if split_thread.forum != self.forum:
                    split_thread.forum.lock()
                    split_thread.forum.synchronize()
                    split_thread.forum.save()

                changed_posts = len(posts)
                message = ungettext(
                    '%(changed)d post was split to "%(thread)s".',
                    '%(changed)d posts were split to "%(thread)s".',
                changed_posts)
                messages.success(request, message % {
                    'changed': changed_posts,
                    'thread': split_thread.title
                })

                if 'follow' in request.POST:
                    return redirect(split_thread.get_absolute_url())
                else:
                    return None # trigger thread refresh

        if request.is_ajax():
            template = self.split_thread_modal_template
        else:
            template = self.split_thread_full_template

        return render(request, template, {
            'form': form,
            'forum': self.forum,
            'thread': self.thread,
            'path': get_forum_path(self.forum),

            'posts': posts
        })
예제 #44
0
파일: thread.py 프로젝트: tylercole/Misago
 def post_action_split(self, ids):
     for id in ids:
         if id == self.thread.start_post_id:
             raise forms.ValidationError(_("You cannot split first post from thread."))
     message = None
     if self.request.POST.get('do') == 'split':
         form = SplitThreadForm(self.request.POST, request=self.request)
         if form.is_valid():
             new_thread = Thread()
             new_thread.forum = form.cleaned_data['thread_forum']
             new_thread.name = form.cleaned_data['thread_name']
             new_thread.slug = slugify(form.cleaned_data['thread_name'])
             new_thread.start = timezone.now()
             new_thread.last = timezone.now()
             new_thread.start_poster_name = 'n'
             new_thread.start_poster_slug = 'n'
             new_thread.last_poster_name = 'n'
             new_thread.last_poster_slug = 'n'
             new_thread.save(force_insert=True)
             prev_merge = -1
             merge = -1
             for post in self.posts:
                 if post.pk in ids:
                     if prev_merge != post.merge:
                         prev_merge = post.merge
                         merge += 1
                     post.merge = merge
                     post.move_to(new_thread)
                     post.save(force_update=True)
             new_thread.sync()
             new_thread.save(force_update=True)
             self.thread.sync()
             self.thread.save(force_update=True)
             self.forum.sync()
             self.forum.save(force_update=True)
             if new_thread.forum != self.forum:
                 new_thread.forum.sync()
                 new_thread.forum.save(force_update=True)
             self.request.messages.set_flash(Message(_("Selected posts have been split to new thread.")), 'success', 'threads')
             return redirect(reverse('thread', kwargs={'thread': new_thread.pk, 'slug': new_thread.slug}))
         message = Message(form.non_field_errors()[0], 'error')
     else:
         form = SplitThreadForm(request=self.request, initial={
                                                               'thread_name': _('[Split] %s') % self.thread.name,
                                                               'thread_forum': self.forum,
                                                               })
     return self.request.theme.render_to_response('threads/split.html',
                                                  {
                                                   'message': message,
                                                   'forum': self.forum,
                                                   'parents': self.parents,
                                                   'thread': self.thread,
                                                   'posts': ids,
                                                   'form': FormLayout(form),
                                                   },
                                                  context_instance=RequestContext(self.request));
예제 #45
0
파일: merge.py 프로젝트: josue804/Misago
def merge_threads(request, validated_data, threads, poll):
    new_thread = Thread(
        category=validated_data['category'],
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(
            request,
            new_thread,
            'merged',
            {
                'merged_thread': thread.title,
            },
            commit=False,
        )

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    add_acl(request.user, new_thread)
    return new_thread
예제 #46
0
class ThreadParticipantTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster_name='Tester',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_set_owner(self):
        """set_owner makes user thread owner"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")
        other_user = UserModel.objects.create_user("Bob2", "*****@*****.**",
                                                   "Pass.123")

        ThreadParticipant.objects.set_owner(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        participant = ThreadParticipant.objects.get(thread=self.thread,
                                                    user=user)
        self.assertTrue(participant.is_owner)
        self.assertEqual(user, participant.user)

        # threads can't have more than one owner
        ThreadParticipant.objects.set_owner(self.thread, other_user)
        self.assertEqual(self.thread.participants.count(), 2)

        participant = ThreadParticipant.objects.get(thread=self.thread,
                                                    user=user)
        self.assertFalse(participant.is_owner)

        self.assertEqual(
            ThreadParticipant.objects.filter(is_owner=True).count(), 1)

    def test_add_participants(self):
        """add_participant adds participant to thread"""
        users = [
            UserModel.objects.create_user("Bob", "*****@*****.**",
                                          "Pass.123"),
            UserModel.objects.create_user("Bob2", "*****@*****.**",
                                          "Pass.123"),
        ]

        ThreadParticipant.objects.add_participants(self.thread, users)
        self.assertEqual(self.thread.participants.count(), 2)

        for user in users:
            participant = ThreadParticipant.objects.get(thread=self.thread,
                                                        user=user)
            self.assertFalse(participant.is_owner)

    def test_remove_participant(self):
        """remove_participant deletes participant from thread"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")
        other_user = UserModel.objects.create_user("Bob2", "*****@*****.**",
                                                   "Pass.123")

        ThreadParticipant.objects.add_participants(self.thread, [user])
        ThreadParticipant.objects.add_participants(self.thread, [other_user])
        self.assertEqual(self.thread.participants.count(), 2)

        ThreadParticipant.objects.remove_participant(self.thread, user)
        self.assertEqual(self.thread.participants.count(), 1)

        with self.assertRaises(ThreadParticipant.DoesNotExist):
            ThreadParticipant.objects.get(thread=self.thread, user=user)
예제 #47
0
class PostModelTests(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(
            forum=self.forum,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        self.post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime)

        update_post_checksum(self.post)
        self.post.save(update_fields=['checksum'])

        self.thread.first_post = self.post
        self.thread.last_post = self.post
        self.thread.save()

    def test_merge_invalid(self):
        """see if attempts for invalid merges fail"""
        with self.assertRaises(ValueError):
            self.post.merge(self.post)

        User = get_user_model()
        other_user = User.objects.create_user("Jeff", "*****@*****.**", "Pass.123")

        other_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=other_user,
            poster_name=other_user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5))

        with self.assertRaises(ValueError):
            self.post.merge(other_post)

        other_thread = Thread.objects.create(
            forum=self.forum,
            started_on=timezone.now(),
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=timezone.now(),
            last_poster_name='Tester',
            last_poster_slug='tester')

        other_post = Post.objects.create(
            forum=self.forum,
            thread=other_thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5))

        with self.assertRaises(ValueError):
            self.post.merge(other_post)

        other_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster_name=other_user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5))

        with self.assertRaises(ValueError):
            self.post.merge(other_post)
        with self.assertRaises(ValueError):
            other_post.merge(self.post)

    def test_merge(self):
        """merge method merges two posts into one"""
        other_post = Post.objects.create(
            forum=self.forum,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="I am other message!",
            parsed="<p>I am other message!</p>",
            checksum="nope",
            posted_on=timezone.now() + timedelta(minutes=5),
            updated_on=timezone.now() + timedelta(minutes=5))

        other_post.merge(self.post)

        self.assertIn(other_post.original, self.post.original)
        self.assertIn(other_post.parsed, self.post.parsed)
        self.assertTrue(self.post.is_valid)

    def test_move(self):
        """move method moves post to other thread"""
        new_thread = Thread.objects.create(
            forum=self.forum,
            started_on=timezone.now(),
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=timezone.now(),
            last_poster_name='Tester',
            last_poster_slug='tester')

        self.post.move(new_thread)

        self.assertEqual(self.post.thread, new_thread)
예제 #48
0
class ParticipantsTests(TestCase):
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(category=self.category,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()

    def test_has_participants(self):
        """has_participants returns true if thread has participants"""
        users = [
            UserModel.objects.create_user("Bob", "*****@*****.**",
                                          "Pass.123"),
            UserModel.objects.create_user("Bob2", "*****@*****.**",
                                          "Pass.123"),
        ]

        self.assertFalse(has_participants(self.thread))

        ThreadParticipant.objects.add_participants(self.thread, users)
        self.assertTrue(has_participants(self.thread))

        self.thread.threadparticipant_set.all().delete()
        self.assertFalse(has_participants(self.thread))

    def test_make_threads_participants_aware(self):
        """
        make_participants_aware sets participants_list and participant
        annotations on list of threads
        """
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")
        other_user = UserModel.objects.create_user("Bob2", "*****@*****.**",
                                                   "Pass.123")

        self.assertFalse(hasattr(self.thread, 'participants_list'))
        self.assertFalse(hasattr(self.thread, 'participant'))

        make_participants_aware(user, [self.thread])

        self.assertFalse(hasattr(self.thread, 'participants_list'))
        self.assertTrue(hasattr(self.thread, 'participant'))
        self.assertIsNone(self.thread.participant)

        ThreadParticipant.objects.set_owner(self.thread, user)
        ThreadParticipant.objects.add_participants(self.thread, [other_user])

        make_participants_aware(user, [self.thread])

        self.assertFalse(hasattr(self.thread, 'participants_list'))
        self.assertEqual(self.thread.participant.user, user)

    def test_make_thread_participants_aware(self):
        """
        make_participants_aware sets participants_list and participant
        annotations on thread model
        """
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")
        other_user = UserModel.objects.create_user("Bob2", "*****@*****.**",
                                                   "Pass.123")

        self.assertFalse(hasattr(self.thread, 'participants_list'))
        self.assertFalse(hasattr(self.thread, 'participant'))

        make_participants_aware(user, self.thread)

        self.assertTrue(hasattr(self.thread, 'participants_list'))
        self.assertTrue(hasattr(self.thread, 'participant'))

        self.assertEqual(self.thread.participants_list, [])
        self.assertIsNone(self.thread.participant)

        ThreadParticipant.objects.set_owner(self.thread, user)
        ThreadParticipant.objects.add_participants(self.thread, [other_user])

        make_participants_aware(user, self.thread)

        self.assertEqual(self.thread.participant.user, user)
        for participant in self.thread.participants_list:
            if participant.user == user:
                break
        else:
            self.fail("thread.participants_list didn't contain user")

    def test_set_owner(self):
        """set_owner sets user as thread owner"""
        user = UserModel.objects.create_user("Bob", "*****@*****.**",
                                             "Pass.123")

        set_owner(self.thread, user)

        owner = self.thread.threadparticipant_set.get(is_owner=True)
        self.assertEqual(user, owner.user)

    def test_set_users_unread_private_threads_sync(self):
        """
        set_users_unread_private_threads_sync sets sync_unread_private_threads
        flag on users provided to true
        """
        users = [
            UserModel.objects.create_user("Bob1", "*****@*****.**",
                                          "Pass.123"),
            UserModel.objects.create_user("Bob2", "*****@*****.**",
                                          "Pass.123"),
        ]

        set_users_unread_private_threads_sync(users=users)
        for user in users:
            UserModel.objects.get(pk=user.pk, sync_unread_private_threads=True)

    def test_set_participants_unread_private_threads_sync(self):
        """
        set_users_unread_private_threads_sync sets sync_unread_private_threads
        flag on participants provided to true
        """
        users = [
            UserModel.objects.create_user("Bob1", "*****@*****.**",
                                          "Pass.123"),
            UserModel.objects.create_user("Bob2", "*****@*****.**",
                                          "Pass.123"),
        ]

        participants = [ThreadParticipant(user=u) for u in users]

        set_users_unread_private_threads_sync(participants=participants)
        for user in users:
            UserModel.objects.get(pk=user.pk, sync_unread_private_threads=True)

    def test_set_participants_users_unread_private_threads_sync(self):
        """
        set_users_unread_private_threads_sync sets sync_unread_private_threads
        flag on users and participants provided to true
        """
        users = [
            UserModel.objects.create_user("Bob1", "*****@*****.**",
                                          "Pass.123"),
        ]

        participants = [ThreadParticipant(user=u) for u in users]

        users.append(
            UserModel.objects.create_user("Bob2", "*****@*****.**",
                                          "Pass.123"))

        set_users_unread_private_threads_sync(users=users,
                                              participants=participants)
        for user in users:
            UserModel.objects.get(pk=user.pk, sync_unread_private_threads=True)

    def test_set_users_unread_private_threads_sync_exclude_user(self):
        """exclude_user kwarg works"""
        users = [
            UserModel.objects.create_user("Bob1", "*****@*****.**",
                                          "Pass.123"),
            UserModel.objects.create_user("Bob2", "*****@*****.**",
                                          "Pass.123")
        ]

        set_users_unread_private_threads_sync(users=users,
                                              exclude_user=users[0])

        self.assertFalse(
            UserModel.objects.get(pk=users[0].pk).sync_unread_private_threads)
        self.assertTrue(
            UserModel.objects.get(pk=users[1].pk).sync_unread_private_threads)

    def test_set_users_unread_private_threads_sync_noop(self):
        """excluding only user is noop"""
        user = UserModel.objects.create_user("Bob1", "*****@*****.**",
                                             "Pass.123")

        with self.assertNumQueries(0):
            set_users_unread_private_threads_sync(users=[user],
                                                  exclude_user=user)

        self.assertFalse(
            UserModel.objects.get(pk=user.pk).sync_unread_private_threads)
예제 #49
0
def merge_threads(user, validated_data, threads):
    new_thread = Thread(
        category=validated_data['category'],
        weight=validated_data.get('weight', 0),
        is_closed=validated_data.get('is_closed', False),
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

    new_thread.synchronize()
    new_thread.save()

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    # add top category to thread
    if validated_data.get('top_category'):
        categories = list(Category.objects.all_categories().filter(
            id__in=user.acl['visible_categories']))
        add_categories_to_threads(validated_data['top_category'], categories,
                                  [new_thread])
    else:
        new_thread.top_category = None

    new_thread.save()

    add_acl(user, new_thread)
    return new_thread
예제 #50
0
    def action_merge(self, request, threads):
        if len(threads) == 1:
            message = _("You have to select at least two threads to merge.")
            raise moderation.ModerationError(message)

        form = MergeThreadsForm()

        if request.method == "POST" and 'submit' in request.POST:
            form = MergeThreadsForm(request.POST)
            if form.is_valid():
                thread_title = form.cleaned_data['merged_thread_title']

                with atomic():
                    merged_thread = Thread()
                    merged_thread.forum = self.forum
                    merged_thread.set_title(
                        form.cleaned_data['merged_thread_title'])
                    merged_thread.starter_name = "-"
                    merged_thread.starter_slug = "-"
                    merged_thread.last_poster_name = "-"
                    merged_thread.last_poster_slug = "-"
                    merged_thread.started_on = timezone.now()
                    merged_thread.last_post_on = timezone.now()
                    merged_thread.is_pinned = max(t.is_pinned for t in threads)
                    merged_thread.is_closed = max(t.is_closed for t in threads)
                    merged_thread.save()

                    for thread in threads:
                        moderation.merge_thread(
                            request.user, merged_thread, thread)

                    merged_thread.synchronize()
                    merged_thread.save()

                with atomic():
                    self.forum.synchronize()
                    self.forum.save()

                changed_threads = len(threads)
                message = ungettext(
                    '%(changed)d thread was merged into "%(thread)s".',
                    '%(changed)d threads were merged into "%(thread)s".',
                changed_threads)
                messages.success(request, message % {
                    'changed': changed_threads,
                    'thread': merged_thread.title
                })

                return None # trigger threads list refresh

        if request.is_ajax():
            template = self.merge_threads_modal_template
        else:
            template = self.merge_threads_full_template

        return render(request, template, {
            'form': form,
            'forum': self.forum,
            'path': get_forum_path(self.forum),
            'threads': threads
        })
예제 #51
0
    def handle(self, *args, **options):
        items_to_create = options['threads']

        categories = list(Category.objects.all_categories())

        fake = Factory.create()

        message = 'Creating %s fake threads...\n'
        self.stdout.write(message % items_to_create)

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, items_to_create)

        while created_threads < items_to_create:
            with atomic():
                datetime = timezone.now()
                category = random.choice(categories)
                user = UserModel.objects.order_by('?')[:1][0]

                thread_is_unapproved = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(
                    category=category,
                    started_on=datetime,
                    starter_name='-',
                    starter_slug='-',
                    last_post_on=datetime,
                    last_poster_name='-',
                    last_poster_slug='-',
                    replies=0,
                    is_unapproved=thread_is_unapproved,
                    is_hidden=thread_is_hidden,
                    is_closed=thread_is_closed,
                )
                thread.set_title(corpus_short.random_choice())
                thread.save()

                original, parsed = self.fake_post_content()

                post = Post.objects.create(
                    category=category,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    original=original,
                    parsed=parsed,
                    posted_on=datetime,
                    updated_on=datetime,
                )
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                user.threads += 1
                user.posts += 1
                user.save()

                thread_type = random.randint(0, 100)
                if thread_type > 98:
                    thread_replies = random.randint(200, 2500)
                elif thread_type > 50:
                    thread_replies = random.randint(5, 30)
                else:
                    thread_replies = random.randint(0, 10)

                for _ in range(thread_replies):
                    datetime = timezone.now()
                    user = UserModel.objects.order_by('?')[:1][0]

                    original, parsed = self.fake_post_content()

                    is_unapproved = random.randint(0, 100) > 97

                    post = Post.objects.create(
                        category=category,
                        thread=thread,
                        poster=user,
                        poster_name=user.username,
                        original=original,
                        parsed=parsed,
                        is_unapproved=is_unapproved,
                        posted_on=datetime,
                        updated_on=datetime,
                    )

                    if not is_unapproved:
                        is_hidden = random.randint(0, 100) > 97
                    else:
                        is_hidden = False

                    if is_hidden:
                        post.is_hidden = True

                        if random.randint(0, 100) < 80:
                            user = UserModel.objects.order_by('?')[:1][0]
                            post.hidden_by = user
                            post.hidden_by_name = user.username
                            post.hidden_by_slug = user.username
                        else:
                            post.hidden_by_name = fake.first_name()
                            post.hidden_by_slug = post.hidden_by_name.lower()

                    update_post_checksum(post)
                    post.save()

                    user.posts += 1
                    user.save()

                thread.synchronize()
                thread.save()

                created_threads += 1
                show_progress(self, created_threads, items_to_create, start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        
        for _ in range(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            if random.randint(0, 100) > 75:
                thread.weight = 2
            else:
                thread.weight = 1
            thread.save()

        for category in categories:
            category.synchronize()
            category.save()

        total_time = time.time() - start_time
        total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
        message = '\nSuccessfully created %s fake threads in %s'
        self.stdout.write(message % (created_threads, total_humanized))