test_api.py 125 KB
Newer Older
Greg Price committed
1 2 3
"""
Tests for Discussion API internal interface
"""
4
import itertools
cahrens committed
5
from datetime import datetime, timedelta
6
from urllib import urlencode
cahrens committed
7
from urlparse import parse_qs, urlparse, urlunparse
Greg Price committed
8

9
import ddt
10
import httpretty
Greg Price committed
11
import mock
12 13
from django.core.exceptions import ValidationError
from django.test.client import RequestFactory
14
from nose.plugins.attrib import attr
15 16 17
from opaque_keys.edx.locator import CourseLocator
from pytz import UTC
from rest_framework.exceptions import PermissionDenied
18

19
from common.test.utils import MockSignalHandlerMixin, disable_signal
Greg Price committed
20
from courseware.tests.factories import BetaTesterFactory, StaffFactory
21
from discussion_api import api
22 23 24
from discussion_api.api import (
    create_comment,
    create_thread,
25
    delete_comment,
26
    delete_thread,
27
    get_comment_list,
28
    get_course,
29
    get_course_topics,
cahrens committed
30
    get_thread,
31
    get_thread_list,
32
    update_comment,
cahrens committed
33
    update_thread
34
)
cahrens committed
35
from discussion_api.exceptions import CommentNotFoundError, DiscussionDisabledError, ThreadNotFoundError
36 37 38 39
from discussion_api.tests.utils import (
    CommentsServiceMockMixin,
    make_minimal_cs_comment,
    make_minimal_cs_thread,
cahrens committed
40
    make_paginated_api_response
41
)
cahrens committed
42
from django_comment_client.tests.utils import ForumsEnableMixin
43 44 45 46 47
from django_comment_common.models import (
    FORUM_ROLE_ADMINISTRATOR,
    FORUM_ROLE_COMMUNITY_TA,
    FORUM_ROLE_MODERATOR,
    FORUM_ROLE_STUDENT,
cahrens committed
48
    Role
49
)
Greg Price committed
50 51
from openedx.core.djangoapps.course_groups.models import CourseUserGroupPartitionGroup
from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory
52
from openedx.core.lib.exceptions import CourseNotFoundError, PageNotFoundError
53
from student.tests.factories import CourseEnrollmentFactory, UserFactory
54
from util.testing import UrlResetMixin
55
from xmodule.modulestore import ModuleStoreEnum
56
from xmodule.modulestore.django import modulestore
57
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase
Greg Price committed
58
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
59
from xmodule.partitions.partitions import Group, UserPartition
60 61 62 63 64 65


def _remove_discussion_tab(course, user_id):
    """
    Remove the discussion tab for the course.

66
    user_id is passed to the modulestore as the editor of the xblock.
67
    """
68
    course.tabs = [tab for tab in course.tabs if not tab.type == 'discussion']
69
    modulestore().update_item(course, user_id)
Greg Price committed
70 71


72 73 74 75 76 77 78 79 80 81 82 83 84
def _discussion_disabled_course_for(user):
    """
    Create and return a course with discussions disabled.

    The user passed in will be enrolled in the course.
    """
    course_with_disabled_forums = CourseFactory.create()
    CourseEnrollmentFactory.create(user=user, course_id=course_with_disabled_forums.id)
    _remove_discussion_tab(course_with_disabled_forums, user.id)

    return course_with_disabled_forums


85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
def _create_course_and_cohort_with_user_role(course_is_cohorted, user, role_name):
    """
    Creates a course with the value of `course_is_cohorted`, plus `always_cohort_inline_discussions`
    set to True (which is no longer the default value). Then 1) enrolls the user in that course,
    2) creates a cohort that the user is placed in, and 3) adds the user to the given role.

    Returns: a tuple of the created course and the created cohort
    """
    cohort_course = CourseFactory.create(
        cohort_config={"cohorted": course_is_cohorted, "always_cohort_inline_discussions": True}
    )
    CourseEnrollmentFactory.create(user=user, course_id=cohort_course.id)
    cohort = CohortFactory.create(course_id=cohort_course.id, users=[user])
    role = Role.objects.create(name=role_name, course_id=cohort_course.id)
    role.users = [user]
    return [cohort_course, cohort]


103
@attr(shard=2)
104
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
105
class GetCourseTest(ForumsEnableMixin, UrlResetMixin, SharedModuleStoreTestCase):
106 107
    """Test for get_course"""

108 109 110 111 112
    @classmethod
    def setUpClass(cls):
        super(GetCourseTest, cls).setUpClass()
        cls.course = CourseFactory.create(org="x", course="y", run="z")

113 114 115 116
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(GetCourseTest, self).setUp()
        self.user = UserFactory.create()
117
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
118 119 120 121
        self.request = RequestFactory().get("/dummy")
        self.request.user = self.user

    def test_nonexistent_course(self):
122
        with self.assertRaises(CourseNotFoundError):
123 124 125 126 127
            get_course(self.request, CourseLocator.from_string("non/existent/course"))

    def test_not_enrolled(self):
        unenrolled_user = UserFactory.create()
        self.request.user = unenrolled_user
128
        with self.assertRaises(CourseNotFoundError):
129 130 131
            get_course(self.request, self.course.id)

    def test_discussions_disabled(self):
132
        with self.assertRaises(DiscussionDisabledError):
133
            get_course(self.request, _discussion_disabled_course_for(self.user).id)
134 135 136 137 138 139 140 141

    def test_basic(self):
        self.assertEqual(
            get_course(self.request, self.course.id),
            {
                "id": unicode(self.course.id),
                "blackouts": [],
                "thread_list_url": "http://testserver/api/discussion/v1/threads/?course_id=x%2Fy%2Fz",
142 143 144
                "following_thread_list_url": (
                    "http://testserver/api/discussion/v1/threads/?course_id=x%2Fy%2Fz&following=True"
                ),
145 146 147 148
                "topics_url": "http://testserver/api/discussion/v1/course_topics/x/y/z",
            }
        )

149

150
@attr(shard=2)
151 152
@ddt.ddt
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
153
class GetCourseTestBlackouts(ForumsEnableMixin, UrlResetMixin, ModuleStoreTestCase):
154 155 156 157 158 159 160 161 162 163 164 165 166
    """
    Tests of get_course for courses that have blackout dates.
    """

    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(GetCourseTestBlackouts, self).setUp()
        self.course = CourseFactory.create(org="x", course="y", run="z")
        self.user = UserFactory.create()
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
        self.request = RequestFactory().get("/dummy")
        self.request.user = self.user

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    def test_blackout(self):
        # A variety of formats is accepted
        self.course.discussion_blackouts = [
            ["2015-06-09T00:00:00Z", "6-10-15"],
            [1433980800000, datetime(2015, 6, 12)],
        ]
        modulestore().update_item(self.course, self.user.id)
        result = get_course(self.request, self.course.id)
        self.assertEqual(
            result["blackouts"],
            [
                {"start": "2015-06-09T00:00:00+00:00", "end": "2015-06-10T00:00:00+00:00"},
                {"start": "2015-06-11T00:00:00+00:00", "end": "2015-06-12T00:00:00+00:00"},
            ]
        )

    @ddt.data(None, "not a datetime", "2015", [])
    def test_blackout_errors(self, bad_value):
        self.course.discussion_blackouts = [
            [bad_value, "2015-06-09T00:00:00Z"],
            ["2015-06-10T00:00:00Z", "2015-06-11T00:00:00Z"],
        ]
        modulestore().update_item(self.course, self.user.id)
        result = get_course(self.request, self.course.id)
        self.assertEqual(result["blackouts"], [])


194
@attr(shard=2)
Greg Price committed
195
@mock.patch.dict("django.conf.settings.FEATURES", {"DISABLE_START_DATES": False})
196
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
197
class GetCourseTopicsTest(ForumsEnableMixin, UrlResetMixin, ModuleStoreTestCase):
Greg Price committed
198
    """Test for get_course_topics"""
199
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
Greg Price committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    def setUp(self):
        super(GetCourseTopicsTest, self).setUp()
        self.maxDiff = None  # pylint: disable=invalid-name
        self.partition = UserPartition(
            0,
            "partition",
            "Test Partition",
            [Group(0, "Cohort A"), Group(1, "Cohort B")],
            scheme_id="cohort"
        )
        self.course = CourseFactory.create(
            org="x",
            course="y",
            run="z",
            start=datetime.now(UTC),
215
            discussion_topics={"Test Topic": {"id": "non-courseware-topic-id"}},
Greg Price committed
216 217 218 219 220
            user_partitions=[self.partition],
            cohort_config={"cohorted": True},
            days_early_for_beta=3
        )
        self.user = UserFactory.create()
221 222
        self.request = RequestFactory().get("/dummy")
        self.request.user = self.user
223
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
Greg Price committed
224

225 226 227 228
    def make_discussion_xblock(self, topic_id, category, subcategory, **kwargs):
        """
        Build a discussion xblock in self.course.
        """
Greg Price committed
229 230 231 232 233 234 235 236 237
        ItemFactory.create(
            parent_location=self.course.location,
            category="discussion",
            discussion_id=topic_id,
            discussion_category=category,
            discussion_target=subcategory,
            **kwargs
        )

238 239 240 241 242 243 244 245 246
    def get_thread_list_url(self, topic_id_list):
        """
        Returns the URL for the thread_list_url field, given a list of topic_ids
        """
        path = "http://testserver/api/discussion/v1/threads/"
        query_list = [("course_id", unicode(self.course.id))] + [("topic_id", topic_id) for topic_id in topic_id_list]
        return urlunparse(("", "", path, "", urlencode(query_list), ""))

    def get_course_topics(self):
Greg Price committed
247 248 249 250
        """
        Get course topics for self.course, using the given user or self.user if
        not provided, and generating absolute URIs with a test scheme/host.
        """
251
        return get_course_topics(self.request, self.course.id)
Greg Price committed
252 253 254 255 256 257

    def make_expected_tree(self, topic_id, name, children=None):
        """
        Build an expected result tree given a topic id, display name, and
        children
        """
258
        topic_id_list = [topic_id] if topic_id else [child["id"] for child in children]
Greg Price committed
259 260 261 262 263
        children = children or []
        node = {
            "id": topic_id,
            "name": name,
            "children": children,
264
            "thread_list_url": self.get_thread_list_url(topic_id_list)
Greg Price committed
265
        }
266

Greg Price committed
267 268
        return node

269
    def test_nonexistent_course(self):
270
        with self.assertRaises(CourseNotFoundError):
271
            get_course_topics(self.request, CourseLocator.from_string("non/existent/course"))
272 273 274

    def test_not_enrolled(self):
        unenrolled_user = UserFactory.create()
275
        self.request.user = unenrolled_user
276
        with self.assertRaises(CourseNotFoundError):
277
            self.get_course_topics()
Greg Price committed
278

279 280
    def test_discussions_disabled(self):
        _remove_discussion_tab(self.course, self.user.id)
281
        with self.assertRaises(DiscussionDisabledError):
282 283 284
            self.get_course_topics()

    def test_without_courseware(self):
Greg Price committed
285 286 287
        actual = self.get_course_topics()
        expected = {
            "courseware_topics": [],
288 289 290
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-topic-id", "Test Topic")
            ],
Greg Price committed
291 292 293
        }
        self.assertEqual(actual, expected)

294
    def test_with_courseware(self):
295
        self.make_discussion_xblock("courseware-topic-id", "Foo", "Bar")
Greg Price committed
296 297 298 299 300 301
        actual = self.get_course_topics()
        expected = {
            "courseware_topics": [
                self.make_expected_tree(
                    None,
                    "Foo",
302
                    [self.make_expected_tree("courseware-topic-id", "Bar")]
Greg Price committed
303 304
                ),
            ],
305 306 307
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-topic-id", "Test Topic")
            ],
Greg Price committed
308 309 310 311
        }
        self.assertEqual(actual, expected)

    def test_many(self):
312 313 314 315 316 317
        with self.store.bulk_operations(self.course.id, emit_signals=False):
            self.course.discussion_topics = {
                "A": {"id": "non-courseware-1"},
                "B": {"id": "non-courseware-2"},
            }
            self.store.update_item(self.course, self.user.id)
318 319 320 321 322
            self.make_discussion_xblock("courseware-1", "A", "1")
            self.make_discussion_xblock("courseware-2", "A", "2")
            self.make_discussion_xblock("courseware-3", "B", "1")
            self.make_discussion_xblock("courseware-4", "B", "2")
            self.make_discussion_xblock("courseware-5", "C", "1")
Greg Price committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        actual = self.get_course_topics()
        expected = {
            "courseware_topics": [
                self.make_expected_tree(
                    None,
                    "A",
                    [
                        self.make_expected_tree("courseware-1", "1"),
                        self.make_expected_tree("courseware-2", "2"),
                    ]
                ),
                self.make_expected_tree(
                    None,
                    "B",
                    [
                        self.make_expected_tree("courseware-3", "1"),
                        self.make_expected_tree("courseware-4", "2"),
                    ]
                ),
                self.make_expected_tree(
                    None,
                    "C",
                    [self.make_expected_tree("courseware-5", "1")]
                ),
            ],
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-1", "A"),
                self.make_expected_tree("non-courseware-2", "B"),
            ],
        }
        self.assertEqual(actual, expected)

    def test_sort_key(self):
356 357 358 359 360 361 362 363
        with self.store.bulk_operations(self.course.id, emit_signals=False):
            self.course.discussion_topics = {
                "W": {"id": "non-courseware-1", "sort_key": "Z"},
                "X": {"id": "non-courseware-2"},
                "Y": {"id": "non-courseware-3", "sort_key": "Y"},
                "Z": {"id": "non-courseware-4", "sort_key": "W"},
            }
            self.store.update_item(self.course, self.user.id)
364 365 366 367 368 369 370
            self.make_discussion_xblock("courseware-1", "First", "A", sort_key="D")
            self.make_discussion_xblock("courseware-2", "First", "B", sort_key="B")
            self.make_discussion_xblock("courseware-3", "First", "C", sort_key="E")
            self.make_discussion_xblock("courseware-4", "Second", "A", sort_key="F")
            self.make_discussion_xblock("courseware-5", "Second", "B", sort_key="G")
            self.make_discussion_xblock("courseware-6", "Second", "C")
            self.make_discussion_xblock("courseware-7", "Second", "D", sort_key="A")
371

Greg Price committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        actual = self.get_course_topics()
        expected = {
            "courseware_topics": [
                self.make_expected_tree(
                    None,
                    "First",
                    [
                        self.make_expected_tree("courseware-2", "B"),
                        self.make_expected_tree("courseware-1", "A"),
                        self.make_expected_tree("courseware-3", "C"),
                    ]
                ),
                self.make_expected_tree(
                    None,
                    "Second",
                    [
                        self.make_expected_tree("courseware-7", "D"),
                        self.make_expected_tree("courseware-6", "C"),
                        self.make_expected_tree("courseware-4", "A"),
                        self.make_expected_tree("courseware-5", "B"),
                    ]
                ),
            ],
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-4", "Z"),
                self.make_expected_tree("non-courseware-2", "X"),
                self.make_expected_tree("non-courseware-3", "Y"),
                self.make_expected_tree("non-courseware-1", "W"),
            ],
        }
        self.assertEqual(actual, expected)

    def test_access_control(self):
        """
        Test that only topics that a user has access to are returned. The
        ways in which a user may not have access are:

        * Module is visible to staff only
        * Module has a start date in the future
        * Module is accessible only to a group the user is not in

        Also, there is a case that ensures that a category with no accessible
        subcategories does not appear in the result.
        """
        beta_tester = BetaTesterFactory.create(course_key=self.course.id)
417
        CourseEnrollmentFactory.create(user=beta_tester, course_id=self.course.id)
Greg Price committed
418 419 420 421 422 423 424 425 426 427 428 429 430
        staff = StaffFactory.create(course_key=self.course.id)
        for user, group_idx in [(self.user, 0), (beta_tester, 1)]:
            cohort = CohortFactory.create(
                course_id=self.course.id,
                name=self.partition.groups[group_idx].name,
                users=[user]
            )
            CourseUserGroupPartitionGroup.objects.create(
                course_user_group=cohort,
                partition_id=self.partition.id,
                group_id=self.partition.groups[group_idx].id
            )

431
        with self.store.bulk_operations(self.course.id, emit_signals=False):
432 433
            self.make_discussion_xblock("courseware-1", "First", "Everybody")
            self.make_discussion_xblock(
434 435 436 437 438
                "courseware-2",
                "First",
                "Cohort A",
                group_access={self.partition.id: [self.partition.groups[0].id]}
            )
439
            self.make_discussion_xblock(
440 441 442 443 444
                "courseware-3",
                "First",
                "Cohort B",
                group_access={self.partition.id: [self.partition.groups[1].id]}
            )
445 446
            self.make_discussion_xblock("courseware-4", "Second", "Staff Only", visible_to_staff_only=True)
            self.make_discussion_xblock(
447 448 449 450 451
                "courseware-5",
                "Second",
                "Future Start Date",
                start=datetime.now(UTC) + timedelta(days=1)
            )
Greg Price committed
452 453 454 455 456 457 458 459 460 461 462 463 464

        student_actual = self.get_course_topics()
        student_expected = {
            "courseware_topics": [
                self.make_expected_tree(
                    None,
                    "First",
                    [
                        self.make_expected_tree("courseware-2", "Cohort A"),
                        self.make_expected_tree("courseware-1", "Everybody"),
                    ]
                ),
            ],
465 466 467
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-topic-id", "Test Topic"),
            ],
Greg Price committed
468 469
        }
        self.assertEqual(student_actual, student_expected)
470 471
        self.request.user = beta_tester
        beta_actual = self.get_course_topics()
Greg Price committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        beta_expected = {
            "courseware_topics": [
                self.make_expected_tree(
                    None,
                    "First",
                    [
                        self.make_expected_tree("courseware-3", "Cohort B"),
                        self.make_expected_tree("courseware-1", "Everybody"),
                    ]
                ),
                self.make_expected_tree(
                    None,
                    "Second",
                    [self.make_expected_tree("courseware-5", "Future Start Date")]
                ),
            ],
488 489 490
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-topic-id", "Test Topic"),
            ],
Greg Price committed
491 492 493
        }
        self.assertEqual(beta_actual, beta_expected)

494 495
        self.request.user = staff
        staff_actual = self.get_course_topics()
Greg Price committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        staff_expected = {
            "courseware_topics": [
                self.make_expected_tree(
                    None,
                    "First",
                    [
                        self.make_expected_tree("courseware-2", "Cohort A"),
                        self.make_expected_tree("courseware-3", "Cohort B"),
                        self.make_expected_tree("courseware-1", "Everybody"),
                    ]
                ),
                self.make_expected_tree(
                    None,
                    "Second",
                    [
                        self.make_expected_tree("courseware-5", "Future Start Date"),
                        self.make_expected_tree("courseware-4", "Staff Only"),
                    ]
                ),
            ],
516 517 518
            "non_courseware_topics": [
                self.make_expected_tree("non-courseware-topic-id", "Test Topic"),
            ],
Greg Price committed
519 520
        }
        self.assertEqual(staff_actual, staff_expected)
521

522 523 524 525 526 527
    def test_discussion_topic(self):
        """
        Tests discussion topic details against a requested topic id
        """
        topic_id_1 = "topic_id_1"
        topic_id_2 = "topic_id_2"
528 529
        self.make_discussion_xblock(topic_id_1, "test_category_1", "test_target_1")
        self.make_discussion_xblock(topic_id_2, "test_category_2", "test_target_2")
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        actual = get_course_topics(self.request, self.course.id, {"topic_id_1", "topic_id_2"})
        self.assertEqual(
            actual,
            {
                "non_courseware_topics": [],
                "courseware_topics": [
                    {
                        "children": [{
                            "children": [],
                            "id": "topic_id_1",
                            "thread_list_url": "http://testserver/api/discussion/v1/threads/?"
                                               "course_id=x%2Fy%2Fz&topic_id=topic_id_1",
                            "name": "test_target_1"
                        }],
                        "id": None,
                        "thread_list_url": "http://testserver/api/discussion/v1/threads/?"
                                           "course_id=x%2Fy%2Fz&topic_id=topic_id_1",
                        "name": "test_category_1"
                    },
                    {
                        "children":
                            [{
                                "children": [],
                                "id": "topic_id_2",
                                "thread_list_url": "http://testserver/api/discussion/v1/threads/?"
                                                   "course_id=x%2Fy%2Fz&topic_id=topic_id_2",
                                "name": "test_target_2"
                            }],
                        "id": None,
                        "thread_list_url": "http://testserver/api/discussion/v1/threads/?"
                                           "course_id=x%2Fy%2Fz&topic_id=topic_id_2",
                        "name": "test_category_2"
                    }
                ]
            }
        )

567

568
@attr(shard=2)
569
@ddt.ddt
570
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
571
class GetThreadListTest(ForumsEnableMixin, CommentsServiceMockMixin, UrlResetMixin, SharedModuleStoreTestCase):
572
    """Test for get_thread_list"""
573 574 575 576 577 578

    @classmethod
    def setUpClass(cls):
        super(GetThreadListTest, cls).setUpClass()
        cls.course = CourseFactory.create()

579
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
580 581
    def setUp(self):
        super(GetThreadListTest, self).setUp()
582 583 584
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
585
        self.maxDiff = None  # pylint: disable=invalid-name
586
        self.user = UserFactory.create()
587
        self.register_get_user_response(self.user)
588
        self.request = RequestFactory().get("/test_path")
589
        self.request.user = self.user
590
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
591
        self.author = UserFactory.create()
592 593
        self.course.cohort_config = {"cohorted": False}
        modulestore().update_item(self.course, ModuleStoreEnum.UserID.test)
594
        self.cohort = CohortFactory.create(course_id=self.course.id)
595

596 597 598 599 600 601 602 603 604
    def get_thread_list(
            self,
            threads,
            page=1,
            page_size=1,
            num_pages=1,
            course=None,
            topic_id_list=None,
    ):
605 606 607 608
        """
        Register the appropriate comments service response, then call
        get_thread_list and return the result.
        """
609
        course = course or self.course
610
        self.register_get_threads_response(threads, page, num_pages)
611
        ret = get_thread_list(self.request, course.id, page, page_size, topic_id_list)
612 613
        return ret

614
    def test_nonexistent_course(self):
615
        with self.assertRaises(CourseNotFoundError):
616 617 618 619
            get_thread_list(self.request, CourseLocator.from_string("non/existent/course"), 1, 1)

    def test_not_enrolled(self):
        self.request.user = UserFactory.create()
620
        with self.assertRaises(CourseNotFoundError):
621 622 623
            self.get_thread_list([])

    def test_discussions_disabled(self):
624
        with self.assertRaises(DiscussionDisabledError):
625
            self.get_thread_list([], course=_discussion_disabled_course_for(self.user))
626

627 628
    def test_empty(self):
        self.assertEqual(
629
            self.get_thread_list([], num_pages=0).data,
630
            {
631 632 633 634 635 636
                "pagination": {
                    "next": None,
                    "previous": None,
                    "num_pages": 0,
                    "count": 0
                },
637
                "results": [],
638
                "text_search_rewrite": None,
639 640 641
            }
        )

642 643 644 645
    def test_get_threads_by_topic_id(self):
        self.get_thread_list([], topic_id_list=["topic_x", "topic_meow"])
        self.assertEqual(urlparse(httpretty.last_request().path).path, "/api/v1/threads")
        self.assert_last_query_params({
646
            "user_id": [unicode(self.user.id)],
647
            "course_id": [unicode(self.course.id)],
648
            "sort_key": ["activity"],
649 650 651 652 653
            "page": ["1"],
            "per_page": ["1"],
            "commentable_ids": ["topic_x,topic_meow"]
        })

654 655 656
    def test_basic_query_params(self):
        self.get_thread_list([], page=6, page_size=14)
        self.assert_last_query_params({
657
            "user_id": [unicode(self.user.id)],
658
            "course_id": [unicode(self.course.id)],
659
            "sort_key": ["activity"],
660 661 662 663 664
            "page": ["6"],
            "per_page": ["14"],
        })

    def test_thread_content(self):
665 666
        self.course.cohort_config = {"cohorted": True}
        modulestore().update_item(self.course, ModuleStoreEnum.UserID.test)
667
        source_threads = [
668
            make_minimal_cs_thread({
669
                "id": "test_thread_id_0",
670
                "course_id": unicode(self.course.id),
671
                "commentable_id": "topic_x",
672
                "username": self.author.username,
673
                "user_id": str(self.author.id),
674 675
                "title": "Test Title",
                "body": "Test body",
676
                "votes": {"up_count": 4},
677 678
                "comments_count": 5,
                "unread_comments_count": 3,
679 680
                "endorsed": True,
                "read": True,
681 682 683 684
                "created_at": "2015-04-28T00:00:00Z",
                "updated_at": "2015-04-28T11:11:11Z",
            }),
            make_minimal_cs_thread({
685
                "id": "test_thread_id_1",
686
                "course_id": unicode(self.course.id),
687
                "commentable_id": "topic_y",
688
                "group_id": self.cohort.id,
689
                "username": self.author.username,
690
                "user_id": str(self.author.id),
691
                "thread_type": "question",
692 693
                "title": "Another Test Title",
                "body": "More content",
694
                "votes": {"up_count": 9},
695
                "comments_count": 18,
696 697 698
                "created_at": "2015-04-28T22:22:22Z",
                "updated_at": "2015-04-28T00:33:33Z",
            })
699 700
        ]
        expected_threads = [
701
            self.expected_thread_data({
702
                "id": "test_thread_id_0",
703
                "author": self.author.username,
704
                "topic_id": "topic_x",
705
                "vote_count": 4,
706
                "comment_count": 6,
707
                "unread_comment_count": 3,
708
                "comment_list_url": "http://testserver/api/discussion/v1/comments/?thread_id=test_thread_id_0",
709
                "editable_fields": ["abuse_flagged", "following", "read", "voted"],
710 711
                "has_endorsed": True,
                "read": True,
712 713 714 715
                "created_at": "2015-04-28T00:00:00Z",
                "updated_at": "2015-04-28T11:11:11Z",
            }),
            self.expected_thread_data({
716
                "id": "test_thread_id_1",
717
                "author": self.author.username,
718
                "topic_id": "topic_y",
719 720
                "group_id": self.cohort.id,
                "group_name": self.cohort.name,
721 722 723
                "type": "question",
                "title": "Another Test Title",
                "raw_body": "More content",
724
                "rendered_body": "<p>More content</p>",
725
                "vote_count": 9,
726
                "comment_count": 19,
727 728
                "created_at": "2015-04-28T22:22:22Z",
                "updated_at": "2015-04-28T00:33:33Z",
729 730 731 732 733 734 735
                "comment_list_url": None,
                "endorsed_comment_list_url": (
                    "http://testserver/api/discussion/v1/comments/?thread_id=test_thread_id_1&endorsed=True"
                ),
                "non_endorsed_comment_list_url": (
                    "http://testserver/api/discussion/v1/comments/?thread_id=test_thread_id_1&endorsed=False"
                ),
736
                "editable_fields": ["abuse_flagged", "following", "read", "voted"],
737
            }),
738
        ]
739 740

        expected_result = make_paginated_api_response(
741
            results=expected_threads, count=2, num_pages=1, next_link=None, previous_link=None
742 743
        )
        expected_result.update({"text_search_rewrite": None})
744
        self.assertEqual(
745 746
            self.get_thread_list(source_threads).data,
            expected_result
747 748
        )

749 750 751 752 753 754 755 756 757 758 759 760 761 762
    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False]
        )
    )
    @ddt.unpack
    def test_request_group(self, role_name, course_is_cohorted):
        cohort_course = CourseFactory.create(cohort_config={"cohorted": course_is_cohorted})
763
        CourseEnrollmentFactory.create(user=self.user, course_id=cohort_course.id)
764 765 766 767 768 769 770 771
        CohortFactory.create(course_id=cohort_course.id, users=[self.user])
        role = Role.objects.create(name=role_name, course_id=cohort_course.id)
        role.users = [self.user]
        self.get_thread_list([], course=cohort_course)
        actual_has_group = "group_id" in httpretty.last_request().querystring
        expected_has_group = (course_is_cohorted and role_name == FORUM_ROLE_STUDENT)
        self.assertEqual(actual_has_group, expected_has_group)

772 773
    def test_pagination(self):
        # N.B. Empty thread list is not realistic but convenient for this test
774 775 776
        expected_result = make_paginated_api_response(
            results=[], count=0, num_pages=3, next_link="http://testserver/test_path?page=2", previous_link=None
        )
777
        expected_result.update({"text_search_rewrite": None})
778
        self.assertEqual(
779 780 781 782 783
            self.get_thread_list([], page=1, num_pages=3).data,
            expected_result
        )

        expected_result = make_paginated_api_response(
784 785 786 787 788
            results=[],
            count=0,
            num_pages=3,
            next_link="http://testserver/test_path?page=3",
            previous_link="http://testserver/test_path?page=1"
789
        )
790
        expected_result.update({"text_search_rewrite": None})
791
        self.assertEqual(
792 793
            self.get_thread_list([], page=2, num_pages=3).data,
            expected_result
794
        )
795 796

        expected_result = make_paginated_api_response(
797
            results=[], count=0, num_pages=3, next_link=None, previous_link="http://testserver/test_path?page=2"
798 799
        )
        expected_result.update({"text_search_rewrite": None})
800
        self.assertEqual(
801 802
            self.get_thread_list([], page=3, num_pages=3).data,
            expected_result
803 804 805 806
        )

        # Test page past the last one
        self.register_get_threads_response([], page=3, num_pages=3)
807
        with self.assertRaises(PageNotFoundError):
808
            get_thread_list(self.request, self.course.id, page=4, page_size=10)
809

810 811
    @ddt.data(None, "rewritten search string")
    def test_text_search(self, text_search_rewrite):
812
        expected_result = make_paginated_api_response(
813
            results=[], count=0, num_pages=0, next_link=None, previous_link=None
814 815 816
        )
        expected_result.update({"text_search_rewrite": text_search_rewrite})
        self.register_get_threads_search_response([], text_search_rewrite, num_pages=0)
817 818 819 820 821 822 823
        self.assertEqual(
            get_thread_list(
                self.request,
                self.course.id,
                page=1,
                page_size=10,
                text_search="test search string"
824 825
            ).data,
            expected_result
826 827
        )
        self.assert_last_query_params({
828
            "user_id": [unicode(self.user.id)],
829
            "course_id": [unicode(self.course.id)],
830
            "sort_key": ["activity"],
831 832 833 834 835
            "page": ["1"],
            "per_page": ["10"],
            "text": ["test search string"],
        })

836
    def test_following(self):
837
        self.register_subscribed_threads_response(self.user, [], page=1, num_pages=0)
838 839 840 841 842 843
        result = get_thread_list(
            self.request,
            self.course.id,
            page=1,
            page_size=11,
            following=True,
844 845
        ).data

846 847 848
        expected_result = make_paginated_api_response(
            results=[], count=0, num_pages=0, next_link=None, previous_link=None
        )
849
        expected_result.update({"text_search_rewrite": None})
850 851
        self.assertEqual(
            result,
852
            expected_result
853 854 855 856 857 858
        )
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/users/{}/subscribed_threads".format(self.user.id)
        )
        self.assert_last_query_params({
859
            "user_id": [unicode(self.user.id)],
860
            "course_id": [unicode(self.course.id)],
861
            "sort_key": ["activity"],
862 863 864 865
            "page": ["1"],
            "per_page": ["11"],
        })

866 867
    @ddt.data("unanswered", "unread")
    def test_view_query(self, query):
868
        self.register_get_threads_response([], page=1, num_pages=0)
869 870 871 872 873 874
        result = get_thread_list(
            self.request,
            self.course.id,
            page=1,
            page_size=11,
            view=query,
875 876 877
        ).data

        expected_result = make_paginated_api_response(
878
            results=[], count=0, num_pages=0, next_link=None, previous_link=None
879
        )
880
        expected_result.update({"text_search_rewrite": None})
881 882
        self.assertEqual(
            result,
883
            expected_result
884 885 886 887 888 889 890 891
        )
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/threads"
        )
        self.assert_last_query_params({
            "user_id": [unicode(self.user.id)],
            "course_id": [unicode(self.course.id)],
892
            "sort_key": ["activity"],
893 894 895 896 897
            "page": ["1"],
            "per_page": ["11"],
            query: ["true"],
        })

898
    @ddt.data(
899
        ("last_activity_at", "activity"),
900 901 902 903 904 905 906 907 908 909 910 911
        ("comment_count", "comments"),
        ("vote_count", "votes")
    )
    @ddt.unpack
    def test_order_by_query(self, http_query, cc_query):
        """
        Tests the order_by parameter

        Arguments:
            http_query (str): Query string sent in the http request
            cc_query (str): Query string used for the comments client service
        """
912
        self.register_get_threads_response([], page=1, num_pages=0)
913 914 915 916 917 918
        result = get_thread_list(
            self.request,
            self.course.id,
            page=1,
            page_size=11,
            order_by=http_query,
919 920
        ).data

921 922 923
        expected_result = make_paginated_api_response(
            results=[], count=0, num_pages=0, next_link=None, previous_link=None
        )
924 925
        expected_result.update({"text_search_rewrite": None})
        self.assertEqual(result, expected_result)
926 927 928 929 930 931 932 933 934 935 936 937
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/threads"
        )
        self.assert_last_query_params({
            "user_id": [unicode(self.user.id)],
            "course_id": [unicode(self.course.id)],
            "sort_key": [cc_query],
            "page": ["1"],
            "per_page": ["11"],
        })

938 939 940 941 942
    def test_order_direction(self):
        """
        Only "desc" is supported for order.  Also, since it is simply swallowed,
        it isn't included in the params.
        """
943
        self.register_get_threads_response([], page=1, num_pages=0)
944 945 946 947 948
        result = get_thread_list(
            self.request,
            self.course.id,
            page=1,
            page_size=11,
949
            order_direction="desc",
950 951
        ).data

952 953 954
        expected_result = make_paginated_api_response(
            results=[], count=0, num_pages=0, next_link=None, previous_link=None
        )
955 956
        expected_result.update({"text_search_rewrite": None})
        self.assertEqual(result, expected_result)
957 958 959 960 961 962 963
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/threads"
        )
        self.assert_last_query_params({
            "user_id": [unicode(self.user.id)],
            "course_id": [unicode(self.course.id)],
964
            "sort_key": ["activity"],
965 966 967 968
            "page": ["1"],
            "per_page": ["11"],
        })

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    def test_invalid_order_direction(self):
        """
        Test with invalid order_direction (e.g. "asc")
        """
        with self.assertRaises(ValidationError) as assertion:
            self.register_get_threads_response([], page=1, num_pages=0)
            get_thread_list(           # pylint: disable=expression-not-assigned
                self.request,
                self.course.id,
                page=1,
                page_size=11,
                order_direction="asc",
            ).data
        self.assertIn("order_direction", assertion.exception.message_dict)

984

985
@attr(shard=2)
986
@ddt.ddt
987
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
988
class GetCommentListTest(ForumsEnableMixin, CommentsServiceMockMixin, SharedModuleStoreTestCase):
989
    """Test for get_comment_list"""
990 991 992 993 994 995

    @classmethod
    def setUpClass(cls):
        super(GetCommentListTest, cls).setUpClass()
        cls.course = CourseFactory.create()

996
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
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
    def setUp(self):
        super(GetCommentListTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
        self.maxDiff = None  # pylint: disable=invalid-name
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
        self.author = UserFactory.create()

    def make_minimal_cs_thread(self, overrides=None):
        """
        Create a thread with the given overrides, plus the course_id if not
        already in overrides.
        """
        overrides = overrides.copy() if overrides else {}
        overrides.setdefault("course_id", unicode(self.course.id))
        return make_minimal_cs_thread(overrides)

    def get_comment_list(self, thread, endorsed=None, page=1, page_size=1):
        """
        Register the appropriate comments service response, then call
        get_comment_list and return the result.
        """
        self.register_get_thread_response(thread)
        return get_comment_list(self.request, thread["id"], endorsed, page, page_size)

    def test_nonexistent_thread(self):
        thread_id = "nonexistent_thread"
        self.register_get_thread_error_response(thread_id, 404)
1030
        with self.assertRaises(ThreadNotFoundError):
1031 1032 1033
            get_comment_list(self.request, thread_id, endorsed=False, page=1, page_size=1)

    def test_nonexistent_course(self):
1034
        with self.assertRaises(CourseNotFoundError):
1035 1036 1037 1038
            self.get_comment_list(self.make_minimal_cs_thread({"course_id": "non/existent/course"}))

    def test_not_enrolled(self):
        self.request.user = UserFactory.create()
1039
        with self.assertRaises(CourseNotFoundError):
1040 1041 1042
            self.get_comment_list(self.make_minimal_cs_thread())

    def test_discussions_disabled(self):
1043
        disabled_course = _discussion_disabled_course_for(self.user)
1044
        with self.assertRaises(DiscussionDisabledError):
1045 1046 1047 1048 1049
            self.get_comment_list(
                self.make_minimal_cs_thread(
                    overrides={"course_id": unicode(disabled_course.id)}
                )
            )
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
1060
            [True, False],
1061 1062 1063 1064
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    def test_group_access(
            self,
            role_name,
            course_is_cohorted,
            topic_is_cohorted,
            thread_group_state
    ):
        cohort_course = CourseFactory.create(
            discussion_topics={"Test Topic": {"id": "test_topic"}},
            cohort_config={
                "cohorted": course_is_cohorted,
                "cohorted_discussions": ["test_topic"] if topic_is_cohorted else [],
            }
        )
1079 1080 1081 1082 1083 1084
        CourseEnrollmentFactory.create(user=self.user, course_id=cohort_course.id)
        cohort = CohortFactory.create(course_id=cohort_course.id, users=[self.user])
        role = Role.objects.create(name=role_name, course_id=cohort_course.id)
        role.users = [self.user]
        thread = self.make_minimal_cs_thread({
            "course_id": unicode(cohort_course.id),
1085
            "commentable_id": "test_topic",
1086 1087 1088 1089 1090 1091 1092 1093 1094
            "group_id": (
                None if thread_group_state == "no_group" else
                cohort.id if thread_group_state == "match_group" else
                cohort.id + 1
            ),
        })
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
1095
            topic_is_cohorted and
1096 1097 1098 1099 1100
            thread_group_state == "different_group"
        )
        try:
            self.get_comment_list(thread)
            self.assertFalse(expected_error)
1101
        except ThreadNotFoundError:
1102 1103 1104 1105 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
            self.assertTrue(expected_error)

    @ddt.data(True, False)
    def test_discussion_endorsed(self, endorsed_value):
        with self.assertRaises(ValidationError) as assertion:
            self.get_comment_list(
                self.make_minimal_cs_thread({"thread_type": "discussion"}),
                endorsed=endorsed_value
            )
        self.assertEqual(
            assertion.exception.message_dict,
            {"endorsed": ["This field may not be specified for discussion threads."]}
        )

    def test_question_without_endorsed(self):
        with self.assertRaises(ValidationError) as assertion:
            self.get_comment_list(
                self.make_minimal_cs_thread({"thread_type": "question"}),
                endorsed=None
            )
        self.assertEqual(
            assertion.exception.message_dict,
            {"endorsed": ["This field is required for question threads."]}
        )

    def test_empty(self):
        discussion_thread = self.make_minimal_cs_thread(
            {"thread_type": "discussion", "children": [], "resp_total": 0}
        )
        self.assertEqual(
1132
            self.get_comment_list(discussion_thread).data,
1133
            make_paginated_api_response(results=[], count=0, num_pages=1, next_link=None, previous_link=None)
1134 1135 1136 1137 1138 1139 1140 1141 1142
        )

        question_thread = self.make_minimal_cs_thread({
            "thread_type": "question",
            "endorsed_responses": [],
            "non_endorsed_responses": [],
            "non_endorsed_resp_total": 0
        })
        self.assertEqual(
1143
            self.get_comment_list(question_thread, endorsed=False).data,
1144
            make_paginated_api_response(results=[], count=0, num_pages=1, next_link=None, previous_link=None)
1145 1146
        )
        self.assertEqual(
1147
            self.get_comment_list(question_thread, endorsed=True).data,
1148
            make_paginated_api_response(results=[], count=0, num_pages=1, next_link=None, previous_link=None)
1149 1150 1151 1152 1153
        )

    def test_basic_query_params(self):
        self.get_comment_list(
            self.make_minimal_cs_thread({
1154
                "children": [make_minimal_cs_comment({"username": self.user.username})],
1155 1156 1157 1158 1159 1160 1161 1162 1163
                "resp_total": 71
            }),
            page=6,
            page_size=14
        )
        self.assert_query_params_equal(
            httpretty.httpretty.latest_requests[-2],
            {
                "user_id": [str(self.user.id)],
1164
                "mark_as_read": ["False"],
1165
                "recursive": ["False"],
1166 1167
                "resp_skip": ["70"],
                "resp_limit": ["14"],
1168
                "with_responses": ["True"],
1169 1170 1171 1172 1173 1174
            }
        )

    def test_discussion_content(self):
        source_comments = [
            {
1175
                "type": "comment",
1176 1177 1178 1179 1180 1181 1182 1183 1184
                "id": "test_comment_1",
                "thread_id": "test_thread",
                "user_id": str(self.author.id),
                "username": self.author.username,
                "anonymous": False,
                "anonymous_to_peers": False,
                "created_at": "2015-05-11T00:00:00Z",
                "updated_at": "2015-05-11T11:11:11Z",
                "body": "Test body",
1185
                "endorsed": False,
1186 1187
                "abuse_flaggers": [],
                "votes": {"up_count": 4},
1188
                "child_count": 0,
1189 1190 1191
                "children": [],
            },
            {
1192
                "type": "comment",
1193 1194 1195 1196 1197 1198 1199 1200 1201
                "id": "test_comment_2",
                "thread_id": "test_thread",
                "user_id": str(self.author.id),
                "username": self.author.username,
                "anonymous": True,
                "anonymous_to_peers": False,
                "created_at": "2015-05-11T22:22:22Z",
                "updated_at": "2015-05-11T33:33:33Z",
                "body": "More content",
1202
                "endorsed": False,
1203 1204
                "abuse_flaggers": [str(self.user.id)],
                "votes": {"up_count": 7},
1205
                "child_count": 0,
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
                "children": [],
            }
        ]
        expected_comments = [
            {
                "id": "test_comment_1",
                "thread_id": "test_thread",
                "parent_id": None,
                "author": self.author.username,
                "author_label": None,
                "created_at": "2015-05-11T00:00:00Z",
                "updated_at": "2015-05-11T11:11:11Z",
                "raw_body": "Test body",
1219
                "rendered_body": "<p>Test body</p>",
1220 1221 1222 1223
                "endorsed": False,
                "endorsed_by": None,
                "endorsed_by_label": None,
                "endorsed_at": None,
1224 1225 1226
                "abuse_flagged": False,
                "voted": False,
                "vote_count": 4,
1227
                "editable_fields": ["abuse_flagged", "voted"],
1228
                "child_count": 0,
1229
                "children": [],
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
            },
            {
                "id": "test_comment_2",
                "thread_id": "test_thread",
                "parent_id": None,
                "author": None,
                "author_label": None,
                "created_at": "2015-05-11T22:22:22Z",
                "updated_at": "2015-05-11T33:33:33Z",
                "raw_body": "More content",
1240
                "rendered_body": "<p>More content</p>",
1241 1242 1243 1244
                "endorsed": False,
                "endorsed_by": None,
                "endorsed_by_label": None,
                "endorsed_at": None,
1245 1246 1247
                "abuse_flagged": True,
                "voted": False,
                "vote_count": 7,
1248
                "editable_fields": ["abuse_flagged", "voted"],
1249
                "child_count": 0,
1250
                "children": [],
1251 1252 1253 1254
            },
        ]
        actual_comments = self.get_comment_list(
            self.make_minimal_cs_thread({"children": source_comments})
1255
        ).data["results"]
1256 1257 1258 1259 1260
        self.assertEqual(actual_comments, expected_comments)

    def test_question_content(self):
        thread = self.make_minimal_cs_thread({
            "thread_type": "question",
1261 1262 1263 1264
            "endorsed_responses": [make_minimal_cs_comment({"id": "endorsed_comment", "username": self.user.username})],
            "non_endorsed_responses": [make_minimal_cs_comment({
                "id": "non_endorsed_comment", "username": self.user.username
            })],
1265 1266 1267
            "non_endorsed_resp_total": 1,
        })

1268
        endorsed_actual = self.get_comment_list(thread, endorsed=True).data
1269 1270
        self.assertEqual(endorsed_actual["results"][0]["id"], "endorsed_comment")

1271
        non_endorsed_actual = self.get_comment_list(thread, endorsed=False).data
1272 1273
        self.assertEqual(non_endorsed_actual["results"][0]["id"], "non_endorsed_comment")

1274 1275 1276 1277 1278 1279 1280 1281 1282
    def test_endorsed_by_anonymity(self):
        """
        Ensure thread anonymity is properly considered in serializing
        endorsed_by.
        """
        thread = self.make_minimal_cs_thread({
            "anonymous": True,
            "children": [
                make_minimal_cs_comment({
1283 1284
                    "username": self.user.username,
                    "endorsement": {"user_id": str(self.author.id), "time": "2015-05-18T12:34:56Z"},
1285 1286 1287
                })
            ]
        })
1288
        actual_comments = self.get_comment_list(thread).data["results"]
1289 1290
        self.assertIsNone(actual_comments[0]["endorsed_by"])

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    @ddt.data(
        ("discussion", None, "children", "resp_total"),
        ("question", False, "non_endorsed_responses", "non_endorsed_resp_total"),
    )
    @ddt.unpack
    def test_cs_pagination(self, thread_type, endorsed_arg, response_field, response_total_field):
        """
        Test cases in which pagination is done by the comments service.

        thread_type is the type of thread (question or discussion).
        endorsed_arg is the value of the endorsed argument.
        repsonse_field is the field in which responses are returned for the
          given thread type.
        response_total_field is the field in which the total number of responses
          is returned for the given thread type.
        """
        # N.B. The mismatch between the number of children and the listed total
        # number of responses is unrealistic but convenient for this test
        thread = self.make_minimal_cs_thread({
            "thread_type": thread_type,
1311
            response_field: [make_minimal_cs_comment({"username": self.user.username})],
1312 1313 1314 1315
            response_total_field: 5,
        })

        # Only page
1316 1317 1318
        actual = self.get_comment_list(thread, endorsed=endorsed_arg, page=1, page_size=5).data
        self.assertIsNone(actual["pagination"]["next"])
        self.assertIsNone(actual["pagination"]["previous"])
1319 1320

        # First page of many
1321 1322 1323
        actual = self.get_comment_list(thread, endorsed=endorsed_arg, page=1, page_size=2).data
        self.assertEqual(actual["pagination"]["next"], "http://testserver/test_path?page=2")
        self.assertIsNone(actual["pagination"]["previous"])
1324 1325

        # Middle page of many
1326 1327 1328
        actual = self.get_comment_list(thread, endorsed=endorsed_arg, page=2, page_size=2).data
        self.assertEqual(actual["pagination"]["next"], "http://testserver/test_path?page=3")
        self.assertEqual(actual["pagination"]["previous"], "http://testserver/test_path?page=1")
1329 1330

        # Last page of many
1331 1332 1333
        actual = self.get_comment_list(thread, endorsed=endorsed_arg, page=3, page_size=2).data
        self.assertIsNone(actual["pagination"]["next"])
        self.assertEqual(actual["pagination"]["previous"], "http://testserver/test_path?page=2")
1334 1335 1336 1337 1338 1339 1340

        # Page past the end
        thread = self.make_minimal_cs_thread({
            "thread_type": thread_type,
            response_field: [],
            response_total_field: 5
        })
1341
        with self.assertRaises(PageNotFoundError):
1342 1343 1344 1345 1346
            self.get_comment_list(thread, endorsed=endorsed_arg, page=2, page_size=5)

    def test_question_endorsed_pagination(self):
        thread = self.make_minimal_cs_thread({
            "thread_type": "question",
1347 1348 1349 1350
            "endorsed_responses": [make_minimal_cs_comment({
                "id": "comment_{}".format(i),
                "username": self.user.username
            }) for i in range(10)]
1351 1352 1353 1354 1355 1356 1357
        })

        def assert_page_correct(page, page_size, expected_start, expected_stop, expected_next, expected_prev):
            """
            Check that requesting the given page/page_size returns the expected
            output
            """
1358
            actual = self.get_comment_list(thread, endorsed=True, page=page, page_size=page_size).data
1359 1360 1361 1362 1363 1364
            result_ids = [result["id"] for result in actual["results"]]
            self.assertEqual(
                result_ids,
                ["comment_{}".format(i) for i in range(expected_start, expected_stop)]
            )
            self.assertEqual(
1365
                actual["pagination"]["next"],
1366 1367 1368
                "http://testserver/test_path?page={}".format(expected_next) if expected_next else None
            )
            self.assertEqual(
1369
                actual["pagination"]["previous"],
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
                "http://testserver/test_path?page={}".format(expected_prev) if expected_prev else None
            )

        # Only page
        assert_page_correct(
            page=1,
            page_size=10,
            expected_start=0,
            expected_stop=10,
            expected_next=None,
            expected_prev=None
        )

        # First page of many
        assert_page_correct(
            page=1,
            page_size=4,
            expected_start=0,
            expected_stop=4,
            expected_next=2,
            expected_prev=None
        )

        # Middle page of many
        assert_page_correct(
            page=2,
            page_size=4,
            expected_start=4,
            expected_stop=8,
            expected_next=3,
            expected_prev=1
        )

        # Last page of many
        assert_page_correct(
            page=3,
            page_size=4,
            expected_start=8,
            expected_stop=10,
            expected_next=None,
            expected_prev=2
        )

        # Page past the end
1414
        with self.assertRaises(PageNotFoundError):
1415
            self.get_comment_list(thread, endorsed=True, page=2, page_size=10)
1416 1417


1418
@attr(shard=2)
1419
@ddt.ddt
1420 1421
@disable_signal(api, 'thread_created')
@disable_signal(api, 'thread_voted')
1422
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
1423
class CreateThreadTest(
1424
        ForumsEnableMixin,
1425 1426 1427 1428 1429
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase,
        MockSignalHandlerMixin
):
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
    LONG_TITLE = (
        'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '
        'Aenean commodo ligula eget dolor. Aenean massa. Cum sociis '
        'natoque penatibus et magnis dis parturient montes, nascetur '
        'ridiculus mus. Donec quam felis, ultricies nec, '
        'pellentesque eu, pretium quis, sem. Nulla consequat massa '
        'quis enim. Donec pede justo, fringilla vel, aliquet nec, '
        'vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet '
        'a, venenatis vitae, justo. Nullam dictum felis eu pede '
        'mollis pretium. Integer tincidunt. Cras dapibus. Vivamus '
        'elementum semper nisi. Aenean vulputate eleifend tellus. '
        'Aenean leo ligula, porttitor eu, consequat vitae, eleifend '
        'ac, enim. Aliquam lorem ante, dapibus in, viverra quis, '
        'feugiat a, tellus. Phasellus viverra nulla ut metus varius '
        'laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies '
        'nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam '
        'eget dui. Etiam rhoncus. Maecenas tempus, tellus eget '
        'condimentum rhoncus, sem quam semper libero, sit amet '
        'adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, '
        'luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et '
        'ante tincidunt tempus. Donec vitae sapien ut libero '
        'venenatis faucibus. Nullam quis ante. Etiam sit amet orci '
        'eget eros faucibus tincidunt. Duis leo. Sed fringilla '
        'mauris sit amet nibh. Donec sodales sagittis magna. Sed '
        'consequat, leo eget bibendum sodales, augue velit cursus '
        'nunc, quis gravida magna mi a libero. Fusce vulputate '
        'eleifend sapien. Vestibulum purus quam, scelerisque ut, '
        'mollis sed, nonummy id, metus. Nullam accumsan lorem in '
        'dui. Cras ultricies mi eu turpis hendrerit fringilla. '
        'Vestibulum ante ipsum primis in faucibus orci luctus et '
        'ultrices posuere cubilia Curae; In ac dui quis mi '
        'consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu '
        'tortor, suscipit eget, imperdiet nec, imperdiet iaculis, '
        'ipsum. Sed aliquam ultrices mauris. Integer ante arcu, '
        'accumsan a, consectetuer eget, posuere ut, mauris. Praesent '
        'adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc '
        'nonummy metus.'
    )

1469
    """Tests for create_thread"""
1470 1471 1472 1473 1474
    @classmethod
    def setUpClass(cls):
        super(CreateThreadTest, cls).setUpClass()
        cls.course = CourseFactory.create()

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(CreateThreadTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
        self.minimal_data = {
            "course_id": unicode(self.course.id),
            "topic_id": "test_topic",
            "type": "discussion",
            "title": "Test Title",
            "raw_body": "Test body",
        }

    @mock.patch("eventtracking.tracker.emit")
    def test_basic(self, mock_emit):
1496
        cs_thread = make_minimal_cs_thread({
1497 1498
            "id": "test_id",
            "username": self.user.username,
1499
            "read": True,
1500
        })
1501
        self.register_post_thread_response(cs_thread)
1502 1503
        with self.assert_signal_sent(api, 'thread_created', sender=None, user=self.user, exclude_args=('post',)):
            actual = create_thread(self.request, self.minimal_data)
1504
        expected = self.expected_thread_data({
1505 1506 1507
            "id": "test_id",
            "course_id": unicode(self.course.id),
            "comment_list_url": "http://testserver/api/discussion/v1/comments/?thread_id=test_id",
1508 1509
            "read": True,
        })
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
        self.assertEqual(actual, expected)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "commentable_id": ["test_topic"],
                "thread_type": ["discussion"],
                "title": ["Test Title"],
                "body": ["Test body"],
                "user_id": [str(self.user.id)],
            }
        )
        event_name, event_data = mock_emit.call_args[0]
        self.assertEqual(event_name, "edx.forum.thread.created")
        self.assertEqual(
            event_data,
            {
                "commentable_id": "test_topic",
                "group_id": None,
                "thread_type": "discussion",
                "title": "Test Title",
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
                "title_truncated": False,
                "anonymous": False,
                "anonymous_to_peers": False,
                "options": {"followed": False},
                "id": "test_id",
                "truncated": False,
                "body": "Test body",
                "url": "",
                "user_forums_roles": [FORUM_ROLE_STUDENT],
                "user_course_roles": [],
            }
        )

    @mock.patch("eventtracking.tracker.emit")
    def test_title_truncation(self, mock_emit):
        data = self.minimal_data.copy()
        data['title'] = self.LONG_TITLE

        cs_thread = make_minimal_cs_thread({
            "id": "test_id",
            "username": self.user.username,
            "read": True,
        })
        self.register_post_thread_response(cs_thread)
        with self.assert_signal_sent(api, 'thread_created', sender=None, user=self.user, exclude_args=('post',)):
            actual = create_thread(self.request, data)
        event_name, event_data = mock_emit.call_args[0]
        self.assertEqual(event_name, "edx.forum.thread.created")
        self.assertEqual(
            event_data,
            {
                "commentable_id": "test_topic",
                "group_id": None,
                "thread_type": "discussion",
                "title": self.LONG_TITLE[:1000],
                "title_truncated": True,
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
                "anonymous": False,
                "anonymous_to_peers": False,
                "options": {"followed": False},
                "id": "test_id",
                "truncated": False,
                "body": "Test body",
                "url": "",
                "user_forums_roles": [FORUM_ROLE_STUDENT],
                "user_course_roles": [],
            }
        )

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            [True, False],
            ["no_group_set", "group_is_none", "group_is_set"],
        )
    )
    @ddt.unpack
    def test_group_id(self, role_name, course_is_cohorted, topic_is_cohorted, data_group_state):
        """
        Tests whether the user has permission to create a thread with certain
        group_id values.

        If there is no group, user cannot create a thread.
        Else if group is None or set, and the course is not cohorted and/or the
        role is a student, user can create a thread.
        """

        cohort_course = CourseFactory.create(
            discussion_topics={"Test Topic": {"id": "test_topic"}},
            cohort_config={
                "cohorted": course_is_cohorted,
                "cohorted_discussions": ["test_topic"] if topic_is_cohorted else [],
            }
        )
        CourseEnrollmentFactory.create(user=self.user, course_id=cohort_course.id)
        if course_is_cohorted:
            cohort = CohortFactory.create(course_id=cohort_course.id, users=[self.user])
        role = Role.objects.create(name=role_name, course_id=cohort_course.id)
        role.users = [self.user]
1615
        self.register_post_thread_response({"username": self.user.username})
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
        data = self.minimal_data.copy()
        data["course_id"] = unicode(cohort_course.id)
        if data_group_state == "group_is_none":
            data["group_id"] = None
        elif data_group_state == "group_is_set":
            if course_is_cohorted:
                data["group_id"] = cohort.id + 1
            else:
                data["group_id"] = 1  # Set to any value since there is no cohort
        expected_error = (
            data_group_state in ["group_is_none", "group_is_set"] and
            (not course_is_cohorted or role_name == FORUM_ROLE_STUDENT)
        )
        try:
            create_thread(self.request, data)
            self.assertFalse(expected_error)
            actual_post_data = httpretty.last_request().parsed_body
            if data_group_state == "group_is_set":
                self.assertEqual(actual_post_data["group_id"], [str(data["group_id"])])
            elif data_group_state == "no_group_set" and course_is_cohorted and topic_is_cohorted:
                self.assertEqual(actual_post_data["group_id"], [str(cohort.id)])
            else:
                self.assertNotIn("group_id", actual_post_data)
1639 1640 1641
        except ValidationError as ex:
            if not expected_error:
                self.fail("Unexpected validation error: {}".format(ex))
1642

1643
    def test_following(self):
1644
        self.register_post_thread_response({"id": "test_id", "username": self.user.username})
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
        self.register_subscription_response(self.user)
        data = self.minimal_data.copy()
        data["following"] = "True"
        result = create_thread(self.request, data)
        self.assertEqual(result["following"], True)
        cs_request = httpretty.last_request()
        self.assertEqual(
            urlparse(cs_request.path).path,
            "/api/v1/users/{}/subscriptions".format(self.user.id)
        )
1655
        self.assertEqual(cs_request.method, "POST")
1656 1657 1658 1659 1660
        self.assertEqual(
            cs_request.parsed_body,
            {"source_type": ["thread"], "source_id": ["test_id"]}
        )

1661
    def test_voted(self):
1662
        self.register_post_thread_response({"id": "test_id", "username": self.user.username})
1663 1664 1665
        self.register_thread_votes_response("test_id")
        data = self.minimal_data.copy()
        data["voted"] = "True"
1666 1667
        with self.assert_signal_sent(api, 'thread_voted', sender=None, user=self.user, exclude_args=('post',)):
            result = create_thread(self.request, data)
1668 1669 1670 1671 1672 1673 1674 1675 1676
        self.assertEqual(result["voted"], True)
        cs_request = httpretty.last_request()
        self.assertEqual(urlparse(cs_request.path).path, "/api/v1/threads/test_id/votes")
        self.assertEqual(cs_request.method, "PUT")
        self.assertEqual(
            cs_request.parsed_body,
            {"user_id": [str(self.user.id)], "value": ["up"]}
        )

1677
    def test_abuse_flagged(self):
1678
        self.register_post_thread_response({"id": "test_id", "username": self.user.username})
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
        self.register_thread_flag_response("test_id")
        data = self.minimal_data.copy()
        data["abuse_flagged"] = "True"
        result = create_thread(self.request, data)
        self.assertEqual(result["abuse_flagged"], True)
        cs_request = httpretty.last_request()
        self.assertEqual(urlparse(cs_request.path).path, "/api/v1/threads/test_id/abuse_flag")
        self.assertEqual(cs_request.method, "PUT")
        self.assertEqual(cs_request.parsed_body, {"user_id": [str(self.user.id)]})

1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
    def test_course_id_missing(self):
        with self.assertRaises(ValidationError) as assertion:
            create_thread(self.request, {})
        self.assertEqual(assertion.exception.message_dict, {"course_id": ["This field is required."]})

    def test_course_id_invalid(self):
        with self.assertRaises(ValidationError) as assertion:
            create_thread(self.request, {"course_id": "invalid!"})
        self.assertEqual(assertion.exception.message_dict, {"course_id": ["Invalid value."]})

    def test_nonexistent_course(self):
1700
        with self.assertRaises(CourseNotFoundError):
1701 1702 1703 1704
            create_thread(self.request, {"course_id": "non/existent/course"})

    def test_not_enrolled(self):
        self.request.user = UserFactory.create()
1705
        with self.assertRaises(CourseNotFoundError):
1706 1707 1708
            create_thread(self.request, self.minimal_data)

    def test_discussions_disabled(self):
1709 1710
        disabled_course = _discussion_disabled_course_for(self.user)
        self.minimal_data["course_id"] = unicode(disabled_course.id)
1711
        with self.assertRaises(DiscussionDisabledError):
1712 1713 1714 1715 1716 1717 1718
            create_thread(self.request, self.minimal_data)

    def test_invalid_field(self):
        data = self.minimal_data.copy()
        data["type"] = "invalid_type"
        with self.assertRaises(ValidationError):
            create_thread(self.request, data)
1719 1720


1721
@attr(shard=2)
1722
@ddt.ddt
1723 1724
@disable_signal(api, 'comment_created')
@disable_signal(api, 'comment_voted')
1725
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
1726
class CreateCommentTest(
1727
        ForumsEnableMixin,
1728 1729 1730 1731 1732
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase,
        MockSignalHandlerMixin
):
1733
    """Tests for create_comment"""
1734 1735 1736 1737 1738
    @classmethod
    def setUpClass(cls):
        super(CreateCommentTest, cls).setUpClass()
        cls.course = CourseFactory.create()

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(CreateCommentTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
        self.register_get_thread_response(
            make_minimal_cs_thread({
                "id": "test_thread",
                "course_id": unicode(self.course.id),
                "commentable_id": "test_topic",
            })
        )
        self.minimal_data = {
            "thread_id": "test_thread",
            "raw_body": "Test body",
        }

    @ddt.data(None, "test_parent")
    @mock.patch("eventtracking.tracker.emit")
    def test_success(self, parent_id, mock_emit):
        if parent_id:
            self.register_get_comment_response({"id": parent_id, "thread_id": "test_thread"})
        self.register_post_comment_response(
            {
                "id": "test_comment",
                "username": self.user.username,
                "created_at": "2015-05-27T00:00:00Z",
                "updated_at": "2015-05-27T00:00:00Z",
            },
1774
            thread_id="test_thread",
1775 1776 1777 1778 1779
            parent_id=parent_id
        )
        data = self.minimal_data.copy()
        if parent_id:
            data["parent_id"] = parent_id
1780 1781
        with self.assert_signal_sent(api, 'comment_created', sender=None, user=self.user, exclude_args=('post',)):
            actual = create_comment(self.request, data)
1782 1783 1784 1785 1786 1787 1788 1789 1790
        expected = {
            "id": "test_comment",
            "thread_id": "test_thread",
            "parent_id": parent_id,
            "author": self.user.username,
            "author_label": None,
            "created_at": "2015-05-27T00:00:00Z",
            "updated_at": "2015-05-27T00:00:00Z",
            "raw_body": "Test body",
1791
            "rendered_body": "<p>Test body</p>",
1792 1793 1794 1795 1796 1797 1798 1799
            "endorsed": False,
            "endorsed_by": None,
            "endorsed_by_label": None,
            "endorsed_at": None,
            "abuse_flagged": False,
            "voted": False,
            "vote_count": 0,
            "children": [],
1800 1801
            "editable_fields": ["abuse_flagged", "raw_body", "voted"],
            "child_count": 0,
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
        }
        self.assertEqual(actual, expected)
        expected_url = (
            "/api/v1/comments/{}".format(parent_id) if parent_id else
            "/api/v1/threads/test_thread/comments"
        )
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            expected_url
        )
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "body": ["Test body"],
                "user_id": [str(self.user.id)]
            }
        )
        expected_event_name = (
            "edx.forum.comment.created" if parent_id else
            "edx.forum.response.created"
        )
        expected_event_data = {
            "discussion": {"id": "test_thread"},
            "commentable_id": "test_topic",
            "options": {"followed": False},
            "id": "test_comment",
            "truncated": False,
            "body": "Test body",
            "url": "",
            "user_forums_roles": [FORUM_ROLE_STUDENT],
            "user_course_roles": [],
        }
        if parent_id:
            expected_event_data["response"] = {"id": parent_id}
        actual_event_name, actual_event_data = mock_emit.call_args[0]
        self.assertEqual(actual_event_name, expected_event_name)
        self.assertEqual(actual_event_data, expected_event_data)

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["question", "discussion"],
        )
    )
    @ddt.unpack
    def test_endorsed(self, role_name, is_thread_author, thread_type):
        role = Role.objects.create(name=role_name, course_id=self.course.id)
        role.users = [self.user]
        self.register_get_thread_response(
            make_minimal_cs_thread({
                "id": "test_thread",
                "course_id": unicode(self.course.id),
                "thread_type": thread_type,
                "user_id": str(self.user.id) if is_thread_author else str(self.user.id + 1),
            })
        )
1865
        self.register_post_comment_response({"username": self.user.username}, "test_thread")
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
        data = self.minimal_data.copy()
        data["endorsed"] = True
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            (not is_thread_author or thread_type == "discussion")
        )
        try:
            create_comment(self.request, data)
            self.assertEqual(httpretty.last_request().parsed_body["endorsed"], ["True"])
            self.assertFalse(expected_error)
        except ValidationError:
            self.assertTrue(expected_error)

1879
    def test_voted(self):
1880
        self.register_post_comment_response({"id": "test_comment", "username": self.user.username}, "test_thread")
1881 1882 1883
        self.register_comment_votes_response("test_comment")
        data = self.minimal_data.copy()
        data["voted"] = "True"
1884 1885
        with self.assert_signal_sent(api, 'comment_voted', sender=None, user=self.user, exclude_args=('post',)):
            result = create_comment(self.request, data)
1886 1887 1888 1889 1890 1891 1892 1893 1894
        self.assertEqual(result["voted"], True)
        cs_request = httpretty.last_request()
        self.assertEqual(urlparse(cs_request.path).path, "/api/v1/comments/test_comment/votes")
        self.assertEqual(cs_request.method, "PUT")
        self.assertEqual(
            cs_request.parsed_body,
            {"user_id": [str(self.user.id)], "value": ["up"]}
        )

1895
    def test_abuse_flagged(self):
1896
        self.register_post_comment_response({"id": "test_comment", "username": self.user.username}, "test_thread")
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
        self.register_comment_flag_response("test_comment")
        data = self.minimal_data.copy()
        data["abuse_flagged"] = "True"
        result = create_comment(self.request, data)
        self.assertEqual(result["abuse_flagged"], True)
        cs_request = httpretty.last_request()
        self.assertEqual(urlparse(cs_request.path).path, "/api/v1/comments/test_comment/abuse_flag")
        self.assertEqual(cs_request.method, "PUT")
        self.assertEqual(cs_request.parsed_body, {"user_id": [str(self.user.id)]})

1907 1908 1909 1910 1911 1912 1913
    def test_thread_id_missing(self):
        with self.assertRaises(ValidationError) as assertion:
            create_comment(self.request, {})
        self.assertEqual(assertion.exception.message_dict, {"thread_id": ["This field is required."]})

    def test_thread_id_not_found(self):
        self.register_get_thread_error_response("test_thread", 404)
1914
        with self.assertRaises(ThreadNotFoundError):
1915 1916 1917 1918 1919 1920
            create_comment(self.request, self.minimal_data)

    def test_nonexistent_course(self):
        self.register_get_thread_response(
            make_minimal_cs_thread({"id": "test_thread", "course_id": "non/existent/course"})
        )
1921
        with self.assertRaises(CourseNotFoundError):
1922 1923 1924 1925
            create_comment(self.request, self.minimal_data)

    def test_not_enrolled(self):
        self.request.user = UserFactory.create()
1926
        with self.assertRaises(CourseNotFoundError):
1927 1928 1929
            create_comment(self.request, self.minimal_data)

    def test_discussions_disabled(self):
1930 1931 1932 1933 1934 1935 1936 1937
        disabled_course = _discussion_disabled_course_for(self.user)
        self.register_get_thread_response(
            make_minimal_cs_thread({
                "id": "test_thread",
                "course_id": unicode(disabled_course.id),
                "commentable_id": "test_topic",
            })
        )
1938
        with self.assertRaises(DiscussionDisabledError):
1939 1940
            create_comment(self.request, self.minimal_data)

1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
    def test_group_access(self, role_name, course_is_cohorted, thread_group_state):
1955
        cohort_course, cohort = _create_course_and_cohort_with_user_role(course_is_cohorted, self.user, role_name)
1956 1957 1958 1959 1960 1961 1962 1963 1964
        self.register_get_thread_response(make_minimal_cs_thread({
            "id": "cohort_thread",
            "course_id": unicode(cohort_course.id),
            "group_id": (
                None if thread_group_state == "no_group" else
                cohort.id if thread_group_state == "match_group" else
                cohort.id + 1
            ),
        }))
1965
        self.register_post_comment_response({"username": self.user.username}, thread_id="cohort_thread")
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
        data = self.minimal_data.copy()
        data["thread_id"] = "cohort_thread"
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
            thread_group_state == "different_group"
        )
        try:
            create_comment(self.request, data)
            self.assertFalse(expected_error)
1976
        except ThreadNotFoundError:
1977 1978
            self.assertTrue(expected_error)

1979 1980 1981 1982 1983
    def test_invalid_field(self):
        data = self.minimal_data.copy()
        del data["raw_body"]
        with self.assertRaises(ValidationError):
            create_comment(self.request, data)
1984 1985


1986
@attr(shard=2)
1987
@ddt.ddt
1988 1989
@disable_signal(api, 'thread_edited')
@disable_signal(api, 'thread_voted')
1990
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
1991
class UpdateThreadTest(
1992
        ForumsEnableMixin,
1993 1994 1995 1996 1997
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase,
        MockSignalHandlerMixin
):
1998
    """Tests for update_thread"""
1999 2000 2001 2002 2003
    @classmethod
    def setUpClass(cls):
        super(UpdateThreadTest, cls).setUpClass()
        cls.course = CourseFactory.create()

2004 2005 2006 2007 2008 2009
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(UpdateThreadTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
2010

2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)

    def register_thread(self, overrides=None):
        """
        Make a thread with appropriate data overridden by the overrides
        parameter and register mock responses for both GET and PUT on its
        endpoint.
        """
        cs_data = make_minimal_cs_thread({
            "id": "test_thread",
            "course_id": unicode(self.course.id),
            "commentable_id": "original_topic",
            "username": self.user.username,
            "user_id": str(self.user.id),
2029
            "thread_type": "discussion",
2030 2031 2032 2033 2034 2035 2036
            "title": "Original Title",
            "body": "Original body",
        })
        cs_data.update(overrides or {})
        self.register_get_thread_response(cs_data)
        self.register_put_thread_response(cs_data)

2037 2038 2039 2040 2041 2042 2043 2044 2045
    def test_empty(self):
        """Check that an empty update does not make any modifying requests."""
        # Ensure that the default following value of False is not applied implicitly
        self.register_get_user_response(self.user, subscribed_thread_ids=["test_thread"])
        self.register_thread()
        update_thread(self.request, "test_thread", {})
        for request in httpretty.httpretty.latest_requests:
            self.assertEqual(request.method, "GET")

2046 2047
    def test_basic(self):
        self.register_thread()
2048 2049
        with self.assert_signal_sent(api, 'thread_edited', sender=None, user=self.user, exclude_args=('post',)):
            actual = update_thread(self.request, "test_thread", {"raw_body": "Edited body"})
2050 2051

        self.assertEqual(actual, self.expected_thread_data({
2052
            "raw_body": "Edited body",
2053
            "rendered_body": "<p>Edited body</p>",
2054 2055 2056 2057
            "topic_id": "original_topic",
            "read": True,
            "title": "Original Title",
        }))
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "commentable_id": ["original_topic"],
                "thread_type": ["discussion"],
                "title": ["Original Title"],
                "body": ["Edited body"],
                "user_id": [str(self.user.id)],
                "anonymous": ["False"],
                "anonymous_to_peers": ["False"],
                "closed": ["False"],
                "pinned": ["False"],
2071
                "read": ["False"],
2072 2073 2074 2075 2076
            }
        )

    def test_nonexistent_thread(self):
        self.register_get_thread_error_response("test_thread", 404)
2077
        with self.assertRaises(ThreadNotFoundError):
2078 2079 2080 2081
            update_thread(self.request, "test_thread", {})

    def test_nonexistent_course(self):
        self.register_thread({"course_id": "non/existent/course"})
2082
        with self.assertRaises(CourseNotFoundError):
2083 2084
            update_thread(self.request, "test_thread", {})

2085
    def test_not_enrolled(self):
2086 2087
        self.register_thread()
        self.request.user = UserFactory.create()
2088
        with self.assertRaises(CourseNotFoundError):
2089 2090 2091
            update_thread(self.request, "test_thread", {})

    def test_discussions_disabled(self):
2092 2093
        disabled_course = _discussion_disabled_course_for(self.user)
        self.register_thread(overrides={"course_id": unicode(disabled_course.id)})
2094
        with self.assertRaises(DiscussionDisabledError):
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
            update_thread(self.request, "test_thread", {})

    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
    def test_group_access(self, role_name, course_is_cohorted, thread_group_state):
2111
        cohort_course, cohort = _create_course_and_cohort_with_user_role(course_is_cohorted, self.user, role_name)
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
        self.register_thread({
            "course_id": unicode(cohort_course.id),
            "group_id": (
                None if thread_group_state == "no_group" else
                cohort.id if thread_group_state == "match_group" else
                cohort.id + 1
            ),
        })
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
            thread_group_state == "different_group"
        )
        try:
            update_thread(self.request, "test_thread", {})
            self.assertFalse(expected_error)
2128
        except ThreadNotFoundError:
2129 2130 2131 2132 2133 2134 2135 2136
            self.assertTrue(expected_error)

    @ddt.data(
        FORUM_ROLE_ADMINISTRATOR,
        FORUM_ROLE_MODERATOR,
        FORUM_ROLE_COMMUNITY_TA,
        FORUM_ROLE_STUDENT,
    )
2137
    def test_author_only_fields(self, role_name):
2138 2139 2140
        role = Role.objects.create(name=role_name, course_id=self.course.id)
        role.users = [self.user]
        self.register_thread({"user_id": str(self.user.id + 1)})
2141 2142
        data = {field: "edited" for field in ["topic_id", "title", "raw_body"]}
        data["type"] = "question"
2143 2144
        expected_error = role_name == FORUM_ROLE_STUDENT
        try:
2145
            update_thread(self.request, "test_thread", data)
2146
            self.assertFalse(expected_error)
2147
        except ValidationError as err:
2148
            self.assertTrue(expected_error)
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
            self.assertEqual(
                err.message_dict,
                {field: ["This field is not editable."] for field in data.keys()}
            )

    @ddt.data(*itertools.product([True, False], [True, False]))
    @ddt.unpack
    def test_following(self, old_following, new_following):
        """
        Test attempts to edit the "following" field.

        old_following indicates whether the thread should be followed at the
        start of the test. new_following indicates the value for the "following"
        field in the update. If old_following and new_following are the same, no
        update should be made. Otherwise, a subscription should be POSTed or
        DELETEd according to the new_following value.
        """
        if old_following:
            self.register_get_user_response(self.user, subscribed_thread_ids=["test_thread"])
        self.register_subscription_response(self.user)
        self.register_thread()
        data = {"following": new_following}
        result = update_thread(self.request, "test_thread", data)
        self.assertEqual(result["following"], new_following)
        last_request_path = urlparse(httpretty.last_request().path).path
        subscription_url = "/api/v1/users/{}/subscriptions".format(self.user.id)
        if old_following == new_following:
            self.assertNotEqual(last_request_path, subscription_url)
        else:
            self.assertEqual(last_request_path, subscription_url)
            self.assertEqual(
                httpretty.last_request().method,
                "POST" if new_following else "DELETE"
            )
            request_data = (
                httpretty.last_request().parsed_body if new_following else
                parse_qs(urlparse(httpretty.last_request().path).query)
            )
            request_data.pop("request_id", None)
            self.assertEqual(
                request_data,
                {"source_type": ["thread"], "source_id": ["test_thread"]}
            )
2192

2193 2194
    @ddt.data(*itertools.product([True, False], [True, False]))
    @ddt.unpack
2195 2196
    @mock.patch("eventtracking.tracker.emit")
    def test_voted(self, current_vote_status, new_vote_status, mock_emit):
2197 2198 2199
        """
        Test attempts to edit the "voted" field.

2200 2201 2202 2203 2204
        current_vote_status indicates whether the thread should be upvoted at
        the start of the test. new_vote_status indicates the value for the
        "voted" field in the update. If current_vote_status and new_vote_status
        are the same, no update should be made. Otherwise, a vote should be PUT
        or DELETEd according to the new_vote_status value.
2205
        """
2206
        if current_vote_status:
2207 2208 2209
            self.register_get_user_response(self.user, upvoted_ids=["test_thread"])
        self.register_thread_votes_response("test_thread")
        self.register_thread()
2210 2211 2212
        data = {"voted": new_vote_status}
        result = update_thread(self.request, "test_thread", data)
        self.assertEqual(result["voted"], new_vote_status)
2213 2214
        last_request_path = urlparse(httpretty.last_request().path).path
        votes_url = "/api/v1/threads/test_thread/votes"
2215
        if current_vote_status == new_vote_status:
2216 2217 2218 2219 2220
            self.assertNotEqual(last_request_path, votes_url)
        else:
            self.assertEqual(last_request_path, votes_url)
            self.assertEqual(
                httpretty.last_request().method,
2221
                "PUT" if new_vote_status else "DELETE"
2222 2223
            )
            actual_request_data = (
2224
                httpretty.last_request().parsed_body if new_vote_status else
2225 2226 2227 2228
                parse_qs(urlparse(httpretty.last_request().path).query)
            )
            actual_request_data.pop("request_id", None)
            expected_request_data = {"user_id": [str(self.user.id)]}
2229
            if new_vote_status:
2230 2231 2232
                expected_request_data["value"] = ["up"]
            self.assertEqual(actual_request_data, expected_request_data)

2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
            event_name, event_data = mock_emit.call_args[0]
            self.assertEqual(event_name, "edx.forum.thread.voted")
            self.assertEqual(
                event_data,
                {
                    'undo_vote': not new_vote_status,
                    'url': '',
                    'target_username': self.user.username,
                    'vote_value': 'up',
                    'user_forums_roles': [FORUM_ROLE_STUDENT],
                    'user_course_roles': [],
                    'commentable_id': 'original_topic',
                    'id': 'test_thread'
                }
            )

2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
    @ddt.data(*itertools.product([True, False], [True, False], [True, False]))
    @ddt.unpack
    def test_vote_count(self, current_vote_status, first_vote, second_vote):
        """
        Tests vote_count increases and decreases correctly from the same user
        """
        #setup
        starting_vote_count = 0
        if current_vote_status:
            self.register_get_user_response(self.user, upvoted_ids=["test_thread"])
            starting_vote_count = 1
        self.register_thread_votes_response("test_thread")
        self.register_thread(overrides={"votes": {"up_count": starting_vote_count}})

        #first vote
        data = {"voted": first_vote}
        result = update_thread(self.request, "test_thread", data)
        self.register_thread(overrides={"voted": first_vote})
        self.assertEqual(result["vote_count"], 1 if first_vote else 0)

        #second vote
        data = {"voted": second_vote}
        result = update_thread(self.request, "test_thread", data)
        self.assertEqual(result["vote_count"], 1 if second_vote else 0)

    @ddt.data(*itertools.product([True, False], [True, False], [True, False], [True, False]))
    @ddt.unpack
    def test_vote_count_two_users(
            self,
            current_user1_vote,
            current_user2_vote,
            user1_vote,
            user2_vote
    ):
        """
        Tests vote_count increases and decreases correctly from different users
        """
        #setup
        user2 = UserFactory.create()
        self.register_get_user_response(user2)
        request2 = RequestFactory().get("/test_path")
        request2.user = user2
        CourseEnrollmentFactory.create(user=user2, course_id=self.course.id)

        vote_count = 0
        if current_user1_vote:
            self.register_get_user_response(self.user, upvoted_ids=["test_thread"])
            vote_count += 1
        if current_user2_vote:
            self.register_get_user_response(user2, upvoted_ids=["test_thread"])
            vote_count += 1

        for (current_vote, user_vote, request) in \
                [(current_user1_vote, user1_vote, self.request),
                 (current_user2_vote, user2_vote, request2)]:

            self.register_thread_votes_response("test_thread")
            self.register_thread(overrides={"votes": {"up_count": vote_count}})

            data = {"voted": user_vote}
            result = update_thread(request, "test_thread", data)
            if current_vote == user_vote:
                self.assertEqual(result["vote_count"], vote_count)
            elif user_vote:
                vote_count += 1
                self.assertEqual(result["vote_count"], vote_count)
                self.register_get_user_response(self.user, upvoted_ids=["test_thread"])
            else:
                vote_count -= 1
                self.assertEqual(result["vote_count"], vote_count)
                self.register_get_user_response(self.user, upvoted_ids=[])

2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
    @ddt.data(*itertools.product([True, False], [True, False]))
    @ddt.unpack
    def test_abuse_flagged(self, old_flagged, new_flagged):
        """
        Test attempts to edit the "abuse_flagged" field.

        old_flagged indicates whether the thread should be flagged at the start
        of the test. new_flagged indicates the value for the "abuse_flagged"
        field in the update. If old_flagged and new_flagged are the same, no
        update should be made. Otherwise, a PUT should be made to the flag or
        or unflag endpoint according to the new_flagged value.
        """
        self.register_get_user_response(self.user)
        self.register_thread_flag_response("test_thread")
        self.register_thread({"abuse_flaggers": [str(self.user.id)] if old_flagged else []})
        data = {"abuse_flagged": new_flagged}
        result = update_thread(self.request, "test_thread", data)
        self.assertEqual(result["abuse_flagged"], new_flagged)
        last_request_path = urlparse(httpretty.last_request().path).path
        flag_url = "/api/v1/threads/test_thread/abuse_flag"
        unflag_url = "/api/v1/threads/test_thread/abuse_unflag"
        if old_flagged == new_flagged:
            self.assertNotEqual(last_request_path, flag_url)
            self.assertNotEqual(last_request_path, unflag_url)
        else:
            self.assertEqual(
                last_request_path,
                flag_url if new_flagged else unflag_url
            )
            self.assertEqual(httpretty.last_request().method, "PUT")
            self.assertEqual(
                httpretty.last_request().parsed_body,
                {"user_id": [str(self.user.id)]}
            )

2356 2357 2358 2359 2360 2361
    def test_invalid_field(self):
        self.register_thread()
        with self.assertRaises(ValidationError) as assertion:
            update_thread(self.request, "test_thread", {"raw_body": ""})
        self.assertEqual(
            assertion.exception.message_dict,
2362
            {"raw_body": ["This field may not be blank."]}
2363
        )
2364 2365


2366
@attr(shard=2)
2367
@ddt.ddt
2368 2369
@disable_signal(api, 'comment_edited')
@disable_signal(api, 'comment_voted')
2370
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
2371
class UpdateCommentTest(
2372
        ForumsEnableMixin,
2373 2374 2375 2376 2377
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase,
        MockSignalHandlerMixin
):
2378
    """Tests for update_comment"""
2379 2380 2381 2382 2383 2384

    @classmethod
    def setUpClass(cls):
        super(UpdateCommentTest, cls).setUpClass()
        cls.course = CourseFactory.create()

2385 2386 2387
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(UpdateCommentTest, self).setUp()
2388

2389 2390 2391
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
2392 2393

        self.user = UserFactory.create()
2394 2395 2396
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
2397
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
2398

2399
    def register_comment(self, overrides=None, thread_overrides=None, course=None):
2400 2401 2402 2403 2404
        """
        Make a comment with appropriate data overridden by the overrides
        parameter and register mock responses for both GET and PUT on its
        endpoint. Also mock GET for the related thread with thread_overrides.
        """
2405 2406 2407
        if course is None:
            course = self.course

2408 2409
        cs_thread_data = make_minimal_cs_thread({
            "id": "test_thread",
2410
            "course_id": unicode(course.id)
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
        })
        cs_thread_data.update(thread_overrides or {})
        self.register_get_thread_response(cs_thread_data)
        cs_comment_data = make_minimal_cs_comment({
            "id": "test_comment",
            "course_id": cs_thread_data["course_id"],
            "thread_id": cs_thread_data["id"],
            "username": self.user.username,
            "user_id": str(self.user.id),
            "created_at": "2015-06-03T00:00:00Z",
            "updated_at": "2015-06-03T00:00:00Z",
            "body": "Original body",
        })
        cs_comment_data.update(overrides or {})
        self.register_get_comment_response(cs_comment_data)
        self.register_put_comment_response(cs_comment_data)

    def test_empty(self):
        """Check that an empty update does not make any modifying requests."""
        self.register_comment()
        update_comment(self.request, "test_comment", {})
        for request in httpretty.httpretty.latest_requests:
            self.assertEqual(request.method, "GET")

2435 2436 2437
    @ddt.data(None, "test_parent")
    def test_basic(self, parent_id):
        self.register_comment({"parent_id": parent_id})
2438 2439
        with self.assert_signal_sent(api, 'comment_edited', sender=None, user=self.user, exclude_args=('post',)):
            actual = update_comment(self.request, "test_comment", {"raw_body": "Edited body"})
2440 2441 2442
        expected = {
            "id": "test_comment",
            "thread_id": "test_thread",
2443
            "parent_id": parent_id,
2444 2445 2446 2447 2448
            "author": self.user.username,
            "author_label": None,
            "created_at": "2015-06-03T00:00:00Z",
            "updated_at": "2015-06-03T00:00:00Z",
            "raw_body": "Edited body",
2449
            "rendered_body": "<p>Edited body</p>",
2450 2451 2452 2453 2454 2455 2456 2457
            "endorsed": False,
            "endorsed_by": None,
            "endorsed_by_label": None,
            "endorsed_at": None,
            "abuse_flagged": False,
            "voted": False,
            "vote_count": 0,
            "children": [],
2458 2459
            "editable_fields": ["abuse_flagged", "raw_body", "voted"],
            "child_count": 0,
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
        }
        self.assertEqual(actual, expected)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "body": ["Edited body"],
                "course_id": [unicode(self.course.id)],
                "user_id": [str(self.user.id)],
                "anonymous": ["False"],
                "anonymous_to_peers": ["False"],
                "endorsed": ["False"],
            }
        )

    def test_nonexistent_comment(self):
        self.register_get_comment_error_response("test_comment", 404)
2476
        with self.assertRaises(CommentNotFoundError):
2477 2478 2479 2480
            update_comment(self.request, "test_comment", {})

    def test_nonexistent_course(self):
        self.register_comment(thread_overrides={"course_id": "non/existent/course"})
2481
        with self.assertRaises(CourseNotFoundError):
2482 2483 2484 2485 2486
            update_comment(self.request, "test_comment", {})

    def test_unenrolled(self):
        self.register_comment()
        self.request.user = UserFactory.create()
2487
        with self.assertRaises(CourseNotFoundError):
2488 2489 2490
            update_comment(self.request, "test_comment", {})

    def test_discussions_disabled(self):
2491
        self.register_comment(course=_discussion_disabled_course_for(self.user))
2492
        with self.assertRaises(DiscussionDisabledError):
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
            update_comment(self.request, "test_comment", {})

    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
    def test_group_access(self, role_name, course_is_cohorted, thread_group_state):
2509
        cohort_course, cohort = _create_course_and_cohort_with_user_role(course_is_cohorted, self.user, role_name)
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
        self.register_get_thread_response(make_minimal_cs_thread())
        self.register_comment(
            {"thread_id": "test_thread"},
            thread_overrides={
                "id": "test_thread",
                "course_id": unicode(cohort_course.id),
                "group_id": (
                    None if thread_group_state == "no_group" else
                    cohort.id if thread_group_state == "match_group" else
                    cohort.id + 1
                ),
            }
        )
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
            thread_group_state == "different_group"
        )
        try:
            update_comment(self.request, "test_comment", {})
            self.assertFalse(expected_error)
2531
        except ThreadNotFoundError:
2532 2533
            self.assertTrue(expected_error)

2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
    @ddt.data(*itertools.product(
        [
            FORUM_ROLE_ADMINISTRATOR,
            FORUM_ROLE_MODERATOR,
            FORUM_ROLE_COMMUNITY_TA,
            FORUM_ROLE_STUDENT,
        ],
        [True, False],
        [True, False],
    ))
    @ddt.unpack
    def test_raw_body_access(self, role_name, is_thread_author, is_comment_author):
2546 2547
        role = Role.objects.create(name=role_name, course_id=self.course.id)
        role.users = [self.user]
2548 2549 2550 2551 2552 2553 2554
        self.register_comment(
            {"user_id": str(self.user.id if is_comment_author else (self.user.id + 1))},
            thread_overrides={
                "user_id": str(self.user.id if is_thread_author else (self.user.id + 1))
            }
        )
        expected_error = role_name == FORUM_ROLE_STUDENT and not is_comment_author
2555 2556 2557
        try:
            update_comment(self.request, "test_comment", {"raw_body": "edited"})
            self.assertFalse(expected_error)
2558
        except ValidationError as err:
2559
            self.assertTrue(expected_error)
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
            self.assertEqual(
                err.message_dict,
                {"raw_body": ["This field is not editable."]}
            )

    @ddt.data(*itertools.product(
        [
            FORUM_ROLE_ADMINISTRATOR,
            FORUM_ROLE_MODERATOR,
            FORUM_ROLE_COMMUNITY_TA,
            FORUM_ROLE_STUDENT,
        ],
        [True, False],
2573
        ["question", "discussion"],
2574 2575 2576
        [True, False],
    ))
    @ddt.unpack
2577
    def test_endorsed_access(self, role_name, is_thread_author, thread_type, is_comment_author):
2578 2579 2580 2581 2582
        role = Role.objects.create(name=role_name, course_id=self.course.id)
        role.users = [self.user]
        self.register_comment(
            {"user_id": str(self.user.id if is_comment_author else (self.user.id + 1))},
            thread_overrides={
2583 2584
                "thread_type": thread_type,
                "user_id": str(self.user.id if is_thread_author else (self.user.id + 1)),
2585 2586
            }
        )
2587 2588 2589 2590
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            (thread_type == "discussion" or not is_thread_author)
        )
2591 2592 2593 2594 2595 2596 2597 2598 2599
        try:
            update_comment(self.request, "test_comment", {"endorsed": True})
            self.assertFalse(expected_error)
        except ValidationError as err:
            self.assertTrue(expected_error)
            self.assertEqual(
                err.message_dict,
                {"endorsed": ["This field is not editable."]}
            )
2600

2601 2602
    @ddt.data(*itertools.product([True, False], [True, False]))
    @ddt.unpack
2603 2604
    @mock.patch("eventtracking.tracker.emit")
    def test_voted(self, current_vote_status, new_vote_status, mock_emit):
2605 2606 2607
        """
        Test attempts to edit the "voted" field.

2608 2609 2610 2611 2612
        current_vote_status indicates whether the comment should be upvoted at
        the start of the test. new_vote_status indicates the value for the
        "voted" field in the update. If current_vote_status and new_vote_status
        are the same, no update should be made. Otherwise, a vote should be PUT
        or DELETEd according to the new_vote_status value.
2613
        """
2614 2615
        vote_count = 0
        if current_vote_status:
2616
            self.register_get_user_response(self.user, upvoted_ids=["test_comment"])
2617
            vote_count = 1
2618
        self.register_comment_votes_response("test_comment")
2619 2620 2621 2622 2623
        self.register_comment(overrides={"votes": {"up_count": vote_count}})
        data = {"voted": new_vote_status}
        result = update_comment(self.request, "test_comment", data)
        self.assertEqual(result["vote_count"], 1 if new_vote_status else 0)
        self.assertEqual(result["voted"], new_vote_status)
2624 2625
        last_request_path = urlparse(httpretty.last_request().path).path
        votes_url = "/api/v1/comments/test_comment/votes"
2626
        if current_vote_status == new_vote_status:
2627 2628 2629 2630 2631
            self.assertNotEqual(last_request_path, votes_url)
        else:
            self.assertEqual(last_request_path, votes_url)
            self.assertEqual(
                httpretty.last_request().method,
2632
                "PUT" if new_vote_status else "DELETE"
2633 2634
            )
            actual_request_data = (
2635
                httpretty.last_request().parsed_body if new_vote_status else
2636 2637 2638 2639
                parse_qs(urlparse(httpretty.last_request().path).query)
            )
            actual_request_data.pop("request_id", None)
            expected_request_data = {"user_id": [str(self.user.id)]}
2640
            if new_vote_status:
2641 2642 2643
                expected_request_data["value"] = ["up"]
            self.assertEqual(actual_request_data, expected_request_data)

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
            event_name, event_data = mock_emit.call_args[0]
            self.assertEqual(event_name, "edx.forum.response.voted")

            self.assertEqual(
                event_data,
                {
                    'undo_vote': not new_vote_status,
                    'url': '',
                    'target_username': self.user.username,
                    'vote_value': 'up',
                    'user_forums_roles': [FORUM_ROLE_STUDENT],
                    'user_course_roles': [],
                    'commentable_id': 'dummy',
                    'id': 'test_comment'
                }
            )

2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
    @ddt.data(*itertools.product([True, False], [True, False], [True, False]))
    @ddt.unpack
    def test_vote_count(self, current_vote_status, first_vote, second_vote):
        """
        Tests vote_count increases and decreases correctly from the same user
        """
        #setup
        starting_vote_count = 0
        if current_vote_status:
            self.register_get_user_response(self.user, upvoted_ids=["test_comment"])
            starting_vote_count = 1
        self.register_comment_votes_response("test_comment")
        self.register_comment(overrides={"votes": {"up_count": starting_vote_count}})

        #first vote
        data = {"voted": first_vote}
        result = update_comment(self.request, "test_comment", data)
        self.register_comment(overrides={"voted": first_vote})
        self.assertEqual(result["vote_count"], 1 if first_vote else 0)

        #second vote
        data = {"voted": second_vote}
        result = update_comment(self.request, "test_comment", data)
        self.assertEqual(result["vote_count"], 1 if second_vote else 0)

    @ddt.data(*itertools.product([True, False], [True, False], [True, False], [True, False]))
    @ddt.unpack
    def test_vote_count_two_users(
            self,
            current_user1_vote,
            current_user2_vote,
            user1_vote,
            user2_vote
    ):
        """
        Tests vote_count increases and decreases correctly from different users
        """
        user2 = UserFactory.create()
        self.register_get_user_response(user2)
        request2 = RequestFactory().get("/test_path")
        request2.user = user2
        CourseEnrollmentFactory.create(user=user2, course_id=self.course.id)

        vote_count = 0
        if current_user1_vote:
            self.register_get_user_response(self.user, upvoted_ids=["test_comment"])
            vote_count += 1
        if current_user2_vote:
            self.register_get_user_response(user2, upvoted_ids=["test_comment"])
            vote_count += 1

        for (current_vote, user_vote, request) in \
                [(current_user1_vote, user1_vote, self.request),
                 (current_user2_vote, user2_vote, request2)]:

            self.register_comment_votes_response("test_comment")
            self.register_comment(overrides={"votes": {"up_count": vote_count}})

            data = {"voted": user_vote}
            result = update_comment(request, "test_comment", data)
            if current_vote == user_vote:
                self.assertEqual(result["vote_count"], vote_count)
            elif user_vote:
                vote_count += 1
                self.assertEqual(result["vote_count"], vote_count)
                self.register_get_user_response(self.user, upvoted_ids=["test_comment"])
            else:
                vote_count -= 1
                self.assertEqual(result["vote_count"], vote_count)
                self.register_get_user_response(self.user, upvoted_ids=[])

2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
    @ddt.data(*itertools.product([True, False], [True, False]))
    @ddt.unpack
    def test_abuse_flagged(self, old_flagged, new_flagged):
        """
        Test attempts to edit the "abuse_flagged" field.

        old_flagged indicates whether the comment should be flagged at the start
        of the test. new_flagged indicates the value for the "abuse_flagged"
        field in the update. If old_flagged and new_flagged are the same, no
        update should be made. Otherwise, a PUT should be made to the flag or
        or unflag endpoint according to the new_flagged value.
        """
        self.register_get_user_response(self.user)
        self.register_comment_flag_response("test_comment")
        self.register_comment({"abuse_flaggers": [str(self.user.id)] if old_flagged else []})
        data = {"abuse_flagged": new_flagged}
        result = update_comment(self.request, "test_comment", data)
        self.assertEqual(result["abuse_flagged"], new_flagged)
        last_request_path = urlparse(httpretty.last_request().path).path
        flag_url = "/api/v1/comments/test_comment/abuse_flag"
        unflag_url = "/api/v1/comments/test_comment/abuse_unflag"
        if old_flagged == new_flagged:
            self.assertNotEqual(last_request_path, flag_url)
            self.assertNotEqual(last_request_path, unflag_url)
        else:
            self.assertEqual(
                last_request_path,
                flag_url if new_flagged else unflag_url
            )
            self.assertEqual(httpretty.last_request().method, "PUT")
            self.assertEqual(
                httpretty.last_request().parsed_body,
                {"user_id": [str(self.user.id)]}
            )

2767

2768
@attr(shard=2)
2769
@ddt.ddt
2770
@disable_signal(api, 'thread_deleted')
2771
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
2772
class DeleteThreadTest(
2773
        ForumsEnableMixin,
2774 2775 2776 2777 2778
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase,
        MockSignalHandlerMixin
):
2779
    """Tests for delete_thread"""
2780 2781 2782 2783 2784
    @classmethod
    def setUpClass(cls):
        super(DeleteThreadTest, cls).setUpClass()
        cls.course = CourseFactory.create()

2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(DeleteThreadTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
        self.thread_id = "test_thread"
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)

    def register_thread(self, overrides=None):
        """
        Make a thread with appropriate data overridden by the overrides
        parameter and register mock responses for both GET and DELETE on its
        endpoint.
        """
        cs_data = make_minimal_cs_thread({
            "id": self.thread_id,
            "course_id": unicode(self.course.id),
            "user_id": str(self.user.id),
        })
        cs_data.update(overrides or {})
        self.register_get_thread_response(cs_data)
        self.register_delete_thread_response(cs_data["id"])

    def test_basic(self):
        self.register_thread()
2815 2816
        with self.assert_signal_sent(api, 'thread_deleted', sender=None, user=self.user, exclude_args=('post',)):
            self.assertIsNone(delete_thread(self.request, self.thread_id))
2817 2818 2819 2820 2821 2822 2823 2824
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/threads/{}".format(self.thread_id)
        )
        self.assertEqual(httpretty.last_request().method, "DELETE")

    def test_thread_id_not_found(self):
        self.register_get_thread_error_response("missing_thread", 404)
2825
        with self.assertRaises(ThreadNotFoundError):
2826 2827 2828 2829
            delete_thread(self.request, "missing_thread")

    def test_nonexistent_course(self):
        self.register_thread({"course_id": "non/existent/course"})
2830
        with self.assertRaises(CourseNotFoundError):
2831 2832 2833 2834 2835
            delete_thread(self.request, self.thread_id)

    def test_not_enrolled(self):
        self.register_thread()
        self.request.user = UserFactory.create()
2836
        with self.assertRaises(CourseNotFoundError):
2837 2838 2839
            delete_thread(self.request, self.thread_id)

    def test_discussions_disabled(self):
2840 2841
        disabled_course = _discussion_disabled_course_for(self.user)
        self.register_thread(overrides={"course_id": unicode(disabled_course.id)})
2842
        with self.assertRaises(DiscussionDisabledError):
2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
            delete_thread(self.request, self.thread_id)

    @ddt.data(
        FORUM_ROLE_ADMINISTRATOR,
        FORUM_ROLE_MODERATOR,
        FORUM_ROLE_COMMUNITY_TA,
        FORUM_ROLE_STUDENT,
    )
    def test_non_author_delete_allowed(self, role_name):
        role = Role.objects.create(name=role_name, course_id=self.course.id)
        role.users = [self.user]
        self.register_thread({"user_id": str(self.user.id + 1)})
        expected_error = role_name == FORUM_ROLE_STUDENT
        try:
2857
            delete_thread(self.request, self.thread_id)
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
            self.assertFalse(expected_error)
        except PermissionDenied:
            self.assertTrue(expected_error)

    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
    def test_group_access(self, role_name, course_is_cohorted, thread_group_state):
        """
        Tests group access for deleting a thread

        All privileged roles are able to delete a thread. A student role can
        only delete a thread if,
        the student role is the author and the thread is not in a cohort,
        the student role is the author and the thread is in the author's cohort.
        """
2884
        cohort_course, cohort = _create_course_and_cohort_with_user_role(course_is_cohorted, self.user, role_name)
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
        self.register_thread({
            "course_id": unicode(cohort_course.id),
            "group_id": (
                None if thread_group_state == "no_group" else
                cohort.id if thread_group_state == "match_group" else
                cohort.id + 1
            ),
        })
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
            thread_group_state == "different_group"
        )
        try:
2899 2900
            delete_thread(self.request, self.thread_id)
            self.assertFalse(expected_error)
2901
        except ThreadNotFoundError:
2902 2903 2904
            self.assertTrue(expected_error)


2905
@attr(shard=2)
2906
@ddt.ddt
2907
@disable_signal(api, 'comment_deleted')
2908
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
2909
class DeleteCommentTest(
2910
        ForumsEnableMixin,
2911 2912 2913 2914 2915
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase,
        MockSignalHandlerMixin
):
2916
    """Tests for delete_comment"""
2917 2918 2919 2920 2921
    @classmethod
    def setUpClass(cls):
        super(DeleteCommentTest, cls).setUpClass()
        cls.course = CourseFactory.create()

2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(DeleteCommentTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
        self.request = RequestFactory().get("/test_path")
        self.request.user = self.user
        self.thread_id = "test_thread"
        self.comment_id = "test_comment"
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)

    def register_comment_and_thread(self, overrides=None, thread_overrides=None):
        """
        Make a comment with appropriate data overridden by the override
        parameters and register mock responses for both GET and DELETE on its
        endpoint. Also mock GET for the related thread with thread_overrides.
        """
        cs_thread_data = make_minimal_cs_thread({
            "id": self.thread_id,
            "course_id": unicode(self.course.id)
        })
        cs_thread_data.update(thread_overrides or {})
        self.register_get_thread_response(cs_thread_data)
        cs_comment_data = make_minimal_cs_comment({
            "id": self.comment_id,
            "course_id": cs_thread_data["course_id"],
            "thread_id": cs_thread_data["id"],
            "username": self.user.username,
            "user_id": str(self.user.id),
        })
        cs_comment_data.update(overrides or {})
        self.register_get_comment_response(cs_comment_data)
        self.register_delete_comment_response(self.comment_id)

    def test_basic(self):
        self.register_comment_and_thread()
2961 2962
        with self.assert_signal_sent(api, 'comment_deleted', sender=None, user=self.user, exclude_args=('post',)):
            self.assertIsNone(delete_comment(self.request, self.comment_id))
2963 2964 2965 2966 2967 2968 2969 2970
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/comments/{}".format(self.comment_id)
        )
        self.assertEqual(httpretty.last_request().method, "DELETE")

    def test_comment_id_not_found(self):
        self.register_get_comment_error_response("missing_comment", 404)
2971
        with self.assertRaises(CommentNotFoundError):
2972 2973 2974 2975 2976 2977
            delete_comment(self.request, "missing_comment")

    def test_nonexistent_course(self):
        self.register_comment_and_thread(
            thread_overrides={"course_id": "non/existent/course"}
        )
2978
        with self.assertRaises(CourseNotFoundError):
2979 2980 2981 2982 2983
            delete_comment(self.request, self.comment_id)

    def test_not_enrolled(self):
        self.register_comment_and_thread()
        self.request.user = UserFactory.create()
2984
        with self.assertRaises(CourseNotFoundError):
2985 2986 2987
            delete_comment(self.request, self.comment_id)

    def test_discussions_disabled(self):
2988 2989 2990 2991 2992
        disabled_course = _discussion_disabled_course_for(self.user)
        self.register_comment_and_thread(
            thread_overrides={"course_id": unicode(disabled_course.id)},
            overrides={"course_id": unicode(disabled_course.id)}
        )
2993
        with self.assertRaises(DiscussionDisabledError):
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
            delete_comment(self.request, self.comment_id)

    @ddt.data(
        FORUM_ROLE_ADMINISTRATOR,
        FORUM_ROLE_MODERATOR,
        FORUM_ROLE_COMMUNITY_TA,
        FORUM_ROLE_STUDENT,
    )
    def test_non_author_delete_allowed(self, role_name):
        role = Role.objects.create(name=role_name, course_id=self.course.id)
        role.users = [self.user]
        self.register_comment_and_thread(
            overrides={"user_id": str(self.user.id + 1)}
        )
        expected_error = role_name == FORUM_ROLE_STUDENT
        try:
            delete_comment(self.request, self.comment_id)
            self.assertFalse(expected_error)
        except PermissionDenied:
            self.assertTrue(expected_error)

    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
    def test_group_access(self, role_name, course_is_cohorted, thread_group_state):
        """
        Tests group access for deleting a comment

        All privileged roles are able to delete a comment. A student role can
        only delete a comment if,
        the student role is the author and the comment is not in a cohort,
        the student role is the author and the comment is in the author's cohort.
        """
3037
        cohort_course, cohort = _create_course_and_cohort_with_user_role(course_is_cohorted, self.user, role_name)
3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
        self.register_comment_and_thread(
            overrides={"thread_id": "test_thread"},
            thread_overrides={
                "course_id": unicode(cohort_course.id),
                "group_id": (
                    None if thread_group_state == "no_group" else
                    cohort.id if thread_group_state == "match_group" else
                    cohort.id + 1
                ),
            }
        )
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
            thread_group_state == "different_group"
        )
        try:
            delete_comment(self.request, self.comment_id)
3056
            self.assertFalse(expected_error)
3057
        except ThreadNotFoundError:
3058
            self.assertTrue(expected_error)
3059 3060


3061
@attr(shard=2)
3062
@ddt.ddt
3063
@mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
3064
class RetrieveThreadTest(
3065
        ForumsEnableMixin,
3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase
):
    """Tests for get_thread"""
    @classmethod
    def setUpClass(cls):
        super(RetrieveThreadTest, cls).setUpClass()
        cls.course = CourseFactory.create()

    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(RetrieveThreadTest, self).setUp()
        httpretty.reset()
        httpretty.enable()
        self.addCleanup(httpretty.disable)
3082 3083
        self.user = UserFactory.create()
        self.register_get_user_response(self.user)
3084
        self.request = RequestFactory().get("/test_path")
3085
        self.request.user = self.user
3086
        self.thread_id = "test_thread"
3087
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098

    def register_thread(self, overrides=None):
        """
        Make a thread with appropriate data overridden by the overrides
        parameter and register mock responses for GET on its
        endpoint.
        """
        cs_data = make_minimal_cs_thread({
            "id": self.thread_id,
            "course_id": unicode(self.course.id),
            "commentable_id": "test_topic",
3099 3100
            "username": self.user.username,
            "user_id": str(self.user.id),
3101 3102
            "title": "Test Title",
            "body": "Test body",
3103 3104
            "resp_total": 0,

3105 3106 3107 3108 3109
        })
        cs_data.update(overrides or {})
        self.register_get_thread_response(cs_data)

    def test_basic(self):
3110
        self.register_thread({"resp_total": 2})
3111 3112 3113 3114
        self.assertEqual(get_thread(self.request, self.thread_id), self.expected_thread_data({
            "response_count": 2,
            "unread_comment_count": 1,
        }))
3115 3116 3117 3118
        self.assertEqual(httpretty.last_request().method, "GET")

    def test_thread_id_not_found(self):
        self.register_get_thread_error_response("missing_thread", 404)
3119
        with self.assertRaises(ThreadNotFoundError):
3120 3121 3122
            get_thread(self.request, "missing_thread")

    def test_nonauthor_enrolled_in_course(self):
3123
        non_author_user = UserFactory.create()
3124 3125 3126 3127
        self.register_get_user_response(non_author_user)
        CourseEnrollmentFactory.create(user=non_author_user, course_id=self.course.id)
        self.register_thread()
        self.request.user = non_author_user
3128 3129 3130 3131
        self.assertEqual(get_thread(self.request, self.thread_id), self.expected_thread_data({
            "editable_fields": ["abuse_flagged", "following", "read", "voted"],
            "unread_comment_count": 1,
        }))
3132 3133
        self.assertEqual(httpretty.last_request().method, "GET")

3134 3135 3136
    def test_not_enrolled_in_course(self):
        self.register_thread()
        self.request.user = UserFactory.create()
3137
        with self.assertRaises(CourseNotFoundError):
3138 3139
            get_thread(self.request, self.thread_id)

3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False],
            ["no_group", "match_group", "different_group"],
        )
    )
    @ddt.unpack
    def test_group_access(self, role_name, course_is_cohorted, thread_group_state):
        """
        Tests group access for retrieving a thread

        All privileged roles are able to retrieve a thread. A student role can
        only retrieve a thread if,
        the student role is the author and the thread is not in a cohort,
        the student role is the author and the thread is in the author's cohort.
        """
3162
        cohort_course, cohort = _create_course_and_cohort_with_user_role(course_is_cohorted, self.user, role_name)
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
        self.register_thread({
            "course_id": unicode(cohort_course.id),
            "group_id": (
                None if thread_group_state == "no_group" else
                cohort.id if thread_group_state == "match_group" else
                cohort.id + 1
            ),
        })
        expected_error = (
            role_name == FORUM_ROLE_STUDENT and
            course_is_cohorted and
            thread_group_state == "different_group"
        )
        try:
            get_thread(self.request, self.thread_id)
            self.assertFalse(expected_error)
3179
        except ThreadNotFoundError:
3180
            self.assertTrue(expected_error)