tests.py 77.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
"""Tests for django comment client views."""
3
import json
4 5
import logging
from contextlib import contextmanager
6

7
import ddt
8
from django.contrib.auth.models import User
9
from django.core.management import call_command
10
from django.core.urlresolvers import reverse
11 12
from django.test.client import RequestFactory
from mock import ANY, Mock, patch
13
from nose.plugins.attrib import attr
14
from nose.tools import assert_equal, assert_true
15
from opaque_keys.edx.keys import CourseKey
16

17
from common.test.utils import MockSignalHandlerMixin, disable_signal
18 19
from course_modes.models import CourseMode
from course_modes.tests.factories import CourseModeFactory
20
from django_comment_client.base import views
21 22 23 24 25
from django_comment_client.tests.group_id import (
    CohortedTopicGroupIdTestMixin,
    GroupIdAssertionMixin,
    NonCohortedTopicGroupIdTestMixin
)
26
from django_comment_client.tests.unicode import UnicodeTestMixin
27
from django_comment_client.tests.utils import CohortedTestCase, ForumsEnableMixin
28 29
from django_comment_common.models import CourseDiscussionSettings, Role, assign_role
from django_comment_common.utils import ThreadContext, seed_permissions_roles, set_course_discussion_settings
30
from lms.djangoapps.teams.tests.factories import CourseTeamFactory, CourseTeamMembershipFactory
31
from lms.lib.comment_client import Thread
32 33
from openedx.core.djangoapps.course_groups.cohorts import set_course_cohorted
from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory
34
from student.tests.factories import CourseAccessRoleFactory, CourseEnrollmentFactory, UserFactory
35
from util.testing import UrlResetMixin
Ben McMorran committed
36
from xmodule.modulestore import ModuleStoreEnum
37 38 39
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
40

41 42
log = logging.getLogger(__name__)

43
CS_PREFIX = "http://localhost:4567/api/v1"
44

45
# pylint: disable=missing-docstring
muhammad-ammar committed
46

47 48

class MockRequestSetupMixin(object):
49 50
    def _create_response_mock(self, data):
        return Mock(text=json.dumps(data), json=Mock(return_value=data))
51

52
    def _set_mock_request_data(self, mock_request, data):
53
        mock_request.return_value = self._create_response_mock(data)
54 55


56
@attr(shard=2)
57
@patch('lms.lib.comment_client.utils.requests.request', autospec=True)
58
class CreateThreadGroupIdTestCase(
59
        MockRequestSetupMixin,
60
        CohortedTestCase,
61 62 63 64 65 66
        CohortedTopicGroupIdTestMixin,
        NonCohortedTopicGroupIdTestMixin
):
    cs_endpoint = "/threads"

    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True):
67
        self._set_mock_request_data(mock_request, {})
68 69 70 71 72 73 74 75 76 77
        mock_request.return_value.status_code = 200
        request_data = {"body": "body", "title": "title", "thread_type": "discussion"}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().post("dummy_url", request_data)
        request.user = user
        request.view_name = "create_thread"

        return views.create_thread(
            request,
78
            course_id=unicode(self.course.id),
79 80
            commentable_id=commentable_id
        )
81

82 83 84 85 86 87 88 89 90 91
    def test_group_info_in_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            None
        )
        self._assert_json_response_contains_group_info(response)


92
@attr(shard=2)
93
@patch('lms.lib.comment_client.utils.requests.request', autospec=True)
94 95 96
@disable_signal(views, 'thread_edited')
@disable_signal(views, 'thread_voted')
@disable_signal(views, 'thread_deleted')
97 98
class ThreadActionGroupIdTestCase(
        MockRequestSetupMixin,
99
        CohortedTestCase,
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        GroupIdAssertionMixin
):
    def call_view(
            self,
            view_name,
            mock_request,
            user=None,
            post_params=None,
            view_args=None
    ):
        self._set_mock_request_data(
            mock_request,
            {
                "user_id": str(self.student.id),
                "group_id": self.student_cohort.id,
                "closed": False,
116 117
                "type": "thread",
                "commentable_id": "non_team_dummy_id"
118 119 120 121 122 123 124 125 126
            }
        )
        mock_request.return_value.status_code = 200
        request = RequestFactory().post("dummy_url", post_params or {})
        request.user = user or self.student
        request.view_name = view_name

        return getattr(views, view_name)(
            request,
127
            course_id=unicode(self.course.id),
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            thread_id="dummy",
            **(view_args or {})
        )

    def test_update(self, mock_request):
        response = self.call_view(
            "update_thread",
            mock_request,
            post_params={"body": "body", "title": "title"}
        )
        self._assert_json_response_contains_group_info(response)

    def test_delete(self, mock_request):
        response = self.call_view("delete_thread", mock_request)
        self._assert_json_response_contains_group_info(response)

    def test_vote(self, mock_request):
        response = self.call_view(
            "vote_for_thread",
            mock_request,
            view_args={"value": "up"}
        )
        self._assert_json_response_contains_group_info(response)
        response = self.call_view("undo_vote_for_thread", mock_request)
        self._assert_json_response_contains_group_info(response)

    def test_flag(self, mock_request):
        response = self.call_view("flag_abuse_for_thread", mock_request)
        self._assert_json_response_contains_group_info(response)
        response = self.call_view("un_flag_abuse_for_thread", mock_request)
        self._assert_json_response_contains_group_info(response)

    def test_pin(self, mock_request):
        response = self.call_view(
            "pin_thread",
            mock_request,
            user=self.moderator
        )
        self._assert_json_response_contains_group_info(response)
        response = self.call_view(
            "un_pin_thread",
            mock_request,
            user=self.moderator
        )
        self._assert_json_response_contains_group_info(response)

    def test_openclose(self, mock_request):
        response = self.call_view(
            "openclose_thread",
            mock_request,
            user=self.moderator
        )
        self._assert_json_response_contains_group_info(
            response,
            lambda d: d['content']
        )


Ben McMorran committed
186
class ViewsTestCaseMixin(object):
187

Ben McMorran committed
188 189 190 191 192
    def set_up_course(self, module_count=0):
        """
        Creates a course, optionally with module_count discussion modules, and
        a user with appropriate permissions.
        """
193

194
        # create a course
polesye committed
195 196 197 198 199
        self.course = CourseFactory.create(
            org='MITx', course='999',
            discussion_topics={"Some Topic": {"id": "some_topic"}},
            display_name='Robot Super Course',
        )
200
        self.course_id = self.course.id
Ben McMorran committed
201 202 203 204 205 206 207 208 209 210 211

        # add some discussion modules
        for i in range(module_count):
            ItemFactory.create(
                parent_location=self.course.location,
                category='discussion',
                discussion_id='id_module_{}'.format(i),
                discussion_category='Category {}'.format(i),
                discussion_target='Discussion {}'.format(i)
            )

212
        # seed the forums permissions and roles
213
        call_command('seed_permissions_roles', unicode(self.course_id))
214

215 216 217 218 219
        # Patch the comment client user save method so it does not try
        # to create a new cc user when creating a django user
        with patch('student.models.cc.User.save'):
            uname = 'student'
            email = 'student@edx.org'
220
            self.password = 'test'  # pylint: disable=attribute-defined-outside-init
221 222

            # Create the user and make them active so we can log them in.
223
            self.student = User.objects.create_user(uname, email, self.password)  # pylint: disable=attribute-defined-outside-init
224 225 226
            self.student.is_active = True
            self.student.save()

227 228 229
            # Add a discussion moderator
            self.moderator = UserFactory.create(password=self.password)  # pylint: disable=attribute-defined-outside-init

230 231 232
            # Enroll the student in the course
            CourseEnrollmentFactory(user=self.student,
                                    course_id=self.course_id)
233

234 235 236 237 238
            # Enroll the moderator and give them the appropriate roles
            CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id)
            self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id))

            assert_true(self.client.login(username='student', password=self.password))
239

Ben McMorran committed
240 241 242 243 244 245 246 247 248
    def _setup_mock_request(self, mock_request, include_depth=False):
        """
        Ensure that mock_request returns the data necessary to make views
        function correctly
        """
        mock_request.return_value.status_code = 200
        data = {
            "user_id": str(self.student.id),
            "closed": False,
249
            "commentable_id": "non_team_dummy_id"
Ben McMorran committed
250 251 252 253 254
        }
        if include_depth:
            data["depth"] = 0
        self._set_mock_request_data(mock_request, data)

255
    def create_thread_helper(self, mock_request, extra_request_data=None, extra_response_data=None):
Ben McMorran committed
256 257 258
        """
        Issues a request to create a thread and verifies the result.
        """
259
        mock_request.return_value.status_code = 200
260
        self._set_mock_request_data(mock_request, {
261
            "thread_type": "discussion",
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": False,
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "robot",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0,
        })
290 291 292 293 294 295 296 297
        thread = {
            "thread_type": "discussion",
            "body": ["this is a post"],
            "anonymous_to_peers": ["false"],
            "auto_subscribe": ["false"],
            "anonymous": ["false"],
            "title": ["Hello"],
        }
298 299
        if extra_request_data:
            thread.update(extra_request_data)
300
        url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course',
301
                                               'course_id': unicode(self.course_id)})
302
        response = self.client.post(url, data=thread)
303
        assert_true(mock_request.called)
304 305 306
        expected_data = {
            'thread_type': 'discussion',
            'body': u'this is a post',
307
            'context': ThreadContext.COURSE,
308 309 310 311 312 313
            'anonymous_to_peers': False, 'user_id': 1,
            'title': u'Hello',
            'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course',
            'anonymous': False,
            'course_id': unicode(self.course_id),
        }
314 315
        if extra_response_data:
            expected_data.update(extra_response_data)
316 317
        mock_request.assert_called_with(
            'post',
318
            '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(prefix=CS_PREFIX),
319
            data=expected_data,
320
            params={'request_id': ANY},
321
            headers=ANY,
322 323
            timeout=5
        )
324
        assert_equal(response.status_code, 200)
325

Ben McMorran committed
326 327 328 329 330
    def update_thread_helper(self, mock_request):
        """
        Issues a request to update a thread and verifies the result.
        """
        self._setup_mock_request(mock_request)
331 332 333 334 335 336
        # Mock out saving in order to test that content is correctly
        # updated. Otherwise, the call to thread.save() receives the
        # same mocked request data that the original call to retrieve
        # the thread did, overwriting any changes.
        with patch.object(Thread, 'save'):
            response = self.client.post(
Peter Fogg committed
337 338
                reverse("update_thread", kwargs={
                    "thread_id": "dummy",
339
                    "course_id": unicode(self.course_id)
Peter Fogg committed
340
                }),
341 342
                data={"body": "foo", "title": "foo", "commentable_id": "some_topic"}
            )
Ben McMorran committed
343
        self.assertEqual(response.status_code, 200)
344 345 346 347
        data = json.loads(response.content)
        self.assertEqual(data['body'], 'foo')
        self.assertEqual(data['title'], 'foo')
        self.assertEqual(data['commentable_id'], 'some_topic')
Ben McMorran committed
348 349


350
@attr(shard=2)
Ben McMorran committed
351
@ddt.ddt
352
@patch('lms.lib.comment_client.utils.requests.request', autospec=True)
353 354
@disable_signal(views, 'thread_created')
@disable_signal(views, 'thread_edited')
355 356 357 358 359 360 361
class ViewsQueryCountTestCase(
        ForumsEnableMixin,
        UrlResetMixin,
        ModuleStoreTestCase,
        MockRequestSetupMixin,
        ViewsTestCaseMixin
):
Ben McMorran committed
362

363
    CREATE_USER = False
364
    ENABLED_CACHES = ['default', 'mongo_metadata_inheritance', 'loc_cache']
365
    ENABLED_SIGNALS = ['course_published']
366

Ben McMorran committed
367 368
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
369
        super(ViewsQueryCountTestCase, self).setUp()
Ben McMorran committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

    def count_queries(func):  # pylint: disable=no-self-argument
        """
        Decorates test methods to count mongo and SQL calls for a
        particular modulestore.
        """
        def inner(self, default_store, module_count, mongo_calls, sql_queries, *args, **kwargs):
            with modulestore().default_store(default_store):
                self.set_up_course(module_count=module_count)
                self.clear_caches()
                with self.assertNumQueries(sql_queries):
                    with check_mongo_calls(mongo_calls):
                        func(self, *args, **kwargs)
        return inner

    @ddt.data(
386
        (ModuleStoreEnum.Type.mongo, 3, 4, 31),
387
        (ModuleStoreEnum.Type.split, 3, 12, 31),
Ben McMorran committed
388 389 390 391 392 393 394
    )
    @ddt.unpack
    @count_queries
    def test_create_thread(self, mock_request):
        self.create_thread_helper(mock_request)

    @ddt.data(
395
        (ModuleStoreEnum.Type.mongo, 3, 3, 27),
396
        (ModuleStoreEnum.Type.split, 3, 9, 27),
Ben McMorran committed
397 398 399 400 401 402 403
    )
    @ddt.unpack
    @count_queries
    def test_update_thread(self, mock_request):
        self.update_thread_helper(mock_request)


404
@attr(shard=2)
405
@ddt.ddt
406
@patch('lms.lib.comment_client.utils.requests.request', autospec=True)
407
class ViewsTestCase(
408
        ForumsEnableMixin,
409
        UrlResetMixin,
410
        SharedModuleStoreTestCase,
411 412 413 414
        MockRequestSetupMixin,
        ViewsTestCaseMixin,
        MockSignalHandlerMixin
):
Ben McMorran committed
415

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(ViewsTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create(
                org='MITx', course='999',
                discussion_topics={"Some Topic": {"id": "some_topic"}},
                display_name='Robot Super Course',
            )

    @classmethod
    def setUpTestData(cls):
        super(ViewsTestCase, cls).setUpTestData()

        cls.course_id = cls.course.id

        # seed the forums permissions and roles
        call_command('seed_permissions_roles', unicode(cls.course_id))

Ben McMorran committed
435 436 437 438 439
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py,
        # so we need to call super.setUp() which reloads urls.py (because
        # of the UrlResetMixin)
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        super(ViewsTestCase, self).setUp()

        # Patch the comment client user save method so it does not try
        # to create a new cc user when creating a django user
        with patch('student.models.cc.User.save'):
            uname = 'student'
            email = 'student@edx.org'
            self.password = 'test'  # pylint: disable=attribute-defined-outside-init

            # Create the user and make them active so we can log them in.
            self.student = User.objects.create_user(uname, email, self.password)  # pylint: disable=attribute-defined-outside-init
            self.student.is_active = True
            self.student.save()

            # Add a discussion moderator
            self.moderator = UserFactory.create(password=self.password)  # pylint: disable=attribute-defined-outside-init

            # Enroll the student in the course
            CourseEnrollmentFactory(user=self.student,
                                    course_id=self.course_id)

            # Enroll the moderator and give them the appropriate roles
            CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id)
            self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id))

            assert_true(self.client.login(username='student', password=self.password))
Ben McMorran committed
466

467 468 469 470 471 472 473
    @contextmanager
    def assert_discussion_signals(self, signal, user=None):
        if user is None:
            user = self.student
        with self.assert_signal_sent(views, signal, sender=None, user=user, exclude_args=('post',)):
            yield

Ben McMorran committed
474
    def test_create_thread(self, mock_request):
475 476
        with self.assert_discussion_signals('thread_created'):
            self.create_thread_helper(mock_request)
Ben McMorran committed
477

478 479 480 481 482 483 484 485 486 487 488
    def test_create_thread_standalone(self, mock_request):
        team = CourseTeamFactory.create(
            name="A Team",
            course_id=self.course_id,
            topic_id='topic_id',
            discussion_topic_id="i4x-MITx-999-course-Robot_Super_Course"
        )

        # Add the student to the team so they can post to the commentable.
        team.add_user(self.student)

489
        # create_thread_helper verifies that extra data are passed through to the comments service
490
        self.create_thread_helper(mock_request, extra_response_data={'context': ThreadContext.STANDALONE})
491

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    def test_delete_thread(self, mock_request):
        self._set_mock_request_data(mock_request, {
            "user_id": str(self.student.id),
            "closed": False,
        })
        test_thread_id = "test_thread_id"
        request = RequestFactory().post("dummy_url", {"id": test_thread_id})
        request.user = self.student
        request.view_name = "delete_thread"
        with self.assert_discussion_signals('thread_deleted'):
            response = views.delete_thread(
                request,
                course_id=unicode(self.course.id),
                thread_id=test_thread_id
            )
        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)

510
    def test_delete_comment(self, mock_request):
511
        self._set_mock_request_data(mock_request, {
512 513 514 515 516 517 518
            "user_id": str(self.student.id),
            "closed": False,
        })
        test_comment_id = "test_comment_id"
        request = RequestFactory().post("dummy_url", {"id": test_comment_id})
        request.user = self.student
        request.view_name = "delete_comment"
519 520 521 522 523 524
        with self.assert_discussion_signals('comment_deleted'):
            response = views.delete_comment(
                request,
                course_id=unicode(self.course.id),
                comment_id=test_comment_id
            )
525 526 527 528 529 530
        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        args = mock_request.call_args[0]
        self.assertEqual(args[0], "delete")
        self.assertTrue(args[1].endswith("/{}".format(test_comment_id)))

531 532 533 534 535 536 537
    def _test_request_error(self, view_name, view_kwargs, data, mock_request):
        """
        Submit a request against the given view with the given data and ensure
        that the result is a 400 error and that no data was posted using
        mock_request
        """
        self._setup_mock_request(mock_request, include_depth=(view_name == "create_sub_comment"))
538 539 540 541 542 543 544 545 546

        response = self.client.post(reverse(view_name, kwargs=view_kwargs), data=data)
        self.assertEqual(response.status_code, 400)
        for call in mock_request.call_args_list:
            self.assertEqual(call[0][0].lower(), "get")

    def test_create_thread_no_title(self, mock_request):
        self._test_request_error(
            "create_thread",
547
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
548 549 550 551 552 553 554
            {"body": "foo"},
            mock_request
        )

    def test_create_thread_empty_title(self, mock_request):
        self._test_request_error(
            "create_thread",
555
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
556 557 558 559 560 561 562
            {"body": "foo", "title": " "},
            mock_request
        )

    def test_create_thread_no_body(self, mock_request):
        self._test_request_error(
            "create_thread",
563
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
564 565 566 567 568 569 570
            {"title": "foo"},
            mock_request
        )

    def test_create_thread_empty_body(self, mock_request):
        self._test_request_error(
            "create_thread",
571
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
572 573 574 575 576 577 578
            {"body": " ", "title": "foo"},
            mock_request
        )

    def test_update_thread_no_title(self, mock_request):
        self._test_request_error(
            "update_thread",
579
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
580 581 582 583 584 585 586
            {"body": "foo"},
            mock_request
        )

    def test_update_thread_empty_title(self, mock_request):
        self._test_request_error(
            "update_thread",
587
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
588 589 590 591 592 593 594
            {"body": "foo", "title": " "},
            mock_request
        )

    def test_update_thread_no_body(self, mock_request):
        self._test_request_error(
            "update_thread",
595
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
596 597 598 599 600 601 602
            {"title": "foo"},
            mock_request
        )

    def test_update_thread_empty_body(self, mock_request):
        self._test_request_error(
            "update_thread",
603
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
604 605 606 607
            {"body": " ", "title": "foo"},
            mock_request
        )

polesye committed
608
    def test_update_thread_course_topic(self, mock_request):
609 610
        with self.assert_discussion_signals('thread_edited'):
            self.update_thread_helper(mock_request)
polesye committed
611

612
    @patch('django_comment_client.utils.get_discussion_categories_ids', return_value=["test_commentable"])
613 614 615
    def test_update_thread_wrong_commentable_id(self, mock_get_discussion_id_map, mock_request):
        self._test_request_error(
            "update_thread",
616
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
617 618 619 620
            {"body": "foo", "title": "foo", "commentable_id": "wrong_commentable"},
            mock_request
        )

621 622 623 624 625 626 627 628 629 630 631 632
    def test_create_comment(self, mock_request):
        self._setup_mock_request(mock_request)
        with self.assert_discussion_signals('comment_created'):
            response = self.client.post(
                reverse(
                    "create_comment",
                    kwargs={"course_id": unicode(self.course_id), "thread_id": "dummy"}
                ),
                data={"body": "body"}
            )
        self.assertEqual(response.status_code, 200)

633 634 635
    def test_create_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_comment",
636
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
637 638 639 640 641 642 643
            {},
            mock_request
        )

    def test_create_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_comment",
644
            {"thread_id": "dummy", "course_id": unicode(self.course_id)},
645 646 647 648 649 650 651
            {"body": " "},
            mock_request
        )

    def test_create_sub_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment",
652
            {"comment_id": "dummy", "course_id": unicode(self.course_id)},
653 654 655 656 657 658 659
            {},
            mock_request
        )

    def test_create_sub_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment",
660
            {"comment_id": "dummy", "course_id": unicode(self.course_id)},
661 662 663 664 665 666 667
            {"body": " "},
            mock_request
        )

    def test_update_comment_no_body(self, mock_request):
        self._test_request_error(
            "update_comment",
668
            {"comment_id": "dummy", "course_id": unicode(self.course_id)},
669 670 671 672 673 674 675
            {},
            mock_request
        )

    def test_update_comment_empty_body(self, mock_request):
        self._test_request_error(
            "update_comment",
676
            {"comment_id": "dummy", "course_id": unicode(self.course_id)},
677 678 679 680
            {"body": " "},
            mock_request
        )

681 682 683 684
    def test_update_comment_basic(self, mock_request):
        self._setup_mock_request(mock_request)
        comment_id = "test_comment_id"
        updated_body = "updated body"
685 686 687 688 689 690 691 692
        with self.assert_discussion_signals('comment_edited'):
            response = self.client.post(
                reverse(
                    "update_comment",
                    kwargs={"course_id": unicode(self.course_id), "comment_id": comment_id}
                ),
                data={"body": updated_body}
            )
693 694 695 696 697 698 699 700 701 702
        self.assertEqual(response.status_code, 200)
        mock_request.assert_called_with(
            "put",
            "{prefix}/comments/{comment_id}".format(prefix=CS_PREFIX, comment_id=comment_id),
            headers=ANY,
            params=ANY,
            timeout=ANY,
            data={"body": updated_body}
        )

703 704 705 706 707 708 709
    def test_flag_thread_open(self, mock_request):
        self.flag_thread(mock_request, False)

    def test_flag_thread_close(self, mock_request):
        self.flag_thread(mock_request, True)

    def flag_thread(self, mock_request, is_closed):
710
        mock_request.return_value.status_code = 200
711 712 713 714 715 716 717 718 719 720
        self._set_mock_request_data(mock_request, {
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
721
            "closed": is_closed,
722
            "id": "518d4237b023791dca00000d",
723
            "user_id": "1", "username": "robot",
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [1],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0,
        })
739 740 741 742
        url = reverse('flag_abuse_for_thread', kwargs={
            'thread_id': '518d4237b023791dca00000d',
            'course_id': unicode(self.course_id)
        })
743
        response = self.client.post(url)
744
        assert_true(mock_request.called)
745

746 747
        call_list = [
            (
748
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
749
                {
750
                    'data': None,
751
                    'params': {'mark_as_read': True, 'request_id': ANY, 'with_responses': False},
752
                    'headers': ANY,
753 754 755 756
                    'timeout': 5
                }
            ),
            (
757
                ('put', '{prefix}/threads/518d4237b023791dca00000d/abuse_flag'.format(prefix=CS_PREFIX)),
758 759
                {
                    'data': {'user_id': '1'},
760
                    'params': {'request_id': ANY},
761
                    'headers': ANY,
762 763 764 765
                    'timeout': 5
                }
            ),
            (
766
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
767
                {
768
                    'data': None,
769
                    'params': {'mark_as_read': True, 'request_id': ANY, 'with_responses': False},
770
                    'headers': ANY,
771 772 773 774
                    'timeout': 5
                }
            )
        ]
775

776
        assert_equal(call_list, mock_request.call_args_list)
777 778

        assert_equal(response.status_code, 200)
779

780 781 782 783 784 785 786
    def test_un_flag_thread_open(self, mock_request):
        self.un_flag_thread(mock_request, False)

    def test_un_flag_thread_close(self, mock_request):
        self.un_flag_thread(mock_request, True)

    def un_flag_thread(self, mock_request, is_closed):
787
        mock_request.return_value.status_code = 200
788 789 790 791 792 793 794 795 796 797
        self._set_mock_request_data(mock_request, {
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
798
            "closed": is_closed,
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "robot",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0
        })
817 818 819 820
        url = reverse('un_flag_abuse_for_thread', kwargs={
            'thread_id': '518d4237b023791dca00000d',
            'course_id': unicode(self.course_id)
        })
821 822 823
        response = self.client.post(url)
        assert_true(mock_request.called)

824 825
        call_list = [
            (
826
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
827
                {
828
                    'data': None,
829
                    'params': {'mark_as_read': True, 'request_id': ANY, 'with_responses': False},
830
                    'headers': ANY,
831 832 833 834
                    'timeout': 5
                }
            ),
            (
835
                ('put', '{prefix}/threads/518d4237b023791dca00000d/abuse_unflag'.format(prefix=CS_PREFIX)),
836 837
                {
                    'data': {'user_id': '1'},
838
                    'params': {'request_id': ANY},
839
                    'headers': ANY,
840 841 842 843
                    'timeout': 5
                }
            ),
            (
844
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
845
                {
846
                    'data': None,
847
                    'params': {'mark_as_read': True, 'request_id': ANY, 'with_responses': False},
848
                    'headers': ANY,
849 850 851 852
                    'timeout': 5
                }
            )
        ]
853

854
        assert_equal(call_list, mock_request.call_args_list)
855 856 857

        assert_equal(response.status_code, 200)

858 859 860 861 862 863 864
    def test_flag_comment_open(self, mock_request):
        self.flag_comment(mock_request, False)

    def test_flag_comment_close(self, mock_request):
        self.flag_comment(mock_request, True)

    def flag_comment(self, mock_request, is_closed):
865
        mock_request.return_value.status_code = 200
866 867 868 869 870 871 872 873 874
        self._set_mock_request_data(mock_request, {
            "body": "this is a comment",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
875
            "closed": is_closed,
876 877 878 879 880 881 882 883 884 885 886 887 888
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "robot",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [1],
            "type": "comment",
            "endorsed": False
        })
889 890 891 892
        url = reverse('flag_abuse_for_comment', kwargs={
            'comment_id': '518d4237b023791dca00000d',
            'course_id': unicode(self.course_id)
        })
893 894 895
        response = self.client.post(url)
        assert_true(mock_request.called)

896 897
        call_list = [
            (
898
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
899
                {
900 901
                    'data': None,
                    'params': {'request_id': ANY},
902
                    'headers': ANY,
903 904 905 906
                    'timeout': 5
                }
            ),
            (
907
                ('put', '{prefix}/comments/518d4237b023791dca00000d/abuse_flag'.format(prefix=CS_PREFIX)),
908 909
                {
                    'data': {'user_id': '1'},
910
                    'params': {'request_id': ANY},
911
                    'headers': ANY,
912 913 914 915
                    'timeout': 5
                }
            ),
            (
916
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
917
                {
918 919
                    'data': None,
                    'params': {'request_id': ANY},
920
                    'headers': ANY,
921 922 923 924
                    'timeout': 5
                }
            )
        ]
925

926
        assert_equal(call_list, mock_request.call_args_list)
927 928 929

        assert_equal(response.status_code, 200)

930 931 932 933 934 935 936
    def test_un_flag_comment_open(self, mock_request):
        self.un_flag_comment(mock_request, False)

    def test_un_flag_comment_close(self, mock_request):
        self.un_flag_comment(mock_request, True)

    def un_flag_comment(self, mock_request, is_closed):
937
        mock_request.return_value.status_code = 200
938 939 940 941 942 943 944 945 946
        self._set_mock_request_data(mock_request, {
            "body": "this is a comment",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
947
            "closed": is_closed,
948 949 950 951 952 953 954 955 956 957 958 959 960
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "robot",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "comment",
            "endorsed": False
        })
961 962 963 964
        url = reverse('un_flag_abuse_for_comment', kwargs={
            'comment_id': '518d4237b023791dca00000d',
            'course_id': unicode(self.course_id)
        })
965 966 967
        response = self.client.post(url)
        assert_true(mock_request.called)

968 969
        call_list = [
            (
970
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
971
                {
972 973
                    'data': None,
                    'params': {'request_id': ANY},
974
                    'headers': ANY,
975 976 977 978
                    'timeout': 5
                }
            ),
            (
979
                ('put', '{prefix}/comments/518d4237b023791dca00000d/abuse_unflag'.format(prefix=CS_PREFIX)),
980 981
                {
                    'data': {'user_id': '1'},
982
                    'params': {'request_id': ANY},
983
                    'headers': ANY,
984 985 986 987
                    'timeout': 5
                }
            ),
            (
988
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
989
                {
990 991
                    'data': None,
                    'params': {'request_id': ANY},
992
                    'headers': ANY,
993 994 995 996
                    'timeout': 5
                }
            )
        ]
997

998
        assert_equal(call_list, mock_request.call_args_list)
999

1000
        assert_equal(response.status_code, 200)
1001

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    @ddt.data(
        ('upvote_thread', 'thread_id', 'thread_voted'),
        ('upvote_comment', 'comment_id', 'comment_voted'),
        ('downvote_thread', 'thread_id', 'thread_voted'),
        ('downvote_comment', 'comment_id', 'comment_voted')
    )
    @ddt.unpack
    def test_voting(self, view_name, item_id, signal, mock_request):
        self._setup_mock_request(mock_request)
        with self.assert_discussion_signals(signal):
            response = self.client.post(
                reverse(
                    view_name,
                    kwargs={item_id: 'dummy', 'course_id': unicode(self.course_id)}
                )
            )
        self.assertEqual(response.status_code, 200)

    def test_endorse_comment(self, mock_request):
        self._setup_mock_request(mock_request)
        self.client.login(username=self.moderator.username, password=self.password)
        with self.assert_discussion_signals('comment_endorsed', user=self.moderator):
            response = self.client.post(
                reverse(
                    'endorse_comment',
                    kwargs={'comment_id': 'dummy', 'course_id': unicode(self.course_id)}
                )
            )
        self.assertEqual(response.status_code, 200)

1032

1033
@attr(shard=2)
1034
@patch("lms.lib.comment_client.utils.requests.request", autospec=True)
1035
@disable_signal(views, 'comment_endorsed')
1036
class ViewPermissionsTestCase(ForumsEnableMixin, UrlResetMixin, SharedModuleStoreTestCase, MockRequestSetupMixin):
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(ViewPermissionsTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()

    @classmethod
    def setUpTestData(cls):
        super(ViewPermissionsTestCase, cls).setUpTestData()

        seed_permissions_roles(cls.course.id)

        cls.password = "test password"
        cls.student = UserFactory.create(password=cls.password)
        cls.moderator = UserFactory.create(password=cls.password)

        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
        CourseEnrollmentFactory(user=cls.moderator, course_id=cls.course.id)

        cls.moderator.roles.add(Role.objects.get(name="Moderator", course_id=cls.course.id))

1059 1060 1061 1062 1063
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(ViewPermissionsTestCase, self).setUp()

    def test_pin_thread_as_student(self, mock_request):
1064
        self._set_mock_request_data(mock_request, {})
1065 1066
        self.client.login(username=self.student.username, password=self.password)
        response = self.client.post(
1067
            reverse("pin_thread", kwargs={"course_id": unicode(self.course.id), "thread_id": "dummy"})
1068 1069 1070 1071
        )
        self.assertEqual(response.status_code, 401)

    def test_pin_thread_as_moderator(self, mock_request):
1072
        self._set_mock_request_data(mock_request, {})
1073 1074
        self.client.login(username=self.moderator.username, password=self.password)
        response = self.client.post(
1075
            reverse("pin_thread", kwargs={"course_id": unicode(self.course.id), "thread_id": "dummy"})
1076 1077 1078 1079
        )
        self.assertEqual(response.status_code, 200)

    def test_un_pin_thread_as_student(self, mock_request):
1080
        self._set_mock_request_data(mock_request, {})
1081 1082
        self.client.login(username=self.student.username, password=self.password)
        response = self.client.post(
1083
            reverse("un_pin_thread", kwargs={"course_id": unicode(self.course.id), "thread_id": "dummy"})
1084 1085 1086 1087
        )
        self.assertEqual(response.status_code, 401)

    def test_un_pin_thread_as_moderator(self, mock_request):
1088
        self._set_mock_request_data(mock_request, {})
1089 1090
        self.client.login(username=self.moderator.username, password=self.password)
        response = self.client.post(
1091
            reverse("un_pin_thread", kwargs={"course_id": unicode(self.course.id), "thread_id": "dummy"})
1092 1093 1094
        )
        self.assertEqual(response.status_code, 200)

1095 1096 1097 1098
    def _set_mock_request_thread_and_comment(self, mock_request, thread_data, comment_data):
        def handle_request(*args, **kwargs):
            url = args[1]
            if "/threads/" in url:
1099
                return self._create_response_mock(thread_data)
1100
            elif "/comments/" in url:
1101
                return self._create_response_mock(comment_data)
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
            else:
                raise ArgumentError("Bad url to mock request")
        mock_request.side_effect = handle_request

    def test_endorse_response_as_staff(self, mock_request):
        self._set_mock_request_thread_and_comment(
            mock_request,
            {"type": "thread", "thread_type": "question", "user_id": str(self.student.id)},
            {"type": "comment", "thread_id": "dummy"}
        )
        self.client.login(username=self.moderator.username, password=self.password)
        response = self.client.post(
1114
            reverse("endorse_comment", kwargs={"course_id": unicode(self.course.id), "comment_id": "dummy"})
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
        )
        self.assertEqual(response.status_code, 200)

    def test_endorse_response_as_student(self, mock_request):
        self._set_mock_request_thread_and_comment(
            mock_request,
            {"type": "thread", "thread_type": "question", "user_id": str(self.moderator.id)},
            {"type": "comment", "thread_id": "dummy"}
        )
        self.client.login(username=self.student.username, password=self.password)
        response = self.client.post(
1126
            reverse("endorse_comment", kwargs={"course_id": unicode(self.course.id), "comment_id": "dummy"})
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        )
        self.assertEqual(response.status_code, 401)

    def test_endorse_response_as_student_question_author(self, mock_request):
        self._set_mock_request_thread_and_comment(
            mock_request,
            {"type": "thread", "thread_type": "question", "user_id": str(self.student.id)},
            {"type": "comment", "thread_id": "dummy"}
        )
        self.client.login(username=self.student.username, password=self.password)
        response = self.client.post(
1138
            reverse("endorse_comment", kwargs={"course_id": unicode(self.course.id), "comment_id": "dummy"})
1139 1140 1141
        )
        self.assertEqual(response.status_code, 200)

1142

1143
@attr(shard=2)
1144 1145 1146 1147 1148
class CreateThreadUnicodeTestCase(
        ForumsEnableMixin,
        SharedModuleStoreTestCase,
        UnicodeTestMixin,
        MockRequestSetupMixin):
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(CreateThreadUnicodeTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()

    @classmethod
    def setUpTestData(cls):
        super(CreateThreadUnicodeTestCase, cls).setUpTestData()
1159

1160 1161 1162
        seed_permissions_roles(cls.course.id)
        cls.student = UserFactory.create()
        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
1163

1164
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1165 1166 1167 1168
    def _test_unicode_data(self, text, mock_request,):
        """
        Test to make sure unicode data in a thread doesn't break it.
        """
1169
        self._set_mock_request_data(mock_request, {})
1170
        request = RequestFactory().post("dummy_url", {"thread_type": "discussion", "body": text, "title": text})
1171 1172
        request.user = self.student
        request.view_name = "create_thread"
1173
        response = views.create_thread(
1174 1175
            # The commentable ID contains a username, the Unicode char below ensures it works fine
            request, course_id=unicode(self.course.id), commentable_id=u"non_tåem_dummy_id"
1176
        )
1177 1178 1179 1180 1181 1182 1183

        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        self.assertEqual(mock_request.call_args[1]["data"]["body"], text)
        self.assertEqual(mock_request.call_args[1]["data"]["title"], text)


1184
@attr(shard=2)
1185
@disable_signal(views, 'thread_edited')
1186 1187 1188 1189 1190 1191
class UpdateThreadUnicodeTestCase(
        ForumsEnableMixin,
        SharedModuleStoreTestCase,
        UnicodeTestMixin,
        MockRequestSetupMixin
):
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201

    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(UpdateThreadUnicodeTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()

    @classmethod
    def setUpTestData(cls):
        super(UpdateThreadUnicodeTestCase, cls).setUpTestData()
1202

1203 1204 1205
        seed_permissions_roles(cls.course.id)
        cls.student = UserFactory.create()
        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
1206

1207
    @patch('django_comment_client.utils.get_discussion_categories_ids', return_value=["test_commentable"])
1208
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1209
    def _test_unicode_data(self, text, mock_request, mock_get_discussion_id_map):
1210
        self._set_mock_request_data(mock_request, {
1211 1212 1213
            "user_id": str(self.student.id),
            "closed": False,
        })
1214
        request = RequestFactory().post("dummy_url", {"body": text, "title": text, "thread_type": "question", "commentable_id": "test_commentable"})
1215 1216
        request.user = self.student
        request.view_name = "update_thread"
1217
        response = views.update_thread(request, course_id=unicode(self.course.id), thread_id="dummy_thread_id")
1218 1219 1220 1221 1222

        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        self.assertEqual(mock_request.call_args[1]["data"]["body"], text)
        self.assertEqual(mock_request.call_args[1]["data"]["title"], text)
1223
        self.assertEqual(mock_request.call_args[1]["data"]["thread_type"], "question")
1224
        self.assertEqual(mock_request.call_args[1]["data"]["commentable_id"], "test_commentable")
1225 1226


1227
@attr(shard=2)
1228
@disable_signal(views, 'comment_created')
1229 1230 1231 1232 1233 1234
class CreateCommentUnicodeTestCase(
        ForumsEnableMixin,
        SharedModuleStoreTestCase,
        UnicodeTestMixin,
        MockRequestSetupMixin
):
1235 1236 1237 1238 1239 1240

    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(CreateCommentUnicodeTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()
1241

1242 1243 1244 1245 1246 1247 1248
    @classmethod
    def setUpTestData(cls):
        super(CreateCommentUnicodeTestCase, cls).setUpTestData()

        seed_permissions_roles(cls.course.id)
        cls.student = UserFactory.create()
        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
1249

1250
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1251
    def _test_unicode_data(self, text, mock_request):
1252
        commentable_id = "non_team_dummy_id"
1253
        self._set_mock_request_data(mock_request, {
1254
            "closed": False,
1255
            "commentable_id": commentable_id
1256
        })
1257 1258 1259
        # We have to get clever here due to Thread's setters and getters.
        # Patch won't work with it.
        try:
1260
            Thread.commentable_id = commentable_id
1261 1262 1263 1264 1265 1266
            request = RequestFactory().post("dummy_url", {"body": text})
            request.user = self.student
            request.view_name = "create_comment"
            response = views.create_comment(
                request, course_id=unicode(self.course.id), thread_id="dummy_thread_id"
            )
1267

1268 1269 1270 1271 1272
            self.assertEqual(response.status_code, 200)
            self.assertTrue(mock_request.called)
            self.assertEqual(mock_request.call_args[1]["data"]["body"], text)
        finally:
            del Thread.commentable_id
1273 1274


1275
@attr(shard=2)
1276
@disable_signal(views, 'comment_edited')
1277 1278 1279 1280 1281 1282
class UpdateCommentUnicodeTestCase(
        ForumsEnableMixin,
        SharedModuleStoreTestCase,
        UnicodeTestMixin,
        MockRequestSetupMixin
):
1283 1284 1285 1286 1287 1288

    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(UpdateCommentUnicodeTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()
1289

1290 1291 1292 1293 1294 1295 1296
    @classmethod
    def setUpTestData(cls):
        super(UpdateCommentUnicodeTestCase, cls).setUpTestData()

        seed_permissions_roles(cls.course.id)
        cls.student = UserFactory.create()
        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
1297

1298
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1299
    def _test_unicode_data(self, text, mock_request):
1300
        self._set_mock_request_data(mock_request, {
1301 1302 1303 1304 1305 1306
            "user_id": str(self.student.id),
            "closed": False,
        })
        request = RequestFactory().post("dummy_url", {"body": text})
        request.user = self.student
        request.view_name = "update_comment"
1307
        response = views.update_comment(request, course_id=unicode(self.course.id), comment_id="dummy_comment_id")
1308 1309 1310 1311 1312 1313

        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        self.assertEqual(mock_request.call_args[1]["data"]["body"], text)


1314
@attr(shard=2)
1315
@disable_signal(views, 'comment_created')
1316 1317 1318 1319 1320 1321
class CreateSubCommentUnicodeTestCase(
        ForumsEnableMixin,
        SharedModuleStoreTestCase,
        UnicodeTestMixin,
        MockRequestSetupMixin
):
1322 1323 1324
    """
    Make sure comments under a response can handle unicode.
    """
1325 1326 1327 1328 1329
    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(CreateSubCommentUnicodeTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()
1330

1331 1332 1333 1334 1335 1336 1337
    @classmethod
    def setUpTestData(cls):
        super(CreateSubCommentUnicodeTestCase, cls).setUpTestData()

        seed_permissions_roles(cls.course.id)
        cls.student = UserFactory.create()
        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
1338

1339
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1340
    def _test_unicode_data(self, text, mock_request):
1341 1342 1343
        """
        Create a comment with unicode in it.
        """
1344
        self._set_mock_request_data(mock_request, {
1345 1346
            "closed": False,
            "depth": 1,
1347 1348
            "thread_id": "test_thread",
            "commentable_id": "non_team_dummy_id"
1349 1350 1351 1352
        })
        request = RequestFactory().post("dummy_url", {"body": text})
        request.user = self.student
        request.view_name = "create_sub_comment"
1353
        Thread.commentable_id = "test_commentable"
1354 1355
        try:
            response = views.create_sub_comment(
1356
                request, course_id=unicode(self.course.id), comment_id="dummy_comment_id"
1357
            )
1358

1359 1360 1361 1362 1363 1364 1365
            self.assertEqual(response.status_code, 200)
            self.assertTrue(mock_request.called)
            self.assertEqual(mock_request.call_args[1]["data"]["body"], text)
        finally:
            del Thread.commentable_id


1366
@attr(shard=2)
1367
@ddt.ddt
1368
@patch("lms.lib.comment_client.utils.requests.request", autospec=True)
1369 1370 1371 1372 1373
@disable_signal(views, 'thread_voted')
@disable_signal(views, 'thread_edited')
@disable_signal(views, 'comment_created')
@disable_signal(views, 'comment_voted')
@disable_signal(views, 'comment_deleted')
1374
class TeamsPermissionsTestCase(ForumsEnableMixin, UrlResetMixin, SharedModuleStoreTestCase, MockRequestSetupMixin):
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    # Most of the test points use the same ddt data.
    # args: user, commentable_id, status_code
    ddt_permissions_args = [
        # Student in team can do operations on threads/comments within the team commentable.
        ('student_in_team', 'team_commentable_id', 200),
        # Non-team commentables can be edited by any student.
        ('student_in_team', 'course_commentable_id', 200),
        # Student not in team cannot do operations within the team commentable.
        ('student_not_in_team', 'team_commentable_id', 401),
        # Non-team commentables can be edited by any student.
        ('student_not_in_team', 'course_commentable_id', 200),
1386
        # Moderators can always operator on threads within a team, regardless of team membership.
1387 1388 1389
        ('moderator', 'team_commentable_id', 200),
        # Group moderators have regular student privileges for creating a thread and commenting
        ('group_moderator', 'course_commentable_id', 200)
1390 1391
    ]

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    def change_divided_discussion_settings(self, scheme):
        """
        Change divided discussion settings for the current course.
        If dividing by cohorts, create and assign users to a cohort.
        """
        enable_cohorts = True if scheme is CourseDiscussionSettings.COHORT else False
        set_course_discussion_settings(
            self.course.id,
            enable_cohorts=enable_cohorts,
            divided_discussions=[],
            always_divide_inline_discussions=True,
            division_scheme=scheme,
        )
        set_course_cohorted(self.course.id, enable_cohorts)

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(TeamsPermissionsTestCase, cls).setUpClassAndTestData():
            teams_configuration = {
                'topics': [{'id': "topic_id", 'name': 'Solar Power', 'description': 'Solar power is hot'}]
            }
            cls.course = CourseFactory.create(teams_configuration=teams_configuration)

    @classmethod
    def setUpTestData(cls):
        super(TeamsPermissionsTestCase, cls).setUpTestData()
1419
        cls.course = CourseFactory.create()
1420 1421
        cls.password = "test password"
        seed_permissions_roles(cls.course.id)
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
        # Create enrollment tracks
        CourseModeFactory.create(
            course_id=cls.course.id,
            mode_slug=CourseMode.VERIFIED
        )
        CourseModeFactory.create(
            course_id=cls.course.id,
            mode_slug=CourseMode.AUDIT
        )

        # Create 6 users--
        # student in team (in the team, audit)
        # student not in team (not in the team, audit)
        # cohorted (in the cohort, audit)
        # verified (not in the cohort, verified)
        # moderator (in the cohort, audit, moderator permissions)
        # group moderator (in the cohort, verified, group moderator permissions)
        def create_users_and_enroll(coursemode):
            student = UserFactory.create(password=cls.password)
            CourseEnrollmentFactory(
                course_id=cls.course.id,
                user=student,
                mode=coursemode
            )
            return student

        cls.student_in_team, cls.student_not_in_team, cls.moderator, cls.cohorted = (
            [create_users_and_enroll(CourseMode.AUDIT) for _ in range(4)])
        cls.verified, cls.group_moderator = [create_users_and_enroll(CourseMode.VERIFIED) for _ in range(2)]

        # Give moderator and group moderator permissions
1454
        cls.moderator.roles.add(Role.objects.get(name="Moderator", course_id=cls.course.id))
1455
        assign_role(cls.course.id, cls.group_moderator, 'Group Moderator')
1456

1457
        # Create a team
1458 1459
        cls.team_commentable_id = "team_discussion_id"
        cls.team = CourseTeamFactory.create(
1460
            name=u'The Only Team',
1461
            course_id=cls.course.id,
1462
            topic_id='topic_id',
1463
            discussion_topic_id=cls.team_commentable_id
1464
        )
1465
        CourseTeamMembershipFactory.create(team=cls.team, user=cls.student_in_team)
1466 1467

        # Dummy commentable ID not linked to a team
1468 1469
        cls.course_commentable_id = "course_level_commentable"

1470 1471 1472 1473 1474 1475 1476
        # Create cohort and add students to it
        CohortFactory(
            course_id=cls.course.id,
            name='Test Cohort',
            users=[cls.group_moderator, cls.cohorted]
        )

1477 1478 1479
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(TeamsPermissionsTestCase, self).setUp()
1480 1481 1482 1483 1484 1485 1486 1487

    def _setup_mock(self, user, mock_request, data):
        user = getattr(self, user)
        self._set_mock_request_data(mock_request, data)
        self.client.login(username=user.username, password=self.password)

    @ddt.data(
        # student_in_team will be able to update his own post, regardless of team membership
1488 1489
        ('student_in_team', 'student_in_team', 'team_commentable_id', 200, CourseDiscussionSettings.NONE),
        ('student_in_team', 'student_in_team', 'course_commentable_id', 200, CourseDiscussionSettings.NONE),
1490
        # students can only update their own posts
1491
        ('student_in_team', 'moderator', 'team_commentable_id', 401, CourseDiscussionSettings.NONE),
1492
        # Even though student_not_in_team is not in the team, he can still modify posts he created while in the team.
1493
        ('student_not_in_team', 'student_not_in_team', 'team_commentable_id', 200, CourseDiscussionSettings.NONE),
1494
        # Moderators can change their own posts and other people's posts.
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
        ('moderator', 'moderator', 'team_commentable_id', 200, CourseDiscussionSettings.NONE),
        ('moderator', 'student_in_team', 'team_commentable_id', 200, CourseDiscussionSettings.NONE),
        # Group moderator can do operations on commentables within their group if the course is divided
        ('group_moderator', 'verified', 'course_commentable_id', 200, CourseDiscussionSettings.ENROLLMENT_TRACK),
        ('group_moderator', 'cohorted', 'course_commentable_id', 200, CourseDiscussionSettings.COHORT),
        # Group moderators cannot do operations on commentables outside of their group
        ('group_moderator', 'verified', 'course_commentable_id', 401, CourseDiscussionSettings.COHORT),
        ('group_moderator', 'cohorted', 'course_commentable_id', 401, CourseDiscussionSettings.ENROLLMENT_TRACK),
        # Group moderators cannot do operations when the course is not divided
        ('group_moderator', 'verified', 'course_commentable_id', 401, CourseDiscussionSettings.NONE),
        ('group_moderator', 'cohorted', 'course_commentable_id', 401, CourseDiscussionSettings.NONE)
1506 1507
    )
    @ddt.unpack
1508
    def test_update_thread(self, user, thread_author, commentable_id, status_code, division_scheme, mock_request):
1509 1510 1511
        """
        Verify that update_thread is limited to thread authors and privileged users (team membership does not matter).
        """
1512
        self.change_divided_discussion_settings(division_scheme)
1513 1514 1515
        commentable_id = getattr(self, commentable_id)
        # thread_author is who is marked as the author of the thread being updated.
        thread_author = getattr(self, thread_author)
1516

1517 1518
        self._setup_mock(
            user, mock_request,  # user is the person making the request.
1519 1520 1521
            {
                "user_id": str(thread_author.id),
                "closed": False, "commentable_id": commentable_id,
1522 1523 1524
                "context": "standalone",
                "username": thread_author.username,
                "course_id": unicode(self.course.id)
1525
            }
1526 1527 1528 1529 1530 1531 1532 1533 1534
        )
        response = self.client.post(
            reverse(
                "update_thread",
                kwargs={
                    "course_id": unicode(self.course.id),
                    "thread_id": "dummy"
                }
            ),
1535
            data={"body": "foo", "title": "foo", "commentable_id": commentable_id}
1536 1537 1538
        )
        self.assertEqual(response.status_code, status_code)

1539 1540
    @ddt.data(
        # Students can delete their own posts
1541
        ('student_in_team', 'student_in_team', 'team_commentable_id', 200, CourseDiscussionSettings.NONE),
1542
        # Moderators can delete any post
1543
        ('moderator', 'student_in_team', 'team_commentable_id', 200, CourseDiscussionSettings.NONE),
1544
        # Others cannot delete posts
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
        ('student_in_team', 'moderator', 'team_commentable_id', 401, CourseDiscussionSettings.NONE),
        ('student_not_in_team', 'student_in_team', 'team_commentable_id', 401, CourseDiscussionSettings.NONE),
        # Group moderator can do operations on commentables within their group if the course is divided
        ('group_moderator', 'verified', 'team_commentable_id', 200, CourseDiscussionSettings.ENROLLMENT_TRACK),
        ('group_moderator', 'cohorted', 'team_commentable_id', 200, CourseDiscussionSettings.COHORT),
        # Group moderators cannot do operations on commentables outside of their group
        ('group_moderator', 'verified', 'team_commentable_id', 401, CourseDiscussionSettings.COHORT),
        ('group_moderator', 'cohorted', 'team_commentable_id', 401, CourseDiscussionSettings.ENROLLMENT_TRACK),
        # Group moderators cannot do operations when the course is not divided
        ('group_moderator', 'verified', 'team_commentable_id', 401, CourseDiscussionSettings.NONE),
        ('group_moderator', 'cohorted', 'team_commentable_id', 401, CourseDiscussionSettings.NONE)
1556 1557
    )
    @ddt.unpack
1558
    def test_delete_comment(self, user, comment_author, commentable_id, status_code, division_scheme, mock_request):
1559 1560
        commentable_id = getattr(self, commentable_id)
        comment_author = getattr(self, comment_author)
1561
        self.change_divided_discussion_settings(division_scheme)
1562 1563 1564 1565

        self._setup_mock(user, mock_request, {
            "closed": False,
            "commentable_id": commentable_id,
1566 1567 1568
            "user_id": str(comment_author.id),
            "username": comment_author.username,
            "course_id": unicode(self.course.id)
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        })

        response = self.client.post(
            reverse(
                "delete_comment",
                kwargs={
                    "course_id": unicode(self.course.id),
                    "comment_id": "dummy"
                }
            ),
            data={"body": "foo", "title": "foo"}
        )
        self.assertEqual(response.status_code, status_code)

1583 1584 1585 1586
    @ddt.data(*ddt_permissions_args)
    @ddt.unpack
    def test_create_comment(self, user, commentable_id, status_code, mock_request):
        """
1587
        Verify that create_comment is limited to members of the team or users with 'edit_content' permission.
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
        """
        commentable_id = getattr(self, commentable_id)
        self._setup_mock(user, mock_request, {"closed": False, "commentable_id": commentable_id})

        response = self.client.post(
            reverse(
                "create_comment",
                kwargs={
                    "course_id": unicode(self.course.id),
                    "thread_id": "dummy"
                }
            ),
            data={"body": "foo", "title": "foo"}
        )
        self.assertEqual(response.status_code, status_code)

    @ddt.data(*ddt_permissions_args)
    @ddt.unpack
    def test_create_sub_comment(self, user, commentable_id, status_code, mock_request):
        """
1608
        Verify that create_subcomment is limited to members of the team or users with 'edit_content' permission.
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
        """
        commentable_id = getattr(self, commentable_id)
        self._setup_mock(
            user, mock_request,
            {"closed": False, "commentable_id": commentable_id, "thread_id": "dummy_thread"},
        )
        response = self.client.post(
            reverse(
                "create_sub_comment",
                kwargs={
                    "course_id": unicode(self.course.id),
                    "comment_id": "dummy_comment"
                }
            ),
            data={"body": "foo", "title": "foo"}
        )
        self.assertEqual(response.status_code, status_code)

    @ddt.data(*ddt_permissions_args)
    @ddt.unpack
    def test_comment_actions(self, user, commentable_id, status_code, mock_request):
        """
1631 1632
        Verify that voting and flagging of comments is limited to members of the team or users with
        'edit_content' permission.
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
        """
        commentable_id = getattr(self, commentable_id)
        self._setup_mock(
            user, mock_request,
            {"closed": False, "commentable_id": commentable_id, "thread_id": "dummy_thread"},
        )
        for action in ["upvote_comment", "downvote_comment", "un_flag_abuse_for_comment", "flag_abuse_for_comment"]:
            response = self.client.post(
                reverse(
                    action,
                    kwargs={"course_id": unicode(self.course.id), "comment_id": "dummy_comment"}
                )
            )
            self.assertEqual(response.status_code, status_code)

    @ddt.data(*ddt_permissions_args)
    @ddt.unpack
    def test_threads_actions(self, user, commentable_id, status_code, mock_request):
        """
1652 1653
        Verify that voting, flagging, and following of threads is limited to members of the team or users with
        'edit_content' permission.
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
        """
        commentable_id = getattr(self, commentable_id)
        self._setup_mock(
            user, mock_request,
            {"closed": False, "commentable_id": commentable_id},
        )
        for action in ["upvote_thread", "downvote_thread", "un_flag_abuse_for_thread", "flag_abuse_for_thread",
                       "follow_thread", "unfollow_thread"]:
            response = self.client.post(
                reverse(
                    action,
                    kwargs={"course_id": unicode(self.course.id), "thread_id": "dummy_thread"}
                )
            )
            self.assertEqual(response.status_code, status_code)

    @ddt.data(*ddt_permissions_args)
    @ddt.unpack
    def test_create_thread(self, user, commentable_id, status_code, __):
        """
1674
        Verify that creation of threads is limited to members of the team or users with 'edit_content' permission.
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
        """
        commentable_id = getattr(self, commentable_id)
        # mock_request is not used because Commentables don't exist in comment service.
        self.client.login(username=getattr(self, user).username, password=self.password)
        response = self.client.post(
            reverse(
                "create_thread",
                kwargs={"course_id": unicode(self.course.id), "commentable_id": commentable_id}
            ),
            data={"body": "foo", "title": "foo", "thread_type": "discussion"}
        )
        self.assertEqual(response.status_code, status_code)

    @ddt.data(*ddt_permissions_args)
    @ddt.unpack
    def test_commentable_actions(self, user, commentable_id, status_code, __):
        """
1692 1693
        Verify that following of commentables is limited to members of the team or users with
        'edit_content' permission.
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
        """
        commentable_id = getattr(self, commentable_id)
        # mock_request is not used because Commentables don't exist in comment service.
        self.client.login(username=getattr(self, user).username, password=self.password)
        for action in ["follow_commentable", "unfollow_commentable"]:
            response = self.client.post(
                reverse(
                    action,
                    kwargs={"course_id": unicode(self.course.id), "commentable_id": commentable_id}
                )
            )
            self.assertEqual(response.status_code, status_code)


1708 1709 1710
TEAM_COMMENTABLE_ID = 'test-team-discussion'


1711
@attr(shard=2)
1712
@disable_signal(views, 'comment_created')
1713
@ddt.ddt
1714
class ForumEventTestCase(ForumsEnableMixin, SharedModuleStoreTestCase, MockRequestSetupMixin):
1715 1716 1717
    """
    Forum actions are expected to launch analytics events. Test these here.
    """
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(ForumEventTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()

    @classmethod
    def setUpTestData(cls):
        super(ForumEventTestCase, cls).setUpTestData()

        seed_permissions_roles(cls.course.id)

        cls.student = UserFactory.create()
        CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
        cls.student.roles.add(Role.objects.get(name="Student", course_id=cls.course.id))
        CourseAccessRoleFactory(course_id=cls.course.id, user=cls.student, role='Wizard')
1734 1735

    @patch('eventtracking.tracker.emit')
1736
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
    def test_thread_event(self, __, mock_emit):
        request = RequestFactory().post(
            "dummy_url", {
                "thread_type": "discussion",
                "body": "Test text",
                "title": "Test",
                "auto_subscribe": True
            }
        )
        request.user = self.student
        request.view_name = "create_thread"

1749
        views.create_thread(request, course_id=unicode(self.course.id), commentable_id="test_commentable")
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764

        event_name, event = mock_emit.call_args[0]
        self.assertEqual(event_name, 'edx.forum.thread.created')
        self.assertEqual(event['body'], 'Test text')
        self.assertEqual(event['title'], 'Test')
        self.assertEqual(event['commentable_id'], 'test_commentable')
        self.assertEqual(event['user_forums_roles'], ['Student'])
        self.assertEqual(event['options']['followed'], True)
        self.assertEqual(event['user_course_roles'], ['Wizard'])
        self.assertEqual(event['anonymous'], False)
        self.assertEqual(event['group_id'], None)
        self.assertEqual(event['thread_type'], 'discussion')
        self.assertEquals(event['anonymous_to_peers'], False)

    @patch('eventtracking.tracker.emit')
1765
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
    def test_response_event(self, mock_request, mock_emit):
        """
        Check to make sure an event is fired when a user responds to a thread.
        """
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "closed": False,
            "commentable_id": 'test_commentable_id',
            'thread_id': 'test_thread_id',
        })
        request = RequestFactory().post("dummy_url", {"body": "Test comment", 'auto_subscribe': True})
        request.user = self.student
        request.view_name = "create_comment"
1779
        views.create_comment(request, course_id=unicode(self.course.id), thread_id='test_thread_id')
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790

        event_name, event = mock_emit.call_args[0]
        self.assertEqual(event_name, 'edx.forum.response.created')
        self.assertEqual(event['body'], "Test comment")
        self.assertEqual(event['commentable_id'], 'test_commentable_id')
        self.assertEqual(event['user_forums_roles'], ['Student'])
        self.assertEqual(event['user_course_roles'], ['Wizard'])
        self.assertEqual(event['discussion']['id'], 'test_thread_id')
        self.assertEqual(event['options']['followed'], True)

    @patch('eventtracking.tracker.emit')
1791
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
    def test_comment_event(self, mock_request, mock_emit):
        """
        Ensure an event is fired when someone comments on a response.
        """
        self._set_mock_request_data(mock_request, {
            "closed": False,
            "depth": 1,
            "thread_id": "test_thread_id",
            "commentable_id": "test_commentable_id",
            "parent_id": "test_response_id"
        })
        request = RequestFactory().post("dummy_url", {"body": "Another comment"})
        request.user = self.student
        request.view_name = "create_sub_comment"
1806
        views.create_sub_comment(request, course_id=unicode(self.course.id), comment_id="dummy_comment_id")
1807 1808 1809 1810 1811 1812 1813 1814 1815

        event_name, event = mock_emit.call_args[0]
        self.assertEqual(event_name, "edx.forum.comment.created")
        self.assertEqual(event['body'], 'Another comment')
        self.assertEqual(event['discussion']['id'], 'test_thread_id')
        self.assertEqual(event['response']['id'], 'test_response_id')
        self.assertEqual(event['user_forums_roles'], ['Student'])
        self.assertEqual(event['user_course_roles'], ['Wizard'])
        self.assertEqual(event['options']['followed'], False)
1816

1817
    @patch('eventtracking.tracker.emit')
1818
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
    @ddt.data((
        'create_thread',
        'edx.forum.thread.created', {
            'thread_type': 'discussion',
            'body': 'Test text',
            'title': 'Test',
            'auto_subscribe': True
        },
        {'commentable_id': TEAM_COMMENTABLE_ID}
    ), (
        'create_comment',
        'edx.forum.response.created',
        {'body': 'Test comment', 'auto_subscribe': True},
        {'thread_id': 'test_thread_id'}
    ), (
        'create_sub_comment',
        'edx.forum.comment.created',
        {'body': 'Another comment'},
        {'comment_id': 'dummy_comment_id'}
    ))
    @ddt.unpack
    def test_team_events(self, view_name, event_name, view_data, view_kwargs, mock_request, mock_emit):
        user = self.student
        team = CourseTeamFactory.create(discussion_topic_id=TEAM_COMMENTABLE_ID)
        CourseTeamMembershipFactory.create(team=team, user=user)

        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            'closed': False,
            'commentable_id': TEAM_COMMENTABLE_ID,
            'thread_id': 'test_thread_id',
        })

        request = RequestFactory().post('dummy_url', view_data)
        request.user = user
        request.view_name = view_name

        getattr(views, view_name)(request, course_id=unicode(self.course.id), **view_kwargs)

        name, event = mock_emit.call_args[0]
        self.assertEqual(name, event_name)
        self.assertEqual(event['team_id'], team.team_id)

1862 1863 1864 1865 1866 1867 1868 1869
    @ddt.data(
        ('vote_for_thread', 'thread_id', 'thread'),
        ('undo_vote_for_thread', 'thread_id', 'thread'),
        ('vote_for_comment', 'comment_id', 'response'),
        ('undo_vote_for_comment', 'comment_id', 'response'),
    )
    @ddt.unpack
    @patch('eventtracking.tracker.emit')
1870
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
    def test_thread_voted_event(self, view_name, obj_id_name, obj_type, mock_request, mock_emit):
        undo = view_name.startswith('undo')

        self._set_mock_request_data(mock_request, {
            'closed': False,
            'commentable_id': 'test_commentable_id',
            'username': 'gumprecht',
        })
        request = RequestFactory().post('dummy_url', {})
        request.user = self.student
        request.view_name = view_name
        view_function = getattr(views, view_name)
        kwargs = dict(course_id=unicode(self.course.id))
        kwargs[obj_id_name] = obj_id_name
        if not undo:
            kwargs.update(value='up')
        view_function(request, **kwargs)

        self.assertTrue(mock_emit.called)
        event_name, event = mock_emit.call_args[0]
        self.assertEqual(event_name, 'edx.forum.{}.voted'.format(obj_type))
        self.assertEqual(event['target_username'], 'gumprecht')
        self.assertEqual(event['undo_vote'], undo)
        self.assertEqual(event['vote_value'], 'up')

1896

1897
@attr(shard=2)
1898
class UsersEndpointTestCase(ForumsEnableMixin, SharedModuleStoreTestCase, MockRequestSetupMixin):
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915

    @classmethod
    def setUpClass(cls):
        # pylint: disable=super-method-not-called
        with super(UsersEndpointTestCase, cls).setUpClassAndTestData():
            cls.course = CourseFactory.create()

    @classmethod
    def setUpTestData(cls):
        super(UsersEndpointTestCase, cls).setUpTestData()

        seed_permissions_roles(cls.course.id)

        cls.student = UserFactory.create()
        cls.enrollment = CourseEnrollmentFactory(user=cls.student, course_id=cls.course.id)
        cls.other_user = UserFactory.create(username="other")
        CourseEnrollmentFactory(user=cls.other_user, course_id=cls.course.id)
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932

    def set_post_counts(self, mock_request, threads_count=1, comments_count=1):
        """
        sets up a mock response from the comments service for getting post counts for our other_user
        """
        self._set_mock_request_data(mock_request, {
            "threads_count": threads_count,
            "comments_count": comments_count,
        })

    def make_request(self, method='get', course_id=None, **kwargs):
        course_id = course_id or self.course.id
        request = getattr(RequestFactory(), method)("dummy_url", kwargs)
        request.user = self.student
        request.view_name = "users"
        return views.users(request, course_id=course_id.to_deprecated_string())

1933
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1934 1935 1936 1937 1938 1939 1940 1941 1942
    def test_finds_exact_match(self, mock_request):
        self.set_post_counts(mock_request)
        response = self.make_request(username="other")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            json.loads(response.content)["users"],
            [{"id": self.other_user.id, "username": self.other_user.username}]
        )

1943
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    def test_finds_no_match(self, mock_request):
        self.set_post_counts(mock_request)
        response = self.make_request(username="othor")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)["users"], [])

    def test_requires_GET(self):
        response = self.make_request(method='post', username="other")
        self.assertEqual(response.status_code, 405)

    def test_requires_username_param(self):
        response = self.make_request()
        self.assertEqual(response.status_code, 400)
        content = json.loads(response.content)
        self.assertIn("errors", content)
        self.assertNotIn("users", content)

    def test_course_does_not_exist(self):
1962
        course_id = CourseKey.from_string("does/not/exist")
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
        response = self.make_request(course_id=course_id, username="other")

        self.assertEqual(response.status_code, 404)
        content = json.loads(response.content)
        self.assertIn("errors", content)
        self.assertNotIn("users", content)

    def test_requires_requestor_enrolled_in_course(self):
        # unenroll self.student from the course.
        self.enrollment.delete()

        response = self.make_request(username="other")
        self.assertEqual(response.status_code, 404)
        content = json.loads(response.content)
1977 1978
        self.assertIn("errors", content)
        self.assertNotIn("users", content)
1979

1980
    @patch('lms.lib.comment_client.utils.requests.request', autospec=True)
1981 1982 1983 1984 1985
    def test_requires_matched_user_has_forum_content(self, mock_request):
        self.set_post_counts(mock_request, 0, 0)
        response = self.make_request(username="other")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content)["users"], [])