test_serializers.py 33.3 KB
Newer Older
1 2 3
"""
Tests for Discussion API serializers
"""
4
import itertools
5
from urlparse import urlparse
6

7
import ddt
8
import httpretty
9
import mock
10
from django.test.client import RequestFactory
11
from nose.plugins.attrib import attr
12

13
from discussion_api.serializers import CommentSerializer, ThreadSerializer, get_context
cahrens committed
14 15
from discussion_api.tests.utils import CommentsServiceMockMixin, make_minimal_cs_comment, make_minimal_cs_thread
from django_comment_client.tests.utils import ForumsEnableMixin
16 17 18 19 20
from django_comment_common.models import (
    FORUM_ROLE_ADMINISTRATOR,
    FORUM_ROLE_COMMUNITY_TA,
    FORUM_ROLE_MODERATOR,
    FORUM_ROLE_STUDENT,
cahrens committed
21
    Role
22
)
23
from lms.lib.comment_client.comment import Comment
24
from lms.lib.comment_client.thread import Thread
cahrens committed
25
from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory
26
from student.tests.factories import UserFactory
27
from util.testing import UrlResetMixin
28 29
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
30
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
31 32 33 34
from xmodule.modulestore.tests.factories import CourseFactory


@ddt.ddt
35
class SerializerTestMixin(ForumsEnableMixin, CommentsServiceMockMixin, UrlResetMixin):
36 37 38 39 40 41
    @classmethod
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUpClass(cls):
        super(SerializerTestMixin, cls).setUpClass()
        cls.course = CourseFactory.create()

42
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
43
    def setUp(self):
44
        super(SerializerTestMixin, self).setUp()
45 46 47 48 49 50
        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)
51 52
        self.request = RequestFactory().get("/dummy")
        self.request.user = self.user
53 54 55 56 57 58 59 60
        self.author = UserFactory.create()

    def create_role(self, role_name, users, course=None):
        """Create a Role in self.course with the given name and users"""
        course = course or self.course
        role = Role.objects.create(name=role_name, course_id=course.id)
        role.users = users

61 62 63 64 65 66 67 68 69 70 71 72
    @ddt.data(
        (FORUM_ROLE_ADMINISTRATOR, True, False, True),
        (FORUM_ROLE_ADMINISTRATOR, False, True, False),
        (FORUM_ROLE_MODERATOR, True, False, True),
        (FORUM_ROLE_MODERATOR, False, True, False),
        (FORUM_ROLE_COMMUNITY_TA, True, False, True),
        (FORUM_ROLE_COMMUNITY_TA, False, True, False),
        (FORUM_ROLE_STUDENT, True, False, True),
        (FORUM_ROLE_STUDENT, False, True, True),
    )
    @ddt.unpack
    def test_anonymity(self, role_name, anonymous, anonymous_to_peers, expected_serialized_anonymous):
73
        """
74 75 76 77 78 79 80 81 82 83 84 85 86
        Test that content is properly made anonymous.

        Content should be anonymous iff the anonymous field is true or the
        anonymous_to_peers field is true and the requester does not have a
        privileged role.

        role_name is the name of the requester's role.
        anonymous is the value of the anonymous field in the content.
        anonymous_to_peers is the value of the anonymous_to_peers field in the
          content.
        expected_serialized_anonymous is whether the content should actually be
          anonymous in the API output when requested by a user with the given
          role.
87
        """
88 89 90 91 92 93 94 95
        self.create_role(role_name, [self.user])
        serialized = self.serialize(
            self.make_cs_content({"anonymous": anonymous, "anonymous_to_peers": anonymous_to_peers})
        )
        actual_serialized_anonymous = serialized["author"] is None
        self.assertEqual(actual_serialized_anonymous, expected_serialized_anonymous)

    @ddt.data(
96
        (FORUM_ROLE_ADMINISTRATOR, False, "Staff"),
97
        (FORUM_ROLE_ADMINISTRATOR, True, None),
98
        (FORUM_ROLE_MODERATOR, False, "Staff"),
99
        (FORUM_ROLE_MODERATOR, True, None),
100
        (FORUM_ROLE_COMMUNITY_TA, False, "Community TA"),
101 102 103 104 105 106 107 108 109
        (FORUM_ROLE_COMMUNITY_TA, True, None),
        (FORUM_ROLE_STUDENT, False, None),
        (FORUM_ROLE_STUDENT, True, None),
    )
    @ddt.unpack
    def test_author_labels(self, role_name, anonymous, expected_label):
        """
        Test correctness of the author_label field.

110
        The label should be "Staff", "Staff", or "Community TA" for the
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        Administrator, Moderator, and Community TA roles, respectively, but
        the label should not be present if the content is anonymous.

        role_name is the name of the author's role.
        anonymous is the value of the anonymous field in the content.
        expected_label is the expected value of the author_label field in the
          API output.
        """
        self.create_role(role_name, [self.author])
        serialized = self.serialize(self.make_cs_content({"anonymous": anonymous}))
        self.assertEqual(serialized["author_label"], expected_label)

    def test_abuse_flagged(self):
        serialized = self.serialize(self.make_cs_content({"abuse_flaggers": [str(self.user.id)]}))
        self.assertEqual(serialized["abuse_flagged"], True)

    def test_voted(self):
        thread_id = "test_thread"
        self.register_get_user_response(self.user, upvoted_ids=[thread_id])
        serialized = self.serialize(self.make_cs_content({"id": thread_id}))
        self.assertEqual(serialized["voted"], True)


134
@attr(shard=3)
135
@ddt.ddt
136
class ThreadSerializerSerializationTest(SerializerTestMixin, SharedModuleStoreTestCase):
137
    """Tests for ThreadSerializer serialization."""
138 139 140 141 142
    def make_cs_content(self, overrides):
        """
        Create a thread with the given overrides, plus some useful test data.
        """
        merged_overrides = {
143 144 145
            "course_id": unicode(self.course.id),
            "user_id": str(self.author.id),
            "username": self.author.username,
146
            "read": True,
147 148
            "endorsed": True,
            "resp_total": 0,
149
        }
150 151
        merged_overrides.update(overrides)
        return make_minimal_cs_thread(merged_overrides)
152 153 154 155 156 157

    def serialize(self, thread):
        """
        Create a serializer with an appropriate context and use it to serialize
        the given thread, returning the result.
        """
158
        return ThreadSerializer(thread, context=get_context(self.course, self.request)).data
159 160

    def test_basic(self):
161
        thread = make_minimal_cs_thread({
162 163 164 165 166 167 168 169 170 171 172
            "id": "test_thread",
            "course_id": unicode(self.course.id),
            "commentable_id": "test_topic",
            "user_id": str(self.author.id),
            "username": self.author.username,
            "title": "Test Title",
            "body": "Test body",
            "pinned": True,
            "votes": {"up_count": 4},
            "comments_count": 5,
            "unread_comments_count": 3,
173 174
        })
        expected = self.expected_thread_data({
175 176
            "author": self.author.username,
            "vote_count": 4,
177
            "comment_count": 6,
178 179
            "unread_comment_count": 3,
            "pinned": True,
180
            "editable_fields": ["abuse_flagged", "following", "read", "voted"],
181
        })
182 183
        self.assertEqual(self.serialize(thread), expected)

184 185 186 187 188 189 190 191 192 193 194 195 196
        thread["thread_type"] = "question"
        expected.update({
            "type": "question",
            "comment_list_url": None,
            "endorsed_comment_list_url": (
                "http://testserver/api/discussion/v1/comments/?thread_id=test_thread&endorsed=True"
            ),
            "non_endorsed_comment_list_url": (
                "http://testserver/api/discussion/v1/comments/?thread_id=test_thread&endorsed=False"
            ),
        })
        self.assertEqual(self.serialize(thread), expected)

197 198 199 200 201 202 203 204
    def test_pinned_missing(self):
        """
        Make sure that older threads in the comments service without the pinned
        field do not break serialization
        """
        thread_data = self.make_cs_content({})
        del thread_data["pinned"]
        self.register_get_thread_response(thread_data)
205
        serialized = self.serialize(thread_data)
206 207
        self.assertEqual(serialized["pinned"], False)

208
    def test_group(self):
209 210
        self.course.cohort_config = {"cohorted": True}
        modulestore().update_item(self.course, ModuleStoreEnum.UserID.test)
211
        cohort = CohortFactory.create(course_id=self.course.id)
212
        serialized = self.serialize(self.make_cs_content({"group_id": cohort.id}))
213 214 215
        self.assertEqual(serialized["group_id"], cohort.id)
        self.assertEqual(serialized["group_name"], cohort.name)

216 217 218 219 220
    def test_following(self):
        thread_id = "test_thread"
        self.register_get_user_response(self.user, subscribed_thread_ids=[thread_id])
        serialized = self.serialize(self.make_cs_content({"id": thread_id}))
        self.assertEqual(serialized["following"], True)
221

222 223 224
    def test_response_count(self):
        thread_data = self.make_cs_content({"resp_total": 2})
        self.register_get_thread_response(thread_data)
225
        serialized = self.serialize(thread_data)
226 227
        self.assertEqual(serialized["response_count"], 2)

228 229 230 231
    def test_response_count_missing(self):
        thread_data = self.make_cs_content({})
        del thread_data["resp_total"]
        self.register_get_thread_response(thread_data)
232
        serialized = self.serialize(thread_data)
233
        self.assertNotIn("response_count", serialized)
234

Brian Beggs committed
235

236
@ddt.ddt
237
class CommentSerializerTest(SerializerTestMixin, SharedModuleStoreTestCase):
238
    """Tests for CommentSerializer."""
239 240 241 242 243 244
    def setUp(self):
        super(CommentSerializerTest, self).setUp()
        self.endorser = UserFactory.create()
        self.endorsed_at = "2015-05-18T12:34:56Z"

    def make_cs_content(self, overrides=None, with_endorsement=False):
245
        """
246
        Create a comment with the given overrides, plus some useful test data.
247
        """
248 249 250 251
        merged_overrides = {
            "user_id": str(self.author.id),
            "username": self.author.username
        }
252 253 254 255 256 257
        if with_endorsement:
            merged_overrides["endorsement"] = {
                "user_id": str(self.endorser.id),
                "time": self.endorsed_at
            }
        merged_overrides.update(overrides or {})
258
        return make_minimal_cs_comment(merged_overrides)
259

260
    def serialize(self, comment, thread_data=None):
261
        """
262 263 264
        Create a serializer with an appropriate context and use it to serialize
        the given comment, returning the result.
        """
265
        context = get_context(self.course, self.request, make_minimal_cs_thread(thread_data))
266
        return CommentSerializer(comment, context=context).data
267

268 269
    def test_basic(self):
        comment = {
270
            "type": "comment",
271 272 273 274 275 276 277 278 279
            "id": "test_comment",
            "thread_id": "test_thread",
            "user_id": str(self.author.id),
            "username": self.author.username,
            "anonymous": False,
            "anonymous_to_peers": False,
            "created_at": "2015-04-28T00:00:00Z",
            "updated_at": "2015-04-28T11:11:11Z",
            "body": "Test body",
280
            "endorsed": False,
281 282 283
            "abuse_flaggers": [],
            "votes": {"up_count": 4},
            "children": [],
284
            "child_count": 0,
285 286 287 288 289 290 291 292 293 294
        }
        expected = {
            "id": "test_comment",
            "thread_id": "test_thread",
            "parent_id": None,
            "author": self.author.username,
            "author_label": None,
            "created_at": "2015-04-28T00:00:00Z",
            "updated_at": "2015-04-28T11:11:11Z",
            "raw_body": "Test body",
295
            "rendered_body": "<p>Test body</p>",
296 297 298 299
            "endorsed": False,
            "endorsed_by": None,
            "endorsed_by_label": None,
            "endorsed_at": None,
300 301 302 303
            "abuse_flagged": False,
            "voted": False,
            "vote_count": 4,
            "children": [],
304
            "editable_fields": ["abuse_flagged", "voted"],
305
            "child_count": 0,
306 307
        }
        self.assertEqual(self.serialize(comment), expected)
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    @ddt.data(
        *itertools.product(
            [
                FORUM_ROLE_ADMINISTRATOR,
                FORUM_ROLE_MODERATOR,
                FORUM_ROLE_COMMUNITY_TA,
                FORUM_ROLE_STUDENT,
            ],
            [True, False]
        )
    )
    @ddt.unpack
    def test_endorsed_by(self, endorser_role_name, thread_anonymous):
        """
        Test correctness of the endorsed_by field.

        The endorser should be anonymous iff the thread is anonymous to the
        requester, and the endorser is not a privileged user.

        endorser_role_name is the name of the endorser's role.
        thread_anonymous is the value of the anonymous field in the thread.
        """
        self.create_role(endorser_role_name, [self.endorser])
        serialized = self.serialize(
            self.make_cs_content(with_endorsement=True),
            thread_data={"anonymous": thread_anonymous}
        )
        actual_endorser_anonymous = serialized["endorsed_by"] is None
        expected_endorser_anonymous = endorser_role_name == FORUM_ROLE_STUDENT and thread_anonymous
        self.assertEqual(actual_endorser_anonymous, expected_endorser_anonymous)

    @ddt.data(
341 342 343
        (FORUM_ROLE_ADMINISTRATOR, "Staff"),
        (FORUM_ROLE_MODERATOR, "Staff"),
        (FORUM_ROLE_COMMUNITY_TA, "Community TA"),
344 345 346 347 348 349 350
        (FORUM_ROLE_STUDENT, None),
    )
    @ddt.unpack
    def test_endorsed_by_labels(self, role_name, expected_label):
        """
        Test correctness of the endorsed_by_label field.

351
        The label should be "Staff", "Staff", or "Community TA" for the
352 353 354 355 356 357 358 359 360 361 362 363 364 365
        Administrator, Moderator, and Community TA roles, respectively.

        role_name is the name of the author's role.
        expected_label is the expected value of the author_label field in the
          API output.
        """
        self.create_role(role_name, [self.endorser])
        serialized = self.serialize(self.make_cs_content(with_endorsement=True))
        self.assertEqual(serialized["endorsed_by_label"], expected_label)

    def test_endorsed_at(self):
        serialized = self.serialize(self.make_cs_content(with_endorsement=True))
        self.assertEqual(serialized["endorsed_at"], self.endorsed_at)

366 367 368 369 370 371
    def test_children(self):
        comment = self.make_cs_content({
            "id": "test_root",
            "children": [
                self.make_cs_content({
                    "id": "test_child_1",
372
                    "parent_id": "test_root",
373 374 375
                }),
                self.make_cs_content({
                    "id": "test_child_2",
376 377 378 379 380 381 382
                    "parent_id": "test_root",
                    "children": [
                        self.make_cs_content({
                            "id": "test_grandchild",
                            "parent_id": "test_child_2"
                        })
                    ],
383 384 385 386 387 388 389 390 391 392
                }),
            ],
        })
        serialized = self.serialize(comment)
        self.assertEqual(serialized["children"][0]["id"], "test_child_1")
        self.assertEqual(serialized["children"][0]["parent_id"], "test_root")
        self.assertEqual(serialized["children"][1]["id"], "test_child_2")
        self.assertEqual(serialized["children"][1]["parent_id"], "test_root")
        self.assertEqual(serialized["children"][1]["children"][0]["id"], "test_grandchild")
        self.assertEqual(serialized["children"][1]["children"][0]["parent_id"], "test_child_2")
393 394 395


@ddt.ddt
396 397 398 399 400 401
class ThreadSerializerDeserializationTest(
        ForumsEnableMixin,
        CommentsServiceMockMixin,
        UrlResetMixin,
        SharedModuleStoreTestCase
):
402
    """Tests for ThreadSerializer deserialization."""
403 404 405 406 407 408
    @classmethod
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUpClass(cls):
        super(ThreadSerializerDeserializationTest, cls).setUpClass()
        cls.course = CourseFactory.create()

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(ThreadSerializerDeserializationTest, 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("/dummy")
        self.request.user = self.user
        self.minimal_data = {
            "course_id": unicode(self.course.id),
            "topic_id": "test_topic",
            "type": "discussion",
            "title": "Test Title",
            "raw_body": "Test body",
        }
426 427 428 429 430 431 432 433
        self.existing_thread = Thread(**make_minimal_cs_thread({
            "id": "existing_thread",
            "course_id": unicode(self.course.id),
            "commentable_id": "original_topic",
            "thread_type": "discussion",
            "title": "Original Title",
            "body": "Original body",
            "user_id": str(self.user.id),
434
            "username": self.user.username,
435 436
            "read": "False",
            "endorsed": "False"
437
        }))
438

439
    def save_and_reserialize(self, data, instance=None):
440
        """
441 442 443
        Create a serializer with the given data and (if updating) instance,
        ensure that it is valid, save the result, and return the full thread
        data from the serializer.
444
        """
445 446 447 448 449 450
        serializer = ThreadSerializer(
            instance,
            data=data,
            partial=(instance is not None),
            context=get_context(self.course, self.request)
        )
451 452 453 454
        self.assertTrue(serializer.is_valid())
        serializer.save()
        return serializer.data

455
    def test_create_minimal(self):
456
        self.register_post_thread_response({"id": "test_id", "username": self.user.username})
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        saved = self.save_and_reserialize(self.minimal_data)
        self.assertEqual(
            urlparse(httpretty.last_request().path).path,
            "/api/v1/test_topic/threads"
        )
        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)],
            }
        )
        self.assertEqual(saved["id"], "test_id")

475
    def test_create_all_fields(self):
476
        self.register_post_thread_response({"id": "test_id", "username": self.user.username})
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
        data = self.minimal_data.copy()
        data["group_id"] = 42
        self.save_and_reserialize(data)
        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)],
                "group_id": ["42"],
            }
        )

493
    def test_create_missing_field(self):
494 495 496 497 498 499 500 501 502 503
        for field in self.minimal_data:
            data = self.minimal_data.copy()
            data.pop(field)
            serializer = ThreadSerializer(data=data)
            self.assertFalse(serializer.is_valid())
            self.assertEqual(
                serializer.errors,
                {field: ["This field is required."]}
            )

504 505 506 507 508
    @ddt.data("", " ")
    def test_create_empty_string(self, value):
        data = self.minimal_data.copy()
        data.update({field: value for field in ["topic_id", "title", "raw_body"]})
        serializer = ThreadSerializer(data=data, context=get_context(self.course, self.request))
509
        self.assertFalse(serializer.is_valid())
510 511
        self.assertEqual(
            serializer.errors,
512
            {field: ["This field may not be blank."] for field in ["topic_id", "title", "raw_body"]}
513 514
        )

515
    def test_create_type(self):
516
        self.register_post_thread_response({"id": "test_id", "username": self.user.username})
517 518 519 520 521 522 523
        data = self.minimal_data.copy()
        data["type"] = "question"
        self.save_and_reserialize(data)

        data["type"] = "invalid_type"
        serializer = ThreadSerializer(data=data)
        self.assertFalse(serializer.is_valid())
524

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    def test_update_empty(self):
        self.register_put_thread_response(self.existing_thread.attributes)
        self.save_and_reserialize({}, self.existing_thread)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "commentable_id": ["original_topic"],
                "thread_type": ["discussion"],
                "title": ["Original Title"],
                "body": ["Original body"],
                "anonymous": ["False"],
                "anonymous_to_peers": ["False"],
                "closed": ["False"],
                "pinned": ["False"],
                "user_id": [str(self.user.id)],
541
                "read": ["False"],
542 543 544
            }
        )

545 546
    @ddt.data(True, False)
    def test_update_all(self, read):
547 548 549 550 551 552
        self.register_put_thread_response(self.existing_thread.attributes)
        data = {
            "topic_id": "edited_topic",
            "type": "question",
            "title": "Edited Title",
            "raw_body": "Edited body",
553
            "read": read,
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        }
        saved = self.save_and_reserialize(data, self.existing_thread)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "commentable_id": ["edited_topic"],
                "thread_type": ["question"],
                "title": ["Edited Title"],
                "body": ["Edited body"],
                "anonymous": ["False"],
                "anonymous_to_peers": ["False"],
                "closed": ["False"],
                "pinned": ["False"],
                "user_id": [str(self.user.id)],
569
                "read": [str(read)],
570 571 572 573 574
            }
        )
        for key in data:
            self.assertEqual(saved[key], data[key])

575 576
    @ddt.data("", " ")
    def test_update_empty_string(self, value):
577 578
        serializer = ThreadSerializer(
            self.existing_thread,
579
            data={field: value for field in ["topic_id", "title", "raw_body"]},
580 581 582
            partial=True,
            context=get_context(self.course, self.request)
        )
583
        self.assertFalse(serializer.is_valid())
584 585
        self.assertEqual(
            serializer.errors,
586
            {field: ["This field may not be blank."] for field in ["topic_id", "title", "raw_body"]}
587 588 589 590 591 592 593 594 595
        )

    def test_update_course_id(self):
        serializer = ThreadSerializer(
            self.existing_thread,
            data={"course_id": "some/other/course"},
            partial=True,
            context=get_context(self.course, self.request)
        )
596
        self.assertFalse(serializer.is_valid())
597 598 599 600 601
        self.assertEqual(
            serializer.errors,
            {"course_id": ["This field is not allowed in an update."]}
        )

602 603

@ddt.ddt
604
class CommentSerializerDeserializationTest(ForumsEnableMixin, CommentsServiceMockMixin, SharedModuleStoreTestCase):
605
    """Tests for ThreadSerializer deserialization."""
606 607 608 609 610
    @classmethod
    def setUpClass(cls):
        super(CommentSerializerDeserializationTest, cls).setUpClass()
        cls.course = CourseFactory.create()

611 612 613 614 615 616 617 618 619 620 621 622 623
    def setUp(self):
        super(CommentSerializerDeserializationTest, 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("/dummy")
        self.request.user = self.user
        self.minimal_data = {
            "thread_id": "test_thread",
            "raw_body": "Test body",
        }
624 625 626 627 628
        self.existing_comment = Comment(**make_minimal_cs_comment({
            "id": "existing_comment",
            "thread_id": "existing_thread",
            "body": "Original body",
            "user_id": str(self.user.id),
629
            "username": self.user.username,
630 631
            "course_id": unicode(self.course.id),
        }))
632

633
    def save_and_reserialize(self, data, instance=None):
634 635 636 637 638 639 640
        """
        Create a serializer with the given data, ensure that it is valid, save
        the result, and return the full comment data from the serializer.
        """
        context = get_context(
            self.course,
            self.request,
641
            make_minimal_cs_thread({"course_id": unicode(self.course.id)})
642
        )
643 644 645 646 647 648
        serializer = CommentSerializer(
            instance,
            data=data,
            partial=(instance is not None),
            context=context
        )
649 650 651 652 653
        self.assertTrue(serializer.is_valid())
        serializer.save()
        return serializer.data

    @ddt.data(None, "test_parent")
654
    def test_create_success(self, parent_id):
655
        data = self.minimal_data.copy()
656
        if parent_id:
657
            data["parent_id"] = parent_id
658 659
            self.register_get_comment_response({"thread_id": "test_thread", "id": parent_id})
        self.register_post_comment_response(
660
            {"id": "test_comment", "username": self.user.username},
661
            thread_id="test_thread",
662 663
            parent_id=parent_id
        )
664
        saved = self.save_and_reserialize(data)
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        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)],
            }
        )
        self.assertEqual(saved["id"], "test_comment")
        self.assertEqual(saved["parent_id"], parent_id)

681 682 683 684 685 686
    def test_create_all_fields(self):
        data = self.minimal_data.copy()
        data["parent_id"] = "test_parent"
        data["endorsed"] = True
        self.register_get_comment_response({"thread_id": "test_thread", "id": "test_parent"})
        self.register_post_comment_response(
687
            {"id": "test_comment", "username": self.user.username},
688 689 690 691 692 693 694 695 696 697 698 699 700 701
            thread_id="test_thread",
            parent_id="test_parent"
        )
        self.save_and_reserialize(data)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "body": ["Test body"],
                "user_id": [str(self.user.id)],
                "endorsed": ["True"],
            }
        )

702
    def test_create_parent_id_nonexistent(self):
703
        self.register_get_comment_error_response("bad_parent", 404)
704 705 706 707
        data = self.minimal_data.copy()
        data["parent_id"] = "bad_parent"
        context = get_context(self.course, self.request, make_minimal_cs_thread())
        serializer = CommentSerializer(data=data, context=context)
708 709 710 711 712 713 714 715 716 717
        self.assertFalse(serializer.is_valid())
        self.assertEqual(
            serializer.errors,
            {
                "non_field_errors": [
                    "parent_id does not identify a comment in the thread identified by thread_id."
                ]
            }
        )

718
    def test_create_parent_id_wrong_thread(self):
719
        self.register_get_comment_response({"thread_id": "different_thread", "id": "test_parent"})
720 721 722 723
        data = self.minimal_data.copy()
        data["parent_id"] = "test_parent"
        context = get_context(self.course, self.request, make_minimal_cs_thread())
        serializer = CommentSerializer(data=data, context=context)
724 725 726 727 728 729 730 731 732 733
        self.assertFalse(serializer.is_valid())
        self.assertEqual(
            serializer.errors,
            {
                "non_field_errors": [
                    "parent_id does not identify a comment in the thread identified by thread_id."
                ]
            }
        )

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    @ddt.data(None, -1, 0, 2, 5)
    def test_create_parent_id_too_deep(self, max_depth):
        with mock.patch("django_comment_client.utils.MAX_COMMENT_DEPTH", max_depth):
            data = self.minimal_data.copy()
            context = get_context(self.course, self.request, make_minimal_cs_thread())
            if max_depth is None or max_depth >= 0:
                if max_depth != 0:
                    self.register_get_comment_response({
                        "id": "not_too_deep",
                        "thread_id": "test_thread",
                        "depth": max_depth - 1 if max_depth else 100
                    })
                    data["parent_id"] = "not_too_deep"
                else:
                    data["parent_id"] = None
                serializer = CommentSerializer(data=data, context=context)
                self.assertTrue(serializer.is_valid(), serializer.errors)
            if max_depth is not None:
                if max_depth >= 0:
                    self.register_get_comment_response({
                        "id": "too_deep",
                        "thread_id": "test_thread",
                        "depth": max_depth
                    })
                    data["parent_id"] = "too_deep"
                else:
                    data["parent_id"] = None
                serializer = CommentSerializer(data=data, context=context)
                self.assertFalse(serializer.is_valid())
763
                self.assertEqual(serializer.errors, {"non_field_errors": ["Comment level is too deep."]})
764

765
    def test_create_missing_field(self):
766 767 768 769 770 771 772 773 774 775 776 777
        for field in self.minimal_data:
            data = self.minimal_data.copy()
            data.pop(field)
            serializer = CommentSerializer(
                data=data,
                context=get_context(self.course, self.request, make_minimal_cs_thread())
            )
            self.assertFalse(serializer.is_valid())
            self.assertEqual(
                serializer.errors,
                {field: ["This field is required."]}
            )
778

779 780 781
    def test_create_endorsed(self):
        # TODO: The comments service doesn't populate the endorsement field on
        # comment creation, so this is sadly realistic
782
        self.register_post_comment_response({"username": self.user.username}, thread_id="test_thread")
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        data = self.minimal_data.copy()
        data["endorsed"] = True
        saved = self.save_and_reserialize(data)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "course_id": [unicode(self.course.id)],
                "body": ["Test body"],
                "user_id": [str(self.user.id)],
                "endorsed": ["True"],
            }
        )
        self.assertTrue(saved["endorsed"])
        self.assertIsNone(saved["endorsed_by"])
        self.assertIsNone(saved["endorsed_by_label"])
        self.assertIsNone(saved["endorsed_at"])

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    def test_update_empty(self):
        self.register_put_comment_response(self.existing_comment.attributes)
        self.save_and_reserialize({}, instance=self.existing_comment)
        self.assertEqual(
            httpretty.last_request().parsed_body,
            {
                "body": ["Original body"],
                "course_id": [unicode(self.course.id)],
                "user_id": [str(self.user.id)],
                "anonymous": ["False"],
                "anonymous_to_peers": ["False"],
                "endorsed": ["False"],
            }
        )

    def test_update_all(self):
816 817 818 819 820 821 822
        cs_response_data = self.existing_comment.attributes.copy()
        cs_response_data["endorsement"] = {
            "user_id": str(self.user.id),
            "time": "2015-06-05T00:00:00Z",
        }
        self.register_put_comment_response(cs_response_data)
        data = {"raw_body": "Edited body", "endorsed": True}
823 824 825 826 827 828 829 830 831
        saved = self.save_and_reserialize(data, instance=self.existing_comment)
        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"],
832 833
                "endorsed": ["True"],
                "endorsement_user_id": [str(self.user.id)],
834 835
            }
        )
836 837 838 839
        for key in data:
            self.assertEqual(saved[key], data[key])
        self.assertEqual(saved["endorsed_by"], self.user.username)
        self.assertEqual(saved["endorsed_at"], "2015-06-05T00:00:00Z")
840

841 842
    @ddt.data("", " ")
    def test_update_empty_raw_body(self, value):
843 844
        serializer = CommentSerializer(
            self.existing_comment,
845
            data={"raw_body": value},
846 847 848
            partial=True,
            context=get_context(self.course, self.request)
        )
849
        self.assertFalse(serializer.is_valid())
850 851
        self.assertEqual(
            serializer.errors,
852
            {"raw_body": ["This field may not be blank."]}
853 854 855 856 857 858 859 860 861 862
        )

    @ddt.data("thread_id", "parent_id")
    def test_update_non_updatable(self, field):
        serializer = CommentSerializer(
            self.existing_comment,
            data={field: "different_value"},
            partial=True,
            context=get_context(self.course, self.request)
        )
863
        self.assertFalse(serializer.is_valid())
864 865 866 867
        self.assertEqual(
            serializer.errors,
            {field: ["This field is not allowed in an update."]}
        )