tests.py 46 KB
Newer Older
1
import logging
2
import json
3

4
from django.test.client import Client, RequestFactory
5
from django.contrib.auth.models import User
6
from django.core.management import call_command
7
from django.core.urlresolvers import reverse
8
from mock import patch, ANY, Mock
9
from nose.tools import assert_true, assert_equal  # pylint: disable=no-name-in-module
10
from opaque_keys.edx.locations import SlashSeparatedCourseKey
11
from lms.lib.comment_client import Thread
12

13
from django_comment_client.base import views
14
from django_comment_client.tests.group_id import CohortedTopicGroupIdTestMixin, NonCohortedTopicGroupIdTestMixin, GroupIdAssertionMixin
15
from django_comment_client.tests.utils import CohortedTestCase
16
from django_comment_client.tests.unicode import UnicodeTestMixin
17
from django_comment_common.models import Role
18
from django_comment_common.utils import seed_permissions_roles
19
from student.tests.factories import CourseEnrollmentFactory, UserFactory, CourseAccessRoleFactory
20 21 22
from util.testing import UrlResetMixin
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
23

24

25 26
log = logging.getLogger(__name__)

27
CS_PREFIX = "http://localhost:4567/api/v1"
28

29
# pylint: disable=missing-docstring
muhammad-ammar committed
30

31 32

class MockRequestSetupMixin(object):
33 34
    def _create_response_mock(self, data):
        return Mock(text=json.dumps(data), json=Mock(return_value=data))
35

36
    def _set_mock_request_data(self, mock_request, data):
37
        mock_request.return_value = self._create_response_mock(data)
38 39


40
@patch('lms.lib.comment_client.utils.requests.request')
41
class CreateThreadGroupIdTestCase(
42
        MockRequestSetupMixin,
43
        CohortedTestCase,
44 45 46 47 48 49
        CohortedTopicGroupIdTestMixin,
        NonCohortedTopicGroupIdTestMixin
):
    cs_endpoint = "/threads"

    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True):
50
        self._set_mock_request_data(mock_request, {})
51 52 53 54 55 56 57 58 59 60 61 62 63
        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,
            course_id=self.course.id.to_deprecated_string(),
            commentable_id=commentable_id
        )
64

65 66 67 68 69 70 71 72 73 74 75 76 77
    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)


@patch('lms.lib.comment_client.utils.requests.request')
class ThreadActionGroupIdTestCase(
        MockRequestSetupMixin,
78
        CohortedTestCase,
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        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,
                "type": "thread"
            }
        )
        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,
            course_id=self.course.id.to_deprecated_string(),
            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']
        )


164
@patch('lms.lib.comment_client.utils.requests.request')
165
class ViewsTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin):
166

167
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
168
    def setUp(self):
169

170 171
        # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py,
        # so we need to call super.setUp() which reloads urls.py (because
172
        # of the UrlResetMixin)
173
        super(ViewsTestCase, self).setUp(create_user=False)
174

175
        # create a course
polesye committed
176 177 178 179 180
        self.course = CourseFactory.create(
            org='MITx', course='999',
            discussion_topics={"Some Topic": {"id": "some_topic"}},
            display_name='Robot Super Course',
        )
181 182
        self.course_id = self.course.id
        # seed the forums permissions and roles
183
        call_command('seed_permissions_roles', self.course_id.to_deprecated_string())
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        # 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'
            password = 'test'

            # Create the user and make them active so we can log them in.
            self.student = User.objects.create_user(uname, email, password)
            self.student.is_active = True
            self.student.save()

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

201 202
            self.client = Client()
            assert_true(self.client.login(username='student', password='test'))
203

204 205
    def test_create_thread(self, mock_request):
        mock_request.return_value.status_code = 200
206
        self._set_mock_request_data(mock_request, {
207
            "thread_type": "discussion",
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
            "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,
        })
236 237 238 239 240 241 242 243
        thread = {
            "thread_type": "discussion",
            "body": ["this is a post"],
            "anonymous_to_peers": ["false"],
            "auto_subscribe": ["false"],
            "anonymous": ["false"],
            "title": ["Hello"],
        }
244
        url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course',
245
                                               'course_id': self.course_id.to_deprecated_string()})
246
        response = self.client.post(url, data=thread)
247
        assert_true(mock_request.called)
248 249
        mock_request.assert_called_with(
            'post',
250
            '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(prefix=CS_PREFIX),
251
            data={
252
                'thread_type': 'discussion',
253 254 255 256
                'body': u'this is a post',
                'anonymous_to_peers': False, 'user_id': 1,
                'title': u'Hello',
                'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course',
257 258
                'anonymous': False,
                'course_id': u'MITx/999/Robot_Super_Course',
259
            },
260
            params={'request_id': ANY},
261
            headers=ANY,
262 263
            timeout=5
        )
264
        assert_equal(response.status_code, 200)
265

266
    def test_delete_comment(self, mock_request):
267
        self._set_mock_request_data(mock_request, {
268 269 270 271 272 273 274
            "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"
275
        response = views.delete_comment(request, course_id=self.course.id.to_deprecated_string(), comment_id=test_comment_id)
276 277 278 279 280 281 282

        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)))

283
    def _setup_mock_request(self, mock_request, include_depth=False):
284
        """
285 286
        Ensure that mock_request returns the data necessary to make views
        function correctly
287 288
        """
        mock_request.return_value.status_code = 200
289
        data = {
290 291 292
            "user_id": str(self.student.id),
            "closed": False,
        }
293 294
        if include_depth:
            data["depth"] = 0
295
        self._set_mock_request_data(mock_request, data)
296 297 298 299 300 301 302 303

    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"))
304 305 306 307 308 309 310 311 312

        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",
313
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
314 315 316 317 318 319 320
            {"body": "foo"},
            mock_request
        )

    def test_create_thread_empty_title(self, mock_request):
        self._test_request_error(
            "create_thread",
321
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
322 323 324 325 326 327 328
            {"body": "foo", "title": " "},
            mock_request
        )

    def test_create_thread_no_body(self, mock_request):
        self._test_request_error(
            "create_thread",
329
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
330 331 332 333 334 335 336
            {"title": "foo"},
            mock_request
        )

    def test_create_thread_empty_body(self, mock_request):
        self._test_request_error(
            "create_thread",
337
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
338 339 340 341 342 343 344
            {"body": " ", "title": "foo"},
            mock_request
        )

    def test_update_thread_no_title(self, mock_request):
        self._test_request_error(
            "update_thread",
345
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
346 347 348 349 350 351 352
            {"body": "foo"},
            mock_request
        )

    def test_update_thread_empty_title(self, mock_request):
        self._test_request_error(
            "update_thread",
353
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
354 355 356 357 358 359 360
            {"body": "foo", "title": " "},
            mock_request
        )

    def test_update_thread_no_body(self, mock_request):
        self._test_request_error(
            "update_thread",
361
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
362 363 364 365 366 367 368
            {"title": "foo"},
            mock_request
        )

    def test_update_thread_empty_body(self, mock_request):
        self._test_request_error(
            "update_thread",
369
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
370 371 372 373
            {"body": " ", "title": "foo"},
            mock_request
        )

polesye committed
374 375 376 377 378 379 380 381 382
    def test_update_thread_course_topic(self, mock_request):
        self._setup_mock_request(mock_request)
        response = self.client.post(
            reverse("update_thread", kwargs={"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()}),
            data={"body": "foo", "title": "foo", "commentable_id": "some_topic"}
        )
        self.assertEqual(response.status_code, 200)

    @patch('django_comment_client.base.views.get_discussion_categories_ids', return_value=["test_commentable"])
383 384 385 386 387 388 389 390
    def test_update_thread_wrong_commentable_id(self, mock_get_discussion_id_map, mock_request):
        self._test_request_error(
            "update_thread",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": "foo", "title": "foo", "commentable_id": "wrong_commentable"},
            mock_request
        )

391 392 393
    def test_create_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_comment",
394
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
395 396 397 398 399 400 401
            {},
            mock_request
        )

    def test_create_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_comment",
402
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
403 404 405 406 407 408 409
            {"body": " "},
            mock_request
        )

    def test_create_sub_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment",
410
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
411 412 413 414 415 416 417
            {},
            mock_request
        )

    def test_create_sub_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment",
418
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
419 420 421 422 423 424 425
            {"body": " "},
            mock_request
        )

    def test_update_comment_no_body(self, mock_request):
        self._test_request_error(
            "update_comment",
426
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
427 428 429 430 431 432 433
            {},
            mock_request
        )

    def test_update_comment_empty_body(self, mock_request):
        self._test_request_error(
            "update_comment",
434
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
435 436 437 438
            {"body": " "},
            mock_request
        )

439 440 441 442 443 444 445 446
    def test_update_comment_basic(self, mock_request):
        self._setup_mock_request(mock_request)
        comment_id = "test_comment_id"
        updated_body = "updated body"

        response = self.client.post(
            reverse(
                "update_comment",
447
                kwargs={"course_id": self.course_id.to_deprecated_string(), "comment_id": comment_id}
448 449 450 451 452 453 454 455 456 457 458 459 460 461
            ),
            data={"body": updated_body}
        )

        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}
        )

462 463 464 465 466 467 468
    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):
469
        mock_request.return_value.status_code = 200
470 471 472 473 474 475 476 477 478 479
        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": [],
480
            "closed": is_closed,
481
            "id": "518d4237b023791dca00000d",
482
            "user_id": "1", "username": "robot",
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
            "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,
        })
498
        url = reverse('flag_abuse_for_thread', kwargs={'thread_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
499
        response = self.client.post(url)
500
        assert_true(mock_request.called)
501

502 503
        call_list = [
            (
504
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
505
                {
506 507
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
508
                    'headers': ANY,
509 510 511 512
                    'timeout': 5
                }
            ),
            (
513
                ('put', '{prefix}/threads/518d4237b023791dca00000d/abuse_flag'.format(prefix=CS_PREFIX)),
514 515
                {
                    'data': {'user_id': '1'},
516
                    'params': {'request_id': ANY},
517
                    'headers': ANY,
518 519 520 521
                    'timeout': 5
                }
            ),
            (
522
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
523
                {
524 525
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
526
                    'headers': ANY,
527 528 529 530
                    'timeout': 5
                }
            )
        ]
531

532
        assert_equal(call_list, mock_request.call_args_list)
533 534

        assert_equal(response.status_code, 200)
535

536 537 538 539 540 541 542
    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):
543
        mock_request.return_value.status_code = 200
544 545 546 547 548 549 550 551 552 553
        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": [],
554
            "closed": is_closed,
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
            "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
        })
573
        url = reverse('un_flag_abuse_for_thread', kwargs={'thread_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
574 575 576
        response = self.client.post(url)
        assert_true(mock_request.called)

577 578
        call_list = [
            (
579
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
580
                {
581 582
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
583
                    'headers': ANY,
584 585 586 587
                    'timeout': 5
                }
            ),
            (
588
                ('put', '{prefix}/threads/518d4237b023791dca00000d/abuse_unflag'.format(prefix=CS_PREFIX)),
589 590
                {
                    'data': {'user_id': '1'},
591
                    'params': {'request_id': ANY},
592
                    'headers': ANY,
593 594 595 596
                    'timeout': 5
                }
            ),
            (
597
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
598
                {
599 600
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
601
                    'headers': ANY,
602 603 604 605
                    'timeout': 5
                }
            )
        ]
606

607
        assert_equal(call_list, mock_request.call_args_list)
608 609 610

        assert_equal(response.status_code, 200)

611 612 613 614 615 616 617
    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):
618
        mock_request.return_value.status_code = 200
619 620 621 622 623 624 625 626 627
        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": [],
628
            "closed": is_closed,
629 630 631 632 633 634 635 636 637 638 639 640 641
            "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
        })
642
        url = reverse('flag_abuse_for_comment', kwargs={'comment_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
643 644 645
        response = self.client.post(url)
        assert_true(mock_request.called)

646 647
        call_list = [
            (
648
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
649
                {
650 651
                    'data': None,
                    'params': {'request_id': ANY},
652
                    'headers': ANY,
653 654 655 656
                    'timeout': 5
                }
            ),
            (
657
                ('put', '{prefix}/comments/518d4237b023791dca00000d/abuse_flag'.format(prefix=CS_PREFIX)),
658 659
                {
                    'data': {'user_id': '1'},
660
                    'params': {'request_id': ANY},
661
                    'headers': ANY,
662 663 664 665
                    'timeout': 5
                }
            ),
            (
666
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
667
                {
668 669
                    'data': None,
                    'params': {'request_id': ANY},
670
                    'headers': ANY,
671 672 673 674
                    'timeout': 5
                }
            )
        ]
675

676
        assert_equal(call_list, mock_request.call_args_list)
677 678 679

        assert_equal(response.status_code, 200)

680 681 682 683 684 685 686
    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):
687
        mock_request.return_value.status_code = 200
688 689 690 691 692 693 694 695 696
        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": [],
697
            "closed": is_closed,
698 699 700 701 702 703 704 705 706 707 708 709 710
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "robot",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "comment",
            "endorsed": False
        })
711
        url = reverse('un_flag_abuse_for_comment', kwargs={'comment_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
712 713 714
        response = self.client.post(url)
        assert_true(mock_request.called)

715 716
        call_list = [
            (
717
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
718
                {
719 720
                    'data': None,
                    'params': {'request_id': ANY},
721
                    'headers': ANY,
722 723 724 725
                    'timeout': 5
                }
            ),
            (
726
                ('put', '{prefix}/comments/518d4237b023791dca00000d/abuse_unflag'.format(prefix=CS_PREFIX)),
727 728
                {
                    'data': {'user_id': '1'},
729
                    'params': {'request_id': ANY},
730
                    'headers': ANY,
731 732 733 734
                    'timeout': 5
                }
            ),
            (
735
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
736
                {
737 738
                    'data': None,
                    'params': {'request_id': ANY},
739
                    'headers': ANY,
740 741 742 743
                    'timeout': 5
                }
            )
        ]
744

745
        assert_equal(call_list, mock_request.call_args_list)
746

747
        assert_equal(response.status_code, 200)
748

749

750
@patch("lms.lib.comment_client.utils.requests.request")
751
class ViewPermissionsTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin):
752 753 754 755 756 757 758 759 760 761 762 763 764
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(ViewPermissionsTestCase, self).setUp()
        self.password = "test password"
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create(password=self.password)
        self.moderator = UserFactory.create(password=self.password)
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)
        CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id)
        self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id))

    def test_pin_thread_as_student(self, mock_request):
765
        self._set_mock_request_data(mock_request, {})
766 767
        self.client.login(username=self.student.username, password=self.password)
        response = self.client.post(
768
            reverse("pin_thread", kwargs={"course_id": self.course.id.to_deprecated_string(), "thread_id": "dummy"})
769 770 771 772
        )
        self.assertEqual(response.status_code, 401)

    def test_pin_thread_as_moderator(self, mock_request):
773
        self._set_mock_request_data(mock_request, {})
774 775
        self.client.login(username=self.moderator.username, password=self.password)
        response = self.client.post(
776
            reverse("pin_thread", kwargs={"course_id": self.course.id.to_deprecated_string(), "thread_id": "dummy"})
777 778 779 780
        )
        self.assertEqual(response.status_code, 200)

    def test_un_pin_thread_as_student(self, mock_request):
781
        self._set_mock_request_data(mock_request, {})
782 783
        self.client.login(username=self.student.username, password=self.password)
        response = self.client.post(
784
            reverse("un_pin_thread", kwargs={"course_id": self.course.id.to_deprecated_string(), "thread_id": "dummy"})
785 786 787 788
        )
        self.assertEqual(response.status_code, 401)

    def test_un_pin_thread_as_moderator(self, mock_request):
789
        self._set_mock_request_data(mock_request, {})
790 791
        self.client.login(username=self.moderator.username, password=self.password)
        response = self.client.post(
792
            reverse("un_pin_thread", kwargs={"course_id": self.course.id.to_deprecated_string(), "thread_id": "dummy"})
793 794 795
        )
        self.assertEqual(response.status_code, 200)

796 797 798 799
    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:
800
                return self._create_response_mock(thread_data)
801
            elif "/comments/" in url:
802
                return self._create_response_mock(comment_data)
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
            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(
            reverse("endorse_comment", kwargs={"course_id": self.course.id.to_deprecated_string(), "comment_id": "dummy"})
        )
        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(
            reverse("endorse_comment", kwargs={"course_id": self.course.id.to_deprecated_string(), "comment_id": "dummy"})
        )
        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(
            reverse("endorse_comment", kwargs={"course_id": self.course.id.to_deprecated_string(), "comment_id": "dummy"})
        )
        self.assertEqual(response.status_code, 200)

843

844
class CreateThreadUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin, MockRequestSetupMixin):
845
    def setUp(self):
846 847
        super(CreateThreadUnicodeTestCase, self).setUp()

848 849 850 851 852 853
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

    @patch('lms.lib.comment_client.utils.requests.request')
854 855 856 857
    def _test_unicode_data(self, text, mock_request,):
        """
        Test to make sure unicode data in a thread doesn't break it.
        """
858
        self._set_mock_request_data(mock_request, {})
859
        request = RequestFactory().post("dummy_url", {"thread_type": "discussion", "body": text, "title": text})
860 861
        request.user = self.student
        request.view_name = "create_thread"
862
        response = views.create_thread(request, course_id=self.course.id.to_deprecated_string(), commentable_id="test_commentable")
863 864 865 866 867 868 869

        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)


870
class UpdateThreadUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin, MockRequestSetupMixin):
871
    def setUp(self):
872 873
        super(UpdateThreadUnicodeTestCase, self).setUp()

874 875 876 877 878
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

polesye committed
879
    @patch('django_comment_client.base.views.get_discussion_categories_ids', return_value=["test_commentable"])
880
    @patch('lms.lib.comment_client.utils.requests.request')
881
    def _test_unicode_data(self, text, mock_request, mock_get_discussion_id_map):
882
        self._set_mock_request_data(mock_request, {
883 884 885
            "user_id": str(self.student.id),
            "closed": False,
        })
886
        request = RequestFactory().post("dummy_url", {"body": text, "title": text, "thread_type": "question", "commentable_id": "test_commentable"})
887 888
        request.user = self.student
        request.view_name = "update_thread"
889
        response = views.update_thread(request, course_id=self.course.id.to_deprecated_string(), thread_id="dummy_thread_id")
890 891 892 893 894

        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)
895
        self.assertEqual(mock_request.call_args[1]["data"]["thread_type"], "question")
896
        self.assertEqual(mock_request.call_args[1]["data"]["commentable_id"], "test_commentable")
897 898


899
class CreateCommentUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin, MockRequestSetupMixin):
900
    def setUp(self):
901 902
        super(CreateCommentUnicodeTestCase, self).setUp()

903 904 905 906 907 908 909
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

    @patch('lms.lib.comment_client.utils.requests.request')
    def _test_unicode_data(self, text, mock_request):
910
        self._set_mock_request_data(mock_request, {
911 912
            "closed": False,
        })
913 914 915 916 917 918 919 920 921 922
        # We have to get clever here due to Thread's setters and getters.
        # Patch won't work with it.
        try:
            Thread.commentable_id = Mock()
            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"
            )
923

924 925 926 927 928
            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
929 930


931
class UpdateCommentUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin, MockRequestSetupMixin):
932
    def setUp(self):
933 934
        super(UpdateCommentUnicodeTestCase, self).setUp()

935 936 937 938 939 940 941
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

    @patch('lms.lib.comment_client.utils.requests.request')
    def _test_unicode_data(self, text, mock_request):
942
        self._set_mock_request_data(mock_request, {
943 944 945 946 947 948
            "user_id": str(self.student.id),
            "closed": False,
        })
        request = RequestFactory().post("dummy_url", {"body": text})
        request.user = self.student
        request.view_name = "update_comment"
949
        response = views.update_comment(request, course_id=self.course.id.to_deprecated_string(), comment_id="dummy_comment_id")
950 951 952 953 954 955

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


956
class CreateSubCommentUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin, MockRequestSetupMixin):
957 958 959
    """
    Make sure comments under a response can handle unicode.
    """
960
    def setUp(self):
961 962
        super(CreateSubCommentUnicodeTestCase, self).setUp()

963 964 965 966 967 968 969
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

    @patch('lms.lib.comment_client.utils.requests.request')
    def _test_unicode_data(self, text, mock_request):
970 971 972
        """
        Create a comment with unicode in it.
        """
973
        self._set_mock_request_data(mock_request, {
974 975
            "closed": False,
            "depth": 1,
976
            "thread_id": "test_thread"
977 978 979 980
        })
        request = RequestFactory().post("dummy_url", {"body": text})
        request.user = self.student
        request.view_name = "create_sub_comment"
981 982 983 984 985
        Thread.commentable_id = Mock()
        try:
            response = views.create_sub_comment(
                request, course_id=self.course.id.to_deprecated_string(), comment_id="dummy_comment_id"
            )
986

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 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 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            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


class ForumEventTestCase(ModuleStoreTestCase, MockRequestSetupMixin):
    """
    Forum actions are expected to launch analytics events. Test these here.
    """
    def setUp(self):
        super(ForumEventTestCase, self).setUp()
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)
        self.student.roles.add(Role.objects.get(name="Student", course_id=self.course.id))
        CourseAccessRoleFactory(course_id=self.course.id, user=self.student, role='Wizard')

    @patch('eventtracking.tracker.emit')
    @patch('lms.lib.comment_client.utils.requests.request')
    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"

        views.create_thread(request, course_id=self.course.id.to_deprecated_string(), commentable_id="test_commentable")

        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')
    @patch('lms.lib.comment_client.utils.requests.request')
    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"
        views.create_comment(request, course_id=self.course.id.to_deprecated_string(), thread_id='test_thread_id')

        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')
    @patch('lms.lib.comment_client.utils.requests.request')
    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"
        views.create_sub_comment(
            request, course_id=self.course.id.to_deprecated_string(), comment_id="dummy_comment_id"
        )

        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)
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103


class UsersEndpointTestCase(ModuleStoreTestCase, MockRequestSetupMixin):

    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 setUp(self):
1104 1105
        super(UsersEndpointTestCase, self).setUp()

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        self.course = CourseFactory.create()
        seed_permissions_roles(self.course.id)
        self.student = UserFactory.create()
        self.enrollment = CourseEnrollmentFactory(user=self.student, course_id=self.course.id)
        self.other_user = UserFactory.create(username="other")
        CourseEnrollmentFactory(user=self.other_user, course_id=self.course.id)

    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())

    @patch('lms.lib.comment_client.utils.requests.request')
    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}]
        )

    @patch('lms.lib.comment_client.utils.requests.request')
    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):
        course_id = SlashSeparatedCourseKey.from_deprecated_string("does/not/exist")
        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)
1164 1165
        self.assertIn("errors", content)
        self.assertNotIn("users", content)
1166 1167 1168 1169 1170 1171 1172

    @patch('lms.lib.comment_client.utils.requests.request')
    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"], [])