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

4
import ddt
5
from django.core import cache
6
from django.core.urlresolvers import reverse
7
from django.http import Http404
8
from django.test.client import Client, RequestFactory
9
from django.test.utils import override_settings
10
from edxmako.tests import mako_middleware_process_request
11 12

from django_comment_client.forum import views
13 14 15 16
from django_comment_client.tests.group_id import (
    CohortedTopicGroupIdTestMixin,
    NonCohortedTopicGroupIdTestMixin
)
17
from django_comment_client.tests.unicode import UnicodeTestMixin
18
from django_comment_client.tests.utils import CohortedTestCase
19
from django_comment_client.utils import strip_none
20 21
from student.tests.factories import UserFactory, CourseEnrollmentFactory
from util.testing import UrlResetMixin
22
from openedx.core.djangoapps.util.testing import ContentGroupTestCase
23 24 25 26 27 28 29
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import (
    ModuleStoreTestCase,
    TEST_DATA_MONGO_MODULESTORE
)
from xmodule.modulestore.tests.factories import check_mongo_calls, CourseFactory, ItemFactory
muhammad-ammar committed
30

31 32 33 34 35 36
from courseware.courses import UserNotEnrolled
from nose.tools import assert_true  # pylint: disable=E0611
from mock import patch, Mock, ANY, call

from openedx.core.djangoapps.course_groups.models import CourseUserGroup

37 38
log = logging.getLogger(__name__)

39
# pylint: disable=missing-docstring
muhammad-ammar committed
40

41

42 43
class ViewsExceptionTestCase(UrlResetMixin, ModuleStoreTestCase):

44
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    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)
        super(ViewsExceptionTestCase, self).setUp()

        # create a course
        self.course = CourseFactory.create(org='MITx', course='999',
                                           display_name='Robot Super Course')

        # 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 student
            self.student = UserFactory(username=uname, password=password, email=email)

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

            # Log the student in
            self.client = Client()
            assert_true(self.client.login(username=uname, password=password))

    @patch('student.models.cc.User.from_django_user')
    @patch('student.models.cc.User.active_threads')
    def test_user_profile_exception(self, mock_threads, mock_from_django_user):

        # Mock the code that makes the HTTP requests to the cs_comment_service app
        # for the profiled user's active threads
        mock_threads.return_value = [], 1, 1

        # Mock the code that makes the HTTP request to the cs_comment_service app
        # that gets the current user's info
        mock_from_django_user.return_value = Mock()

        url = reverse('django_comment_client.forum.views.user_profile',
86
                      kwargs={'course_id': self.course.id.to_deprecated_string(), 'user_id': '12345'})  # There is no user 12345
87 88 89 90
        self.response = self.client.get(url)
        self.assertEqual(self.response.status_code, 404)

    @patch('student.models.cc.User.from_django_user')
91
    @patch('student.models.cc.User.subscribed_threads')
92 93 94 95 96 97 98 99 100 101 102
    def test_user_followed_threads_exception(self, mock_threads, mock_from_django_user):

        # Mock the code that makes the HTTP requests to the cs_comment_service app
        # for the profiled user's active threads
        mock_threads.return_value = [], 1, 1

        # Mock the code that makes the HTTP request to the cs_comment_service app
        # that gets the current user's info
        mock_from_django_user.return_value = Mock()

        url = reverse('django_comment_client.forum.views.followed_threads',
103
                      kwargs={'course_id': self.course.id.to_deprecated_string(), 'user_id': '12345'})  # There is no user 12345
104 105
        self.response = self.client.get(url)
        self.assertEqual(self.response.status_code, 404)
106 107


108 109 110
def make_mock_thread_data(
        course, text, thread_id, num_children, include_children, group_id=None, group_name=None, commentable_id=None
):
111 112 113 114 115
    thread_data = {
        "id": thread_id,
        "type": "thread",
        "title": text,
        "body": text,
116 117 118
        "commentable_id": (
            commentable_id or course.discussion_topics.get('General', {}).get('id') or "dummy_commentable_id"
        ),
119 120 121
        "resp_total": 42,
        "resp_skip": 25,
        "resp_limit": 5,
122
        "group_id": group_id
123
    }
124 125
    if group_id is not None:
        thread_data['group_name'] = group_name
126
    if num_children is not None:
127 128 129
        thread_data['group_id'] = group_id
        thread_data['group_name'] = group_name
    if include_children:
130
        thread_data["children"] = [{
131
            "id": "dummy_comment_id_{}".format(i),
132 133
            "type": "comment",
            "body": text,
134
        } for i in range(num_children)]
135 136 137
    return thread_data


138
def make_mock_request_impl(
139 140 141 142 143 144
        course,
        text,
        thread_id="dummy_thread_id",
        group_id=None,
        commentable_id=None,
        num_thread_responses=1
145
):
146 147
    def mock_request_impl(*args, **kwargs):
        url = args[1]
148
        data = None
149
        if url.endswith("threads") or url.endswith("user_profile"):
150
            data = {
151 152 153 154 155 156 157
                "collection": [
                    make_mock_thread_data(
                        course=course,
                        text=text,
                        thread_id=thread_id,
                        num_children=None,
                        group_id=group_id,
158 159
                        commentable_id=commentable_id,
                        include_children=False
160 161
                    )
                ]
162
            }
163
        elif thread_id and url.endswith(thread_id):
164 165 166 167 168
            data = {
                "collection": [make_mock_thread_data(course=course, text=text, thread_id=thread_id,
                                                     num_children=num_thread_responses, include_children=False,
                                                     group_id=group_id)]
            }
169
        elif "/users/" in url:
170
            data = {
171
                "default_sort_key": "date",
172 173 174 175
                "upvoted_ids": [],
                "downvoted_ids": [],
                "subscribed_thread_ids": [],
            }
176 177 178 179 180 181
            # comments service adds these attributes when course_id param is present
            if kwargs.get('params', {}).get('course_id'):
                data.update({
                    "threads_count": 1,
                    "comments_count": 2
                })
182 183 184
        if data:
            return Mock(status_code=200, text=json.dumps(data), json=Mock(return_value=data))
        return Mock(status_code=404)
185 186 187
    return mock_request_impl


188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
class StringEndsWithMatcher(object):
    def __init__(self, suffix):
        self.suffix = suffix

    def __eq__(self, other):
        return other.endswith(self.suffix)


class PartialDictMatcher(object):
    def __init__(self, expected_values):
        self.expected_values = expected_values

    def __eq__(self, other):
        return all([
            key in other and other[key] == value
            for key, value in self.expected_values.iteritems()
        ])


@patch('requests.request')
class SingleThreadTestCase(ModuleStoreTestCase):
    def setUp(self):
210 211
        super(SingleThreadTestCase, self).setUp(create_user=False)

212
        self.course = CourseFactory.create(discussion_topics={'dummy discussion': {'id': 'dummy_discussion_id'}})
213 214 215 216 217 218
        self.student = UserFactory.create()
        CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id)

    def test_ajax(self, mock_request):
        text = "dummy content"
        thread_id = "test_thread_id"
219
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text, thread_id=thread_id)
220 221 222 223 224 225 226 227

        request = RequestFactory().get(
            "dummy_url",
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = self.student
        response = views.single_thread(
            request,
228
            self.course.id.to_deprecated_string(),
229 230 231 232 233 234
            "dummy_discussion_id",
            "test_thread_id"
        )

        self.assertEquals(response.status_code, 200)
        response_data = json.loads(response.content)
235 236
        # strip_none is being used to perform the same transform that the
        # django view performs prior to writing thread data to the response
237 238
        self.assertEquals(
            response_data["content"],
239 240 241
            strip_none(make_mock_thread_data(
                course=self.course, text=text, thread_id=thread_id, num_children=1, include_children=False
            ))
242 243 244
        )
        mock_request.assert_called_with(
            "get",
Sarina Canelake committed
245
            StringEndsWithMatcher(thread_id),  # url
246 247 248 249 250 251 252 253 254 255 256
            data=None,
            params=PartialDictMatcher({"mark_as_read": True, "user_id": 1, "recursive": True}),
            headers=ANY,
            timeout=ANY
        )

    def test_skip_limit(self, mock_request):
        text = "dummy content"
        thread_id = "test_thread_id"
        response_skip = "45"
        response_limit = "15"
257
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text, thread_id=thread_id)
258 259 260 261 262 263 264 265 266

        request = RequestFactory().get(
            "dummy_url",
            {"resp_skip": response_skip, "resp_limit": response_limit},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = self.student
        response = views.single_thread(
            request,
267
            self.course.id.to_deprecated_string(),
268 269 270 271 272
            "dummy_discussion_id",
            "test_thread_id"
        )
        self.assertEquals(response.status_code, 200)
        response_data = json.loads(response.content)
273 274
        # strip_none is being used to perform the same transform that the
        # django view performs prior to writing thread data to the response
275 276
        self.assertEquals(
            response_data["content"],
277
            strip_none(make_mock_thread_data(course=self.course, text=text, thread_id=thread_id, num_children=1))
278 279 280
        )
        mock_request.assert_called_with(
            "get",
Sarina Canelake committed
281
            StringEndsWithMatcher(thread_id),  # url
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            data=None,
            params=PartialDictMatcher({
                "mark_as_read": True,
                "user_id": 1,
                "recursive": True,
                "resp_skip": response_skip,
                "resp_limit": response_limit,
            }),
            headers=ANY,
            timeout=ANY
        )

    def test_post(self, mock_request):
        request = RequestFactory().post("dummy_url")
        response = views.single_thread(
            request,
298
            self.course.id.to_deprecated_string(),
299 300 301 302 303
            "dummy_discussion_id",
            "dummy_thread_id"
        )
        self.assertEquals(response.status_code, 405)

304 305 306 307
    def test_not_found(self, mock_request):
        request = RequestFactory().get("dummy_url")
        request.user = self.student
        # Mock request to return 404 for thread request
308
        mock_request.side_effect = make_mock_request_impl(course=self.course, text="dummy", thread_id=None)
309 310 311 312
        self.assertRaises(
            Http404,
            views.single_thread,
            request,
313
            self.course.id.to_deprecated_string(),
314 315 316 317
            "test_discussion_id",
            "test_thread_id"
        )

318

319 320 321 322
@ddt.ddt
@patch('requests.request')
class SingleThreadQueryCountTestCase(ModuleStoreTestCase):
    """
323 324
    Ensures the number of modulestore queries and number of sql queries are
    independent of the number of responses retrieved for a given discussion thread.
325
    """
326
    MODULESTORE = TEST_DATA_MONGO_MODULESTORE
327 328

    @ddt.data(
329 330 331
        # old mongo with cache
        (ModuleStoreEnum.Type.mongo, 1, 7, 5, 12, 7),
        (ModuleStoreEnum.Type.mongo, 50, 7, 5, 12, 7),
332
        # split mongo: 3 queries, regardless of thread response size.
333 334
        (ModuleStoreEnum.Type.split, 1, 3, 3, 12, 7),
        (ModuleStoreEnum.Type.split, 50, 3, 3, 12, 7),
335 336
    )
    @ddt.unpack
337 338 339 340 341 342
    def test_number_of_mongo_queries(
            self,
            default_store,
            num_thread_responses,
            num_uncached_mongo_calls,
            num_cached_mongo_calls,
Usman Khalid committed
343 344
            num_uncached_sql_queries,
            num_cached_sql_queries,
345 346
            mock_request
    ):
347
        with modulestore().default_store(default_store):
348
            course = CourseFactory.create(discussion_topics={'dummy discussion': {'id': 'dummy_discussion_id'}})
349 350 351 352 353 354

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

        test_thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(
355
            course=course, text="dummy content", thread_id=test_thread_id, num_thread_responses=num_thread_responses
356 357 358 359 360 361
        )
        request = RequestFactory().get(
            "dummy_url",
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = student
362 363 364 365 366

        def call_single_thread():
            """
            Call single_thread and assert that it returns what we expect.
            """
367 368 369 370 371 372 373 374 375
            response = views.single_thread(
                request,
                course.id.to_deprecated_string(),
                "dummy_discussion_id",
                test_thread_id
            )
            self.assertEquals(response.status_code, 200)
            self.assertEquals(len(json.loads(response.content)["content"]["children"]), num_thread_responses)

376
        # Test uncached first, then cached now that the cache is warm.
Usman Khalid committed
377
        cached_calls = [
378 379
            [num_uncached_mongo_calls, num_uncached_sql_queries],
            [num_cached_mongo_calls, num_cached_sql_queries],
Usman Khalid committed
380
        ]
381 382 383 384
        for expected_mongo_calls, expected_sql_queries in cached_calls:
            with self.assertNumQueries(expected_sql_queries):
                with check_mongo_calls(expected_mongo_calls):
                    call_single_thread()
385

386

387
@patch('requests.request')
388
class SingleCohortedThreadTestCase(CohortedTestCase):
389 390 391 392
    def _create_mock_cohorted_thread(self, mock_request):
        self.mock_text = "dummy content"
        self.mock_thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(
393
            course=self.course, text=self.mock_text, thread_id=self.mock_thread_id, group_id=self.student_cohort.id
394 395 396 397 398 399 400 401 402 403 404 405 406
        )

    def test_ajax(self, mock_request):
        self._create_mock_cohorted_thread(mock_request)

        request = RequestFactory().get(
            "dummy_url",
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = self.student
        response = views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
407
            "cohorted_topic",
408 409 410 411 412 413 414 415
            self.mock_thread_id
        )

        self.assertEquals(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEquals(
            response_data["content"],
            make_mock_thread_data(
416 417 418 419
                course=self.course,
                text=self.mock_text,
                thread_id=self.mock_thread_id,
                num_children=1,
420
                group_id=self.student_cohort.id,
421 422
                group_name=self.student_cohort.name,
                include_children=False,
423 424 425 426 427 428 429 430 431 432 433 434
            )
        )

    def test_html(self, mock_request):
        self._create_mock_cohorted_thread(mock_request)

        request = RequestFactory().get("dummy_url")
        request.user = self.student
        mako_middleware_process_request(request)
        response = views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
435
            "cohorted_topic",
436 437 438 439 440 441 442 443 444 445 446
            self.mock_thread_id
        )

        self.assertEquals(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
        html = response.content

        # Verify that the group name is correctly included in the HTML
        self.assertRegexpMatches(html, r'"group_name": "student_cohort"')


447
@patch('lms.lib.comment_client.utils.requests.request')
448
class SingleThreadAccessTestCase(CohortedTestCase):
449 450
    def call_view(self, mock_request, commentable_id, user, group_id, thread_group_id=None, pass_group_id=True):
        thread_id = "test_thread_id"
451 452 453
        mock_request.side_effect = make_mock_request_impl(
            course=self.course, text="dummy context", thread_id=thread_id, group_id=thread_group_id
        )
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().get(
            "dummy_url",
            data=request_data,
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = user
        return views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
            commentable_id,
            thread_id
        )

    def test_student_non_cohorted(self, mock_request):
        resp = self.call_view(mock_request, "non_cohorted_topic", self.student, self.student_cohort.id)
        self.assertEqual(resp.status_code, 200)

    def test_student_same_cohort(self, mock_request):
        resp = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            thread_group_id=self.student_cohort.id
        )
        self.assertEqual(resp.status_code, 200)

485 486 487 488 489 490 491 492 493 494 495 496
    # this test ensures that a thread response from the cs with group_id: null
    # behaves the same as a thread response without a group_id (see: TNL-444)
    def test_student_global_thread_in_cohorted_topic(self, mock_request):
        resp = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            thread_group_id=None
        )
        self.assertEqual(resp.status_code, 200)

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    def test_student_different_cohort(self, mock_request):
        self.assertRaises(
            Http404,
            lambda: self.call_view(
                mock_request,
                "cohorted_topic",
                self.student,
                self.student_cohort.id,
                thread_group_id=self.moderator_cohort.id
            )
        )

    def test_moderator_non_cohorted(self, mock_request):
        resp = self.call_view(mock_request, "non_cohorted_topic", self.moderator, self.moderator_cohort.id)
        self.assertEqual(resp.status_code, 200)

    def test_moderator_same_cohort(self, mock_request):
        resp = self.call_view(
            mock_request,
            "cohorted_topic",
            self.moderator,
            self.moderator_cohort.id,
            thread_group_id=self.moderator_cohort.id
        )
        self.assertEqual(resp.status_code, 200)

    def test_moderator_different_cohort(self, mock_request):
        resp = self.call_view(
            mock_request,
            "cohorted_topic",
            self.moderator,
            self.moderator_cohort.id,
            thread_group_id=self.student_cohort.id
        )
        self.assertEqual(resp.status_code, 200)


@patch('lms.lib.comment_client.utils.requests.request')
535
class SingleThreadGroupIdTestCase(CohortedTestCase, CohortedTopicGroupIdTestMixin):
536 537
    cs_endpoint = "/threads"

538
    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True, is_ajax=False):
539 540 541
        mock_request.side_effect = make_mock_request_impl(
            course=self.course, text="dummy context", group_id=self.student_cohort.id
        )
542 543 544 545

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
546 547 548
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
549 550
        request = RequestFactory().get(
            "dummy_url",
551 552
            data=request_data,
            **headers
553 554 555 556 557 558
        )
        request.user = user
        mako_middleware_process_request(request)
        return views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
559
            commentable_id,
560 561 562
            "dummy_thread_id"
        )

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    def test_group_info_in_html_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            is_ajax=False
        )
        self._assert_html_response_contains_group_info(response)

    def test_group_info_in_ajax_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            is_ajax=True
        )
        self._assert_json_response_contains_group_info(
            response, lambda d: d['content']
        )

585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
@patch('requests.request')
class SingleThreadContentGroupTestCase(ContentGroupTestCase):
    def assert_can_access(self, user, discussion_id, thread_id, should_have_access):
        """
        Verify that a user has access to a thread within a given
        discussion_id when should_have_access is True, otherwise
        verify that the user does not have access to that thread.
        """
        request = RequestFactory().get("dummy_url")
        request.user = user
        mako_middleware_process_request(request)

        def call_single_thread():
            return views.single_thread(
                request,
                unicode(self.course.id),
                discussion_id,
                thread_id
            )

        if should_have_access:
            self.assertEqual(call_single_thread().status_code, 200)
        else:
            with self.assertRaises(Http404):
                call_single_thread()

    def test_staff_user(self, mock_request):
        """
        Verify that the staff user can access threads in the alpha,
        beta, and global discussion modules.
        """
        thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(course=self.course, text="dummy content", thread_id=thread_id)

        for discussion_module in [self.alpha_module, self.beta_module, self.global_module]:
            self.assert_can_access(self.staff_user, discussion_module.discussion_id, thread_id, True)

    def test_alpha_user(self, mock_request):
        """
        Verify that the alpha user can access threads in the alpha and
        global discussion modules.
        """
        thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(course=self.course, text="dummy content", thread_id=thread_id)

        for discussion_module in [self.alpha_module, self.global_module]:
            self.assert_can_access(self.alpha_user, discussion_module.discussion_id, thread_id, True)

        self.assert_can_access(self.alpha_user, self.beta_module.discussion_id, thread_id, False)

    def test_beta_user(self, mock_request):
        """
        Verify that the beta user can access threads in the beta and
        global discussion modules.
        """
        thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(course=self.course, text="dummy content", thread_id=thread_id)

        for discussion_module in [self.beta_module, self.global_module]:
            self.assert_can_access(self.beta_user, discussion_module.discussion_id, thread_id, True)

        self.assert_can_access(self.beta_user, self.alpha_module.discussion_id, thread_id, False)

    def test_non_cohorted_user(self, mock_request):
        """
        Verify that the non-cohorted user can access threads in just the
        global discussion module.
        """
        thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(course=self.course, text="dummy content", thread_id=thread_id)

        self.assert_can_access(self.non_cohorted_user, self.global_module.discussion_id, thread_id, True)

        self.assert_can_access(self.non_cohorted_user, self.alpha_module.discussion_id, thread_id, False)

        self.assert_can_access(self.non_cohorted_user, self.beta_module.discussion_id, thread_id, False)


664 665
@patch('lms.lib.comment_client.utils.requests.request')
class InlineDiscussionGroupIdTestCase(
666
        CohortedTestCase,
667 668 669 670 671
        CohortedTopicGroupIdTestMixin,
        NonCohortedTopicGroupIdTestMixin
):
    cs_endpoint = "/threads"

672 673 674 675
    def setUp(self):
        super(InlineDiscussionGroupIdTestCase, self).setUp()
        self.cohorted_commentable_id = 'cohorted_topic'

676
    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True):
677
        kwargs = {'commentable_id': self.cohorted_commentable_id}
678 679 680 681 682 683 684 685 686
        if group_id:
            # avoid causing a server error when the LMS chokes attempting
            # to find a group name for the group_id, when we're testing with
            # an invalid one.
            try:
                CourseUserGroup.objects.get(id=group_id)
                kwargs['group_id'] = group_id
            except CourseUserGroup.DoesNotExist:
                pass
687
        mock_request.side_effect = make_mock_request_impl(self.course, "dummy content", **kwargs)
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().get(
            "dummy_url",
            data=request_data
        )
        request.user = user
        return views.inline_discussion(
            request,
            self.course.id.to_deprecated_string(),
            commentable_id
        )

703 704 705
    def test_group_info_in_ajax_response(self, mock_request):
        response = self.call_view(
            mock_request,
706
            self.cohorted_commentable_id,
707 708 709 710 711 712 713
            self.student,
            self.student_cohort.id
        )
        self._assert_json_response_contains_group_info(
            response, lambda d: d['discussion_data'][0]
        )

714 715

@patch('lms.lib.comment_client.utils.requests.request')
716
class ForumFormDiscussionGroupIdTestCase(CohortedTestCase, CohortedTopicGroupIdTestMixin):
717 718
    cs_endpoint = "/threads"

719 720 721 722
    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True, is_ajax=False):
        kwargs = {}
        if group_id:
            kwargs['group_id'] = group_id
723
        mock_request.side_effect = make_mock_request_impl(self.course, "dummy content", **kwargs)
724 725 726 727

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
728 729 730
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
731 732
        request = RequestFactory().get(
            "dummy_url",
733 734
            data=request_data,
            **headers
735 736 737 738 739 740 741 742
        )
        request.user = user
        mako_middleware_process_request(request)
        return views.forum_form_discussion(
            request,
            self.course.id.to_deprecated_string()
        )

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    def test_group_info_in_html_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id
        )
        self._assert_html_response_contains_group_info(response)

    def test_group_info_in_ajax_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            is_ajax=True
        )
        self._assert_json_response_contains_group_info(
            response, lambda d: d['discussion_data'][0]
        )
763

764

765
@patch('lms.lib.comment_client.utils.requests.request')
766
class UserProfileDiscussionGroupIdTestCase(CohortedTestCase, CohortedTopicGroupIdTestMixin):
767 768
    cs_endpoint = "/active_threads"

769 770 771 772 773 774 775
    def call_view_for_profiled_user(
            self, mock_request, requesting_user, profiled_user, group_id, pass_group_id, is_ajax=False
    ):
        """
        Calls "user_profile" view method on behalf of "requesting_user" to get information about
        the user "profiled_user".
        """
776 777 778
        kwargs = {}
        if group_id:
            kwargs['group_id'] = group_id
779
        mock_request.side_effect = make_mock_request_impl(self.course, "dummy content", **kwargs)
780 781 782 783

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
784 785 786
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
787 788
        request = RequestFactory().get(
            "dummy_url",
789 790
            data=request_data,
            **headers
791
        )
792
        request.user = requesting_user
793 794 795 796
        mako_middleware_process_request(request)
        return views.user_profile(
            request,
            self.course.id.to_deprecated_string(),
797 798 799 800 801 802
            profiled_user.id
        )

    def call_view(self, mock_request, _commentable_id, user, group_id, pass_group_id=True, is_ajax=False):
        return self.call_view_for_profiled_user(
            mock_request, user, user, group_id, pass_group_id=pass_group_id, is_ajax=is_ajax
803 804
        )

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
    def test_group_info_in_html_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            is_ajax=False
        )
        self._assert_html_response_contains_group_info(response)

    def test_group_info_in_ajax_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id,
            is_ajax=True
        )
        self._assert_json_response_contains_group_info(
            response, lambda d: d['discussion_data'][0]
        )

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
    def _test_group_id_passed_to_user_profile(
            self, mock_request, expect_group_id_in_request, requesting_user, profiled_user, group_id, pass_group_id
    ):
        """
        Helper method for testing whether or not group_id was passed to the user_profile request.
        """

        def get_params_from_user_info_call(for_specific_course):
            """
            Returns the request parameters for the user info call with either course_id specified or not,
            depending on value of 'for_specific_course'.
            """
            # There will be 3 calls from user_profile. One has the cs_endpoint "active_threads", and it is already
            # tested. The other 2 calls are for user info; one of those calls is for general information about the user,
            # and it does not specify a course_id. The other call does specify a course_id, and if the caller did not
            # have discussion moderator privileges, it should also contain a group_id.
            for r_call in mock_request.call_args_list:
                if not r_call[0][1].endswith(self.cs_endpoint):
                    params = r_call[1]["params"]
                    has_course_id = "course_id" in params
                    if (for_specific_course and has_course_id) or (not for_specific_course and not has_course_id):
                        return params
            self.assertTrue(
                False,
                "Did not find appropriate user_profile call for 'for_specific_course'=" + for_specific_course
            )

        mock_request.reset_mock()
        self.call_view_for_profiled_user(
            mock_request,
            requesting_user,
            profiled_user,
            group_id,
            pass_group_id=pass_group_id,
            is_ajax=False
        )
        # Should never have a group_id if course_id was not included in the request.
        params_without_course_id = get_params_from_user_info_call(False)
        self.assertNotIn("group_id", params_without_course_id)

        params_with_course_id = get_params_from_user_info_call(True)
        if expect_group_id_in_request:
            self.assertIn("group_id", params_with_course_id)
            self.assertEqual(group_id, params_with_course_id["group_id"])
        else:
            self.assertNotIn("group_id", params_with_course_id)

    def test_group_id_passed_to_user_profile_student(self, mock_request):
        """
        Test that the group id is always included when requesting user profile information for a particular
        course if the requester does not have discussion moderation privileges.
        """
        def verify_group_id_always_present(profiled_user, pass_group_id):
            """
            Helper method to verify that group_id is always present for student in course
            (non-privileged user).
            """
            self._test_group_id_passed_to_user_profile(
                mock_request, True, self.student, profiled_user, self.student_cohort.id, pass_group_id
            )

        # In all these test cases, the requesting_user is the student (non-privileged user).
        # The profile returned on behalf of the student is for the profiled_user.
        verify_group_id_always_present(profiled_user=self.student, pass_group_id=True)
        verify_group_id_always_present(profiled_user=self.student, pass_group_id=False)
        verify_group_id_always_present(profiled_user=self.moderator, pass_group_id=True)
        verify_group_id_always_present(profiled_user=self.moderator, pass_group_id=False)

    def test_group_id_user_profile_moderator(self, mock_request):
        """
        Test that the group id is only included when a privileged user requests user profile information for a
        particular course and user if the group_id is explicitly passed in.
        """
        def verify_group_id_present(profiled_user, pass_group_id, requested_cohort=self.moderator_cohort):
            """
            Helper method to verify that group_id is present.
            """
            self._test_group_id_passed_to_user_profile(
                mock_request, True, self.moderator, profiled_user, requested_cohort.id, pass_group_id
            )

        def verify_group_id_not_present(profiled_user, pass_group_id, requested_cohort=self.moderator_cohort):
            """
            Helper method to verify that group_id is not present.
            """
            self._test_group_id_passed_to_user_profile(
                mock_request, False, self.moderator, profiled_user, requested_cohort.id, pass_group_id
            )

        # In all these test cases, the requesting_user is the moderator (privileged user).

        # If the group_id is explicitly passed, it will be present in the request.
        verify_group_id_present(profiled_user=self.student, pass_group_id=True)
        verify_group_id_present(profiled_user=self.moderator, pass_group_id=True)
        verify_group_id_present(
            profiled_user=self.student, pass_group_id=True, requested_cohort=self.student_cohort
        )

        # If the group_id is not explicitly passed, it will not be present because the requesting_user
        # has discussion moderator privileges.
        verify_group_id_not_present(profiled_user=self.student, pass_group_id=False)
        verify_group_id_not_present(profiled_user=self.moderator, pass_group_id=False)

930 931

@patch('lms.lib.comment_client.utils.requests.request')
932
class FollowedThreadsDiscussionGroupIdTestCase(CohortedTestCase, CohortedTopicGroupIdTestMixin):
933 934 935
    cs_endpoint = "/subscribed_threads"

    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True):
936 937 938
        kwargs = {}
        if group_id:
            kwargs['group_id'] = group_id
939
        mock_request.side_effect = make_mock_request_impl(self.course, "dummy content", **kwargs)
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().get(
            "dummy_url",
            data=request_data,
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = user
        return views.followed_threads(
            request,
            self.course.id.to_deprecated_string(),
            user.id
        )

956 957 958 959 960 961 962 963 964 965 966
    def test_group_info_in_ajax_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            self.student_cohort.id
        )
        self._assert_json_response_contains_group_info(
            response, lambda d: d['discussion_data'][0]
        )

967

968 969
class InlineDiscussionTestCase(ModuleStoreTestCase):
    def setUp(self):
970 971
        super(InlineDiscussionTestCase, self).setUp()

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
        self.course = CourseFactory.create(org="TestX", number="101", display_name="Test Course")
        self.student = UserFactory.create()
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)
        self.discussion1 = ItemFactory.create(
            parent_location=self.course.location,
            category="discussion",
            discussion_id="discussion1",
            display_name='Discussion1',
            discussion_category="Chapter",
            discussion_target="Discussion1"
        )

    @patch('lms.lib.comment_client.utils.requests.request')
    def test_courseware_data(self, mock_request):
        request = RequestFactory().get("dummy_url")
        request.user = self.student
988 989 990
        mock_request.side_effect = make_mock_request_impl(
            course=self.course, text="dummy content", commentable_id=self.discussion1.discussion_id
        )
991

992 993 994
        response = views.inline_discussion(
            request, self.course.id.to_deprecated_string(), self.discussion1.discussion_id
        )
995 996 997 998 999 1000 1001 1002
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        expected_courseware_url = '/courses/TestX/101/Test_Course/jump_to/i4x://TestX/101/discussion/Discussion1'
        expected_courseware_title = 'Chapter / Discussion1'
        self.assertEqual(response_data['discussion_data'][0]['courseware_url'], expected_courseware_url)
        self.assertEqual(response_data["discussion_data"][0]["courseware_title"], expected_courseware_title)


1003
@patch('requests.request')
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
class SingleCohortedThreadTestCase(ModuleStoreTestCase):
    def setUp(self):
        self.course = CourseFactory.create()
        self.student = UserFactory.create()
        CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id)
        self.student_cohort = CourseUserGroup.objects.create(
            name="student_cohort",
            course_id=self.course.id,
            group_type=CourseUserGroup.COHORT
        )

    def _create_mock_cohorted_thread(self, mock_request):
        self.mock_text = "dummy content"
        self.mock_thread_id = "test_thread_id"
        mock_request.side_effect = make_mock_request_impl(
            self.mock_text, self.mock_thread_id,
            group_id=self.student_cohort.id
        )

    def test_ajax(self, mock_request):
        self._create_mock_cohorted_thread(mock_request)

        request = RequestFactory().get(
            "dummy_url",
            HTTP_X_REQUESTED_WITH="XMLHttpRequest"
        )
        request.user = self.student
        response = views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
            "dummy_discussion_id",
            self.mock_thread_id
        )

        self.assertEquals(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEquals(
            response_data["content"],
            make_mock_thread_data(
                self.course,
                self.mock_text, self.mock_thread_id, 1, True,
                group_id=self.student_cohort.id,
                group_name=self.student_cohort.name,
            )
        )

    def test_html(self, mock_request):
        self._create_mock_cohorted_thread(mock_request)

        request = RequestFactory().get("dummy_url")
        request.user = self.student
        mako_middleware_process_request(request)
        response = views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
            "dummy_discussion_id",
            self.mock_thread_id
        )

        self.assertEquals(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
        html = response.content

        # Verify that the group name is correctly included in the HTML
        self.assertRegexpMatches(html, r'"group_name": "student_cohort"')


@patch('requests.request')
1072 1073 1074 1075 1076 1077
class UserProfileTestCase(ModuleStoreTestCase):

    TEST_THREAD_TEXT = 'userprofile-test-text'
    TEST_THREAD_ID = 'userprofile-test-thread-id'

    def setUp(self):
1078 1079
        super(UserProfileTestCase, self).setUp()

1080 1081 1082 1083 1084 1085
        self.course = CourseFactory.create()
        self.student = UserFactory.create()
        self.profiled_user = UserFactory.create()
        CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id)

    def get_response(self, mock_request, params, **headers):
1086 1087 1088
        mock_request.side_effect = make_mock_request_impl(
            course=self.course, text=self.TEST_THREAD_TEXT, thread_id=self.TEST_THREAD_ID
        )
1089 1090
        request = RequestFactory().get("dummy_url", data=params, **headers)
        request.user = self.student
1091 1092

        mako_middleware_process_request(request)
1093 1094
        response = views.user_profile(
            request,
1095
            self.course.id.to_deprecated_string(),
1096 1097 1098 1099 1100 1101 1102
            self.profiled_user.id
        )
        mock_request.assert_any_call(
            "get",
            StringEndsWithMatcher('/users/{}/active_threads'.format(self.profiled_user.id)),
            data=None,
            params=PartialDictMatcher({
1103
                "course_id": self.course.id.to_deprecated_string(),
1104 1105
                "page": params.get("page", 1),
                "per_page": views.THREADS_PER_PAGE
Sarina Canelake committed
1106
            }),
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
            headers=ANY,
            timeout=ANY
        )
        return response

    def check_html(self, mock_request, **params):
        response = self.get_response(mock_request, params)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
        html = response.content
1117 1118
        self.assertRegexpMatches(html, r'data-page="1"')
        self.assertRegexpMatches(html, r'data-num-pages="1"')
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        self.assertRegexpMatches(html, r'<span>1</span> discussion started')
        self.assertRegexpMatches(html, r'<span>2</span> comments')
        self.assertRegexpMatches(html, r'&quot;id&quot;: &quot;{}&quot;'.format(self.TEST_THREAD_ID))
        self.assertRegexpMatches(html, r'&quot;title&quot;: &quot;{}&quot;'.format(self.TEST_THREAD_TEXT))
        self.assertRegexpMatches(html, r'&quot;body&quot;: &quot;{}&quot;'.format(self.TEST_THREAD_TEXT))
        self.assertRegexpMatches(html, r'&quot;username&quot;: &quot;{}&quot;'.format(self.student.username))

    def check_ajax(self, mock_request, **params):
        response = self.get_response(mock_request, params, HTTP_X_REQUESTED_WITH="XMLHttpRequest")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json; charset=utf-8')
        response_data = json.loads(response.content)
        self.assertEqual(
            sorted(response_data.keys()),
            ["annotated_content_info", "discussion_data", "num_pages", "page"]
Sarina Canelake committed
1134
        )
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        self.assertEqual(len(response_data['discussion_data']), 1)
        self.assertEqual(response_data["page"], 1)
        self.assertEqual(response_data["num_pages"], 1)
        self.assertEqual(response_data['discussion_data'][0]['id'], self.TEST_THREAD_ID)
        self.assertEqual(response_data['discussion_data'][0]['title'], self.TEST_THREAD_TEXT)
        self.assertEqual(response_data['discussion_data'][0]['body'], self.TEST_THREAD_TEXT)

    def test_html(self, mock_request):
        self.check_html(mock_request)

    def test_html_p2(self, mock_request):
        self.check_html(mock_request, page="2")

    def test_ajax(self, mock_request):
        self.check_ajax(mock_request)

    def test_ajax_p2(self, mock_request):
        self.check_ajax(mock_request, page="2")

    def test_404_profiled_user(self, mock_request):
        request = RequestFactory().get("dummy_url")
        request.user = self.student
        with self.assertRaises(Http404):
stv committed
1158
            views.user_profile(
1159
                request,
1160
                self.course.id.to_deprecated_string(),
1161 1162 1163 1164 1165 1166 1167
                -999
            )

    def test_404_course(self, mock_request):
        request = RequestFactory().get("dummy_url")
        request.user = self.student
        with self.assertRaises(Http404):
stv committed
1168
            views.user_profile(
1169 1170 1171 1172 1173 1174
                request,
                "non/existent/course",
                self.profiled_user.id
            )

    def test_post(self, mock_request):
1175 1176 1177
        mock_request.side_effect = make_mock_request_impl(
            course=self.course, text=self.TEST_THREAD_TEXT, thread_id=self.TEST_THREAD_ID
        )
1178 1179 1180 1181
        request = RequestFactory().post("dummy_url")
        request.user = self.student
        response = views.user_profile(
            request,
1182
            self.course.id.to_deprecated_string(),
1183 1184 1185 1186
            self.profiled_user.id
        )
        self.assertEqual(response.status_code, 405)

Sarina Canelake committed
1187

1188
@patch('requests.request')
1189 1190 1191
class CommentsServiceRequestHeadersTestCase(UrlResetMixin, ModuleStoreTestCase):
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
1192 1193
        super(CommentsServiceRequestHeadersTestCase, self).setUp()

1194 1195 1196 1197
        username = "foo"
        password = "bar"

        # Invoke UrlResetMixin
1198
        super(CommentsServiceRequestHeadersTestCase, self).setUp(create_user=False)
1199
        self.course = CourseFactory.create(discussion_topics={'dummy discussion': {'id': 'dummy_discussion_id'}})
1200 1201 1202 1203 1204 1205 1206 1207
        self.student = UserFactory.create(username=username, password=password)
        CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id)
        self.assertTrue(
            self.client.login(username=username, password=password)
        )

    def assert_all_calls_have_header(self, mock_request, key, value):
        expected = call(
Sarina Canelake committed
1208 1209
            ANY,  # method
            ANY,  # url
1210 1211 1212 1213 1214 1215 1216 1217
            data=ANY,
            params=ANY,
            headers=PartialDictMatcher({key: value}),
            timeout=ANY
        )
        for actual in mock_request.call_args_list:
            self.assertEqual(expected, actual)

1218 1219 1220 1221
    def test_accept_language(self, mock_request):
        lang = "eo"
        text = "dummy content"
        thread_id = "test_thread_id"
1222
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text, thread_id=thread_id)
1223 1224 1225 1226 1227

        self.client.get(
            reverse(
                "django_comment_client.forum.views.single_thread",
                kwargs={
1228
                    "course_id": self.course.id.to_deprecated_string(),
1229
                    "discussion_id": "dummy_discussion_id",
1230 1231 1232 1233 1234 1235 1236
                    "thread_id": thread_id,
                }
            ),
            HTTP_ACCEPT_LANGUAGE=lang,
        )
        self.assert_all_calls_have_header(mock_request, "Accept-Language", lang)

1237 1238
    @override_settings(COMMENTS_SERVICE_KEY="test_api_key")
    def test_api_key(self, mock_request):
1239
        mock_request.side_effect = make_mock_request_impl(course=self.course, text="dummy", thread_id="dummy")
1240 1241 1242 1243

        self.client.get(
            reverse(
                "django_comment_client.forum.views.forum_form_discussion",
1244
                kwargs={"course_id": self.course.id.to_deprecated_string()}
1245 1246 1247 1248 1249
            ),
        )
        self.assert_all_calls_have_header(mock_request, "X-Edx-Api-Key", "test_api_key")


1250 1251
class InlineDiscussionUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin):
    def setUp(self):
1252 1253
        super(InlineDiscussionUnicodeTestCase, self).setUp()

1254 1255 1256 1257 1258 1259
        self.course = CourseFactory.create()
        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):
1260
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text)
1261 1262 1263
        request = RequestFactory().get("dummy_url")
        request.user = self.student

1264 1265 1266
        response = views.inline_discussion(
            request, self.course.id.to_deprecated_string(), self.course.discussion_topics['General']['id']
        )
1267 1268 1269 1270 1271 1272 1273 1274
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEqual(response_data["discussion_data"][0]["title"], text)
        self.assertEqual(response_data["discussion_data"][0]["body"], text)


class ForumFormDiscussionUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin):
    def setUp(self):
1275 1276
        super(ForumFormDiscussionUnicodeTestCase, self).setUp()

1277 1278 1279 1280 1281 1282
        self.course = CourseFactory.create()
        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):
1283
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text)
1284 1285
        request = RequestFactory().get("dummy_url")
        request.user = self.student
Sarina Canelake committed
1286
        request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"  # so request.is_ajax() == True
1287

1288
        response = views.forum_form_discussion(request, self.course.id.to_deprecated_string())
1289 1290 1291 1292 1293
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEqual(response_data["discussion_data"][0]["title"], text)
        self.assertEqual(response_data["discussion_data"][0]["body"], text)

muhammad-ammar committed
1294

1295 1296
class ForumDiscussionSearchUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin):
    def setUp(self):
1297 1298
        super(ForumDiscussionSearchUnicodeTestCase, self).setUp()

1299 1300 1301 1302 1303 1304
        self.course = CourseFactory.create()
        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):
1305
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text)
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
        data = {
            "ajax": 1,
            "text": text,
        }
        request = RequestFactory().get("dummy_url", data)
        request.user = self.student
        request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"  # so request.is_ajax() == True

        response = views.forum_form_discussion(request, self.course.id.to_deprecated_string())
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEqual(response_data["discussion_data"][0]["title"], text)
        self.assertEqual(response_data["discussion_data"][0]["body"], text)
1319

muhammad-ammar committed
1320

1321 1322
class SingleThreadUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin):
    def setUp(self):
1323 1324
        super(SingleThreadUnicodeTestCase, self).setUp()

1325
        self.course = CourseFactory.create(discussion_topics={'dummy_discussion_id': {'id': 'dummy_discussion_id'}})
1326 1327 1328 1329 1330 1331
        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):
        thread_id = "test_thread_id"
1332
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text, thread_id=thread_id)
1333 1334
        request = RequestFactory().get("dummy_url")
        request.user = self.student
Sarina Canelake committed
1335
        request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"  # so request.is_ajax() == True
1336

1337
        response = views.single_thread(request, self.course.id.to_deprecated_string(), "dummy_discussion_id", thread_id)
1338 1339 1340 1341 1342 1343 1344 1345
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEqual(response_data["content"]["title"], text)
        self.assertEqual(response_data["content"]["body"], text)


class UserProfileUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin):
    def setUp(self):
1346 1347
        super(UserProfileUnicodeTestCase, self).setUp()

1348 1349 1350 1351 1352 1353
        self.course = CourseFactory.create()
        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):
1354
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text)
1355 1356
        request = RequestFactory().get("dummy_url")
        request.user = self.student
Sarina Canelake committed
1357
        request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"  # so request.is_ajax() == True
1358

1359
        response = views.user_profile(request, self.course.id.to_deprecated_string(), str(self.student.id))
1360 1361 1362 1363 1364 1365 1366 1367
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEqual(response_data["discussion_data"][0]["title"], text)
        self.assertEqual(response_data["discussion_data"][0]["body"], text)


class FollowedThreadsUnicodeTestCase(ModuleStoreTestCase, UnicodeTestMixin):
    def setUp(self):
1368 1369
        super(FollowedThreadsUnicodeTestCase, self).setUp()

1370 1371 1372 1373 1374 1375
        self.course = CourseFactory.create()
        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):
1376
        mock_request.side_effect = make_mock_request_impl(course=self.course, text=text)
1377 1378
        request = RequestFactory().get("dummy_url")
        request.user = self.student
Sarina Canelake committed
1379
        request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"  # so request.is_ajax() == True
1380

1381
        response = views.followed_threads(request, self.course.id.to_deprecated_string(), str(self.student.id))
1382 1383 1384 1385
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.content)
        self.assertEqual(response_data["discussion_data"][0]["title"], text)
        self.assertEqual(response_data["discussion_data"][0]["body"], text)
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402


class EnrollmentTestCase(ModuleStoreTestCase):
    """
    Tests for the behavior of views depending on if the student is enrolled
    in the course
    """

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(EnrollmentTestCase, self).setUp()
        self.course = CourseFactory.create()
        self.student = UserFactory.create()

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    @patch('lms.lib.comment_client.utils.requests.request')
    def test_unenrolled(self, mock_request):
1403
        mock_request.side_effect = make_mock_request_impl(course=self.course, text='dummy')
1404 1405 1406 1407
        request = RequestFactory().get('dummy_url')
        request.user = self.student
        with self.assertRaises(UserNotEnrolled):
            views.forum_form_discussion(request, course_id=self.course.id.to_deprecated_string())