tests.py 48.4 KB
Newer Older
1 2 3
"""
Tests for the EdxNotes app.
"""
4 5
import json
import urlparse
6
from contextlib import contextmanager
7 8 9
from datetime import datetime
from unittest import skipUnless

10
import ddt
11
import jwt
12
from django.conf import settings
13
from django.contrib.auth.models import AnonymousUser
14 15 16 17 18 19
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from django.test.utils import override_settings
from edx_oauth2_provider.tests.factories import ClientFactory
from mock import MagicMock, patch
20
from nose.plugins.attrib import attr
21
from provider.oauth2.models import Client
22

23 24 25
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module_for_descriptor
from courseware.tabs import get_course_tab_list
26 27 28 29
from edxmako.shortcuts import render_to_string
from edxnotes import helpers
from edxnotes.decorators import edxnotes
from edxnotes.exceptions import EdxNotesParseError, EdxNotesServiceUnavailable
30
from edxnotes.plugins import EdxNotesTab
31
from student.tests.factories import CourseEnrollmentFactory, UserFactory
32
from xmodule.modulestore import ModuleStoreEnum
33
from xmodule.modulestore.django import modulestore
34 35
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
36
from xmodule.tabs import CourseTab
37

38 39
FEATURES = settings.FEATURES.copy()

40
NOTES_API_EMPTY_RESPONSE = {
41 42 43 44 45 46 47 48 49 50
    "total": 0,
    "rows": [],
    "current_page": 1,
    "start": 0,
    "next": None,
    "previous": None,
    "num_pages": 0,
}

NOTES_VIEW_EMPTY_RESPONSE = {
51 52 53 54 55 56 57 58 59 60
    "count": 0,
    "results": [],
    "current_page": 1,
    "start": 0,
    "next": None,
    "previous": None,
    "num_pages": 0,
}


61 62 63 64
def enable_edxnotes_for_the_course(course, user_id):
    """
    Enable EdxNotes for the course.
    """
65
    course.tabs.append(CourseTab.load("edxnotes"))
66 67 68 69 70 71 72 73 74 75
    modulestore().update_item(course, user_id)


@edxnotes
class TestProblem(object):
    """
    Test class (fake problem) decorated by edxnotes decorator.

    The purpose of this class is to imitate any problem.
    """
76
    def __init__(self, course, user=None):
77 78
        self.system = MagicMock(is_author_mode=False)
        self.scope_ids = MagicMock(usage_id="test_usage_id")
79 80
        user = user or UserFactory()
        self.runtime = MagicMock(course_id=course.id, get_real_user=lambda __: user)
81 82 83 84 85 86 87 88 89 90
        self.descriptor = MagicMock()
        self.descriptor.runtime.modulestore.get_course.return_value = course

    def get_html(self):
        """
        Imitate get_html in module.
        """
        return "original_get_html"


91
@attr(shard=3)
92
@skipUnless(settings.FEATURES["ENABLE_EDXNOTES"], "EdxNotes feature needs to be enabled.")
93
class EdxNotesDecoratorTest(ModuleStoreTestCase):
94 95 96 97 98
    """
    Tests for edxnotes decorator.
    """

    def setUp(self):
99 100
        super(EdxNotesDecoratorTest, self).setUp()

101
        ClientFactory(name="edx-notes")
102 103
        # Using old mongo because of locator comparison issues (see longer
        # note below in EdxNotesHelpersTest setUp.
104 105 106
        self.course = CourseFactory(edxnotes=True, default_store=ModuleStoreEnum.Type.mongo)
        self.user = UserFactory()
        self.client.login(username=self.user.username, password=UserFactory._DEFAULT_PASSWORD)
107
        self.problem = TestProblem(self.course, self.user)
108 109

    @patch.dict("django.conf.settings.FEATURES", {'ENABLE_EDXNOTES': True})
110 111 112 113
    @patch("edxnotes.helpers.get_public_endpoint", autospec=True)
    @patch("edxnotes.helpers.get_token_url", autospec=True)
    @patch("edxnotes.helpers.get_edxnotes_id_token", autospec=True)
    @patch("edxnotes.helpers.generate_uid", autospec=True)
114 115 116 117 118
    def test_edxnotes_enabled(self, mock_generate_uid, mock_get_id_token, mock_get_token_url, mock_get_endpoint):
        """
        Tests if get_html is wrapped when feature flag is on and edxnotes are
        enabled for the course.
        """
119 120 121 122 123
        course = CourseFactory(edxnotes=True)
        enrollment = CourseEnrollmentFactory(course_id=course.id)
        user = enrollment.user
        problem = TestProblem(course, user)

124 125 126 127
        mock_generate_uid.return_value = "uid"
        mock_get_id_token.return_value = "token"
        mock_get_token_url.return_value = "/tokenUrl"
        mock_get_endpoint.return_value = "/endpoint"
128
        enable_edxnotes_for_the_course(course, user.id)
129 130 131 132 133
        expected_context = {
            "content": "original_get_html",
            "uid": "uid",
            "edxnotes_visibility": "true",
            "params": {
134 135
                "usageId": "test_usage_id",
                "courseId": course.id,
136 137 138 139
                "token": "token",
                "tokenUrl": "/tokenUrl",
                "endpoint": "/endpoint",
                "debug": settings.DEBUG,
140
                "eventStringLimit": settings.TRACK_MAX_EVENT / 6,
141 142 143
            },
        }
        self.assertEqual(
144
            problem.get_html(),
145 146 147 148 149 150 151 152 153
            render_to_string("edxnotes_wrapper.html", expected_context),
        )

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    def test_edxnotes_disabled_if_edxnotes_flag_is_false(self):
        """
        Tests that get_html is wrapped when feature flag is on, but edxnotes are
        disabled for the course.
        """
154
        self.course.edxnotes = False
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        self.assertEqual("original_get_html", self.problem.get_html())

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": False})
    def test_edxnotes_disabled(self):
        """
        Tests that get_html is not wrapped when feature flag is off.
        """
        self.assertEqual("original_get_html", self.problem.get_html())

    def test_edxnotes_studio(self):
        """
        Tests that get_html is not wrapped when problem is rendered in Studio.
        """
        self.problem.system.is_author_mode = True
        self.assertEqual("original_get_html", self.problem.get_html())

    def test_edxnotes_harvard_notes_enabled(self):
        """
        Tests that get_html is not wrapped when Harvard Annotation Tool is enabled.
        """
        self.course.advanced_modules = ["videoannotation", "imageannotation", "textannotation"]
        enable_edxnotes_for_the_course(self.course, self.user.id)
        self.assertEqual("original_get_html", self.problem.get_html())

179 180 181 182 183 184 185
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    def test_anonymous_user(self):
        user = AnonymousUser()
        problem = TestProblem(self.course, user)
        enable_edxnotes_for_the_course(self.course, None)
        assert problem.get_html() == "original_get_html"

186

187
@attr(shard=3)
188
@skipUnless(settings.FEATURES["ENABLE_EDXNOTES"], "EdxNotes feature needs to be enabled.")
189
@ddt.ddt
190 191 192 193 194 195 196 197 198 199
class EdxNotesHelpersTest(ModuleStoreTestCase):
    """
    Tests for EdxNotes helpers.
    """
    def setUp(self):
        """
        Setup a dummy course content.
        """
        super(EdxNotesHelpersTest, self).setUp()

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        # There are many tests that are comparing locators as returned from helper methods. When using
        # the split modulestore, some of those locators have version and branch information, but the
        # comparison values do not. This needs further investigation in order to enable these tests
        # with the split modulestore.
        with self.store.default_store(ModuleStoreEnum.Type.mongo):
            ClientFactory(name="edx-notes")
            self.course = CourseFactory.create()
            self.chapter = ItemFactory.create(category="chapter", parent_location=self.course.location)
            self.chapter_2 = ItemFactory.create(category="chapter", parent_location=self.course.location)
            self.sequential = ItemFactory.create(category="sequential", parent_location=self.chapter.location)
            self.vertical = ItemFactory.create(category="vertical", parent_location=self.sequential.location)
            self.html_module_1 = ItemFactory.create(category="html", parent_location=self.vertical.location)
            self.html_module_2 = ItemFactory.create(category="html", parent_location=self.vertical.location)
            self.vertical_with_container = ItemFactory.create(
                category='vertical', parent_location=self.sequential.location
            )
            self.child_container = ItemFactory.create(
                category='split_test', parent_location=self.vertical_with_container.location)
            self.child_vertical = ItemFactory.create(category='vertical', parent_location=self.child_container.location)
            self.child_html_module = ItemFactory.create(category="html", parent_location=self.child_vertical.location)

            # Read again so that children lists are accurate
            self.course = self.store.get_item(self.course.location)
            self.chapter = self.store.get_item(self.chapter.location)
            self.chapter_2 = self.store.get_item(self.chapter_2.location)
            self.sequential = self.store.get_item(self.sequential.location)
            self.vertical = self.store.get_item(self.vertical.location)

            self.vertical_with_container = self.store.get_item(self.vertical_with_container.location)
            self.child_container = self.store.get_item(self.child_container.location)
            self.child_vertical = self.store.get_item(self.child_vertical.location)
            self.child_html_module = self.store.get_item(self.child_html_module.location)

233 234
            self.user = UserFactory()
            self.client.login(username=self.user.username, password=UserFactory._DEFAULT_PASSWORD)
235

236 237 238
        self.request = RequestFactory().request()
        self.request.user = self.user

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    def _get_unit_url(self, course, chapter, section, position=1):
        """
        Returns `jump_to_id` url for the `vertical`.
        """
        return reverse('courseware_position', kwargs={
            'course_id': course.id,
            'chapter': chapter.url_name,
            'section': section.url_name,
            'position': position,
        })

    def test_edxnotes_harvard_notes_enabled(self):
        """
        Tests that edxnotes are disabled when Harvard Annotation Tool is enabled.
        """
254 255
        self.course.advanced_modules = ['imageannotation', 'textannotation', 'videoannotation']
        assert not helpers.is_feature_enabled(self.course, self.user)
256

257 258
    @ddt.data(True, False)
    def test_is_feature_enabled(self, enabled):
259
        """
260
        Tests that is_feature_enabled shows correct behavior.
261
        """
262 263 264
        course = CourseFactory(edxnotes=enabled)
        enrollment = CourseEnrollmentFactory(course_id=course.id)
        assert helpers.is_feature_enabled(course, enrollment.user) == enabled
265

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    @ddt.data(
        helpers.get_public_endpoint,
        helpers.get_internal_endpoint,
    )
    def test_get_endpoints(self, get_endpoint_function):
        """
        Test that the get_public_endpoint and get_internal_endpoint functions
        return appropriate values.
        """
        @contextmanager
        def patch_edxnotes_api_settings(url):
            """
            Convenience function for patching both EDXNOTES_PUBLIC_API and
            EDXNOTES_INTERNAL_API.
            """
            with override_settings(EDXNOTES_PUBLIC_API=url):
                with override_settings(EDXNOTES_INTERNAL_API=url):
                    yield

285
        # url ends with "/"
286 287
        with patch_edxnotes_api_settings("http://example.com/"):
            self.assertEqual("http://example.com/", get_endpoint_function())
288 289

        # url doesn't have "/" at the end
290 291
        with patch_edxnotes_api_settings("http://example.com"):
            self.assertEqual("http://example.com/", get_endpoint_function())
292 293

        # url with path that starts with "/"
294 295
        with patch_edxnotes_api_settings("http://example.com"):
            self.assertEqual("http://example.com/some_path/", get_endpoint_function("/some_path"))
296 297

        # url with path without "/"
298 299
        with patch_edxnotes_api_settings("http://example.com"):
            self.assertEqual("http://example.com/some_path/", get_endpoint_function("some_path/"))
300 301

        # url is not configured
302 303
        with patch_edxnotes_api_settings(None):
            self.assertRaises(ImproperlyConfigured, get_endpoint_function)
304

305
    @patch("edxnotes.helpers.requests.get", autospec=True)
306 307 308 309
    def test_get_notes_correct_data(self, mock_get):
        """
        Tests the result if correct data is received.
        """
310
        mock_get.return_value.content = json.dumps(
311
            {
312
                "total": 2,
313 314 315 316 317
                "current_page": 1,
                "start": 0,
                "next": None,
                "previous": None,
                "num_pages": 1,
318
                "rows": [
319 320 321 322 323 324 325 326 327 328 329 330 331
                    {
                        u"quote": u"quote text",
                        u"text": u"text",
                        u"usage_id": unicode(self.html_module_1.location),
                        u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000).isoformat(),
                    },
                    {
                        u"quote": u"quote text",
                        u"text": u"text",
                        u"usage_id": unicode(self.html_module_2.location),
                        u"updated": datetime(2014, 11, 19, 8, 6, 16, 00000).isoformat(),
                    }
                ]
332
            }
333
        )
334 335

        self.assertItemsEqual(
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
            {
                "count": 2,
                "current_page": 1,
                "start": 0,
                "next": None,
                "previous": None,
                "num_pages": 1,
                "results": [
                    {
                        u"quote": u"quote text",
                        u"text": u"text",
                        u"chapter": {
                            u"display_name": self.chapter.display_name_with_default_escaped,
                            u"index": 0,
                            u"location": unicode(self.chapter.location),
                            u"children": [unicode(self.sequential.location)]
                        },
                        u"section": {
                            u"display_name": self.sequential.display_name_with_default_escaped,
                            u"location": unicode(self.sequential.location),
                            u"children": [
                                unicode(self.vertical.location), unicode(self.vertical_with_container.location)
                            ]
                        },
                        u"unit": {
                            u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
                            u"display_name": self.vertical.display_name_with_default_escaped,
                            u"location": unicode(self.vertical.location),
                        },
                        u"usage_id": unicode(self.html_module_2.location),
                        u"updated": "Nov 19, 2014 at 08:06 UTC",
367
                    },
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
                    {
                        u"quote": u"quote text",
                        u"text": u"text",
                        u"chapter": {
                            u"display_name": self.chapter.display_name_with_default_escaped,
                            u"index": 0,
                            u"location": unicode(self.chapter.location),
                            u"children": [unicode(self.sequential.location)]
                        },
                        u"section": {
                            u"display_name": self.sequential.display_name_with_default_escaped,
                            u"location": unicode(self.sequential.location),
                            u"children": [
                                unicode(self.vertical.location),
                                unicode(self.vertical_with_container.location)]
                        },
                        u"unit": {
                            u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
                            u"display_name": self.vertical.display_name_with_default_escaped,
                            u"location": unicode(self.vertical.location),
                        },
                        u"usage_id": unicode(self.html_module_1.location),
                        u"updated": "Nov 19, 2014 at 08:05 UTC",
391
                    },
392 393
                ]
            },
394
            helpers.get_notes(self.request, self.course)
395 396
        )

397
    @patch("edxnotes.helpers.requests.get", autospec=True)
398 399 400 401 402
    def test_get_notes_json_error(self, mock_get):
        """
        Tests the result if incorrect json is received.
        """
        mock_get.return_value.content = "Error"
403
        self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
404

405
    @patch("edxnotes.helpers.requests.get", autospec=True)
406 407
    def test_get_notes_empty_collection(self, mock_get):
        """
408
        Tests the result if an empty response is received.
409
        """
410 411
        mock_get.return_value.content = json.dumps({})
        self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
412

413
    @patch("edxnotes.helpers.requests.get", autospec=True)
414 415 416 417 418
    def test_search_correct_data(self, mock_get):
        """
        Tests the result if correct data is received.
        """
        mock_get.return_value.content = json.dumps({
419
            "total": 2,
420 421 422 423 424
            "current_page": 1,
            "start": 0,
            "next": None,
            "previous": None,
            "num_pages": 1,
425
            "rows": [
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
                {
                    u"quote": u"quote text",
                    u"text": u"text",
                    u"usage_id": unicode(self.html_module_1.location),
                    u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000).isoformat(),
                },
                {
                    u"quote": u"quote text",
                    u"text": u"text",
                    u"usage_id": unicode(self.html_module_2.location),
                    u"updated": datetime(2014, 11, 19, 8, 6, 16, 00000).isoformat(),
                }
            ]
        })

        self.assertItemsEqual(
            {
443 444 445 446 447 448 449
                "count": 2,
                "current_page": 1,
                "start": 0,
                "next": None,
                "previous": None,
                "num_pages": 1,
                "results": [
450 451 452 453
                    {
                        u"quote": u"quote text",
                        u"text": u"text",
                        u"chapter": {
454
                            u"display_name": self.chapter.display_name_with_default_escaped,
455 456 457 458 459
                            u"index": 0,
                            u"location": unicode(self.chapter.location),
                            u"children": [unicode(self.sequential.location)]
                        },
                        u"section": {
460
                            u"display_name": self.sequential.display_name_with_default_escaped,
461 462 463 464 465 466 467
                            u"location": unicode(self.sequential.location),
                            u"children": [
                                unicode(self.vertical.location),
                                unicode(self.vertical_with_container.location)]
                        },
                        u"unit": {
                            u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
468
                            u"display_name": self.vertical.display_name_with_default_escaped,
469 470 471 472 473 474 475 476 477
                            u"location": unicode(self.vertical.location),
                        },
                        u"usage_id": unicode(self.html_module_2.location),
                        u"updated": "Nov 19, 2014 at 08:06 UTC",
                    },
                    {
                        u"quote": u"quote text",
                        u"text": u"text",
                        u"chapter": {
478
                            u"display_name": self.chapter.display_name_with_default_escaped,
479 480 481 482 483
                            u"index": 0,
                            u"location": unicode(self.chapter.location),
                            u"children": [unicode(self.sequential.location)]
                        },
                        u"section": {
484
                            u"display_name": self.sequential.display_name_with_default_escaped,
485 486 487 488 489 490 491
                            u"location": unicode(self.sequential.location),
                            u"children": [
                                unicode(self.vertical.location),
                                unicode(self.vertical_with_container.location)]
                        },
                        u"unit": {
                            u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
492
                            u"display_name": self.vertical.display_name_with_default_escaped,
493 494 495 496 497 498 499
                            u"location": unicode(self.vertical.location),
                        },
                        u"usage_id": unicode(self.html_module_1.location),
                        u"updated": "Nov 19, 2014 at 08:05 UTC",
                    },
                ]
            },
500
            helpers.get_notes(self.request, self.course)
501 502
        )

503
    @patch("edxnotes.helpers.requests.get", autospec=True)
504 505 506 507 508
    def test_search_json_error(self, mock_get):
        """
        Tests the result if incorrect json is received.
        """
        mock_get.return_value.content = "Error"
509
        self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
510

511
    @patch("edxnotes.helpers.requests.get", autospec=True)
512 513 514 515 516
    def test_search_wrong_data_format(self, mock_get):
        """
        Tests the result if incorrect data structure is received.
        """
        mock_get.return_value.content = json.dumps({"1": 2})
517
        self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
518

519
    @patch("edxnotes.helpers.requests.get", autospec=True)
520 521 522 523
    def test_search_empty_collection(self, mock_get):
        """
        Tests no results.
        """
524
        mock_get.return_value.content = json.dumps(NOTES_API_EMPTY_RESPONSE)
525
        self.assertItemsEqual(
526
            NOTES_VIEW_EMPTY_RESPONSE,
527
            helpers.get_notes(self.request, self.course)
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        )

    def test_preprocess_collection_no_item(self):
        """
        Tests the result if appropriate module is not found.
        """
        initial_collection = [
            {
                u"quote": u"quote text",
                u"text": u"text",
                u"usage_id": unicode(self.html_module_1.location),
                u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000).isoformat()
            },
            {
                u"quote": u"quote text",
                u"text": u"text",
                u"usage_id": unicode(self.course.id.make_usage_key("html", "test_item")),
                u"updated": datetime(2014, 11, 19, 8, 6, 16, 00000).isoformat()
            },
        ]

        self.assertItemsEqual(
            [{
                u"quote": u"quote text",
                u"text": u"text",
                u"chapter": {
554
                    u"display_name": self.chapter.display_name_with_default_escaped,
555 556 557 558 559
                    u"index": 0,
                    u"location": unicode(self.chapter.location),
                    u"children": [unicode(self.sequential.location)]
                },
                u"section": {
560
                    u"display_name": self.sequential.display_name_with_default_escaped,
561 562 563 564 565
                    u"location": unicode(self.sequential.location),
                    u"children": [unicode(self.vertical.location), unicode(self.vertical_with_container.location)]
                },
                u"unit": {
                    u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
566
                    u"display_name": self.vertical.display_name_with_default_escaped,
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
                    u"location": unicode(self.vertical.location),
                },
                u"usage_id": unicode(self.html_module_1.location),
                u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000),
            }],
            helpers.preprocess_collection(self.user, self.course, initial_collection)
        )

    def test_preprocess_collection_has_access(self):
        """
        Tests the result if the user does not have access to some of the modules.
        """
        initial_collection = [
            {
                u"quote": u"quote text",
                u"text": u"text",
                u"usage_id": unicode(self.html_module_1.location),
                u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000).isoformat(),
            },
            {
                u"quote": u"quote text",
                u"text": u"text",
                u"usage_id": unicode(self.html_module_2.location),
                u"updated": datetime(2014, 11, 19, 8, 6, 16, 00000).isoformat(),
            },
        ]
        self.html_module_2.visible_to_staff_only = True
        self.store.update_item(self.html_module_2, self.user.id)
        self.assertItemsEqual(
            [{
                u"quote": u"quote text",
                u"text": u"text",
                u"chapter": {
600
                    u"display_name": self.chapter.display_name_with_default_escaped,
601 602 603 604 605
                    u"index": 0,
                    u"location": unicode(self.chapter.location),
                    u"children": [unicode(self.sequential.location)]
                },
                u"section": {
606
                    u"display_name": self.sequential.display_name_with_default_escaped,
607 608 609 610 611
                    u"location": unicode(self.sequential.location),
                    u"children": [unicode(self.vertical.location), unicode(self.vertical_with_container.location)]
                },
                u"unit": {
                    u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
612
                    u"display_name": self.vertical.display_name_with_default_escaped,
613 614 615 616 617 618 619 620
                    u"location": unicode(self.vertical.location),
                },
                u"usage_id": unicode(self.html_module_1.location),
                u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000),
            }],
            helpers.preprocess_collection(self.user, self.course, initial_collection)
        )

621 622
    @patch("edxnotes.helpers.has_access", autospec=True)
    @patch("edxnotes.helpers.modulestore", autospec=True)
623 624 625 626 627
    def test_preprocess_collection_no_unit(self, mock_modulestore, mock_has_access):
        """
        Tests the result if the unit does not exist.
        """
        store = MagicMock()
628
        store.get_item().get_parent.return_value = None
629 630 631 632 633 634 635 636 637 638 639 640 641
        mock_modulestore.return_value = store
        mock_has_access.return_value = True
        initial_collection = [{
            u"quote": u"quote text",
            u"text": u"text",
            u"usage_id": unicode(self.html_module_1.location),
            u"updated": datetime(2014, 11, 19, 8, 5, 16, 00000).isoformat(),
        }]

        self.assertItemsEqual(
            [], helpers.preprocess_collection(self.user, self.course, initial_collection)
        )

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    @override_settings(NOTES_DISABLED_TABS=['course_structure', 'tags'])
    def test_preprocess_collection_with_disabled_tabs(self, ):
        """
        Tests that preprocess collection returns correct data if `course_structure` and `tags` are disabled.
        """
        initial_collection = [
            {
                u"quote": u"quote text1",
                u"text": u"text1",
                u"usage_id": unicode(self.html_module_1.location),
                u"updated": datetime(2016, 01, 26, 8, 5, 16, 00000).isoformat(),
            },
            {
                u"quote": u"quote text2",
                u"text": u"text2",
                u"usage_id": unicode(self.html_module_2.location),
                u"updated": datetime(2016, 01, 26, 9, 6, 17, 00000).isoformat(),
            },
        ]

        self.assertItemsEqual(
            [
                {

                    'section': {},
                    'chapter': {},
                    "unit": {
                        u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
                        u"display_name": self.vertical.display_name_with_default_escaped,
                        u"location": unicode(self.vertical.location),
                    },
                    u'text': u'text1',
                    u'quote': u'quote text1',
                    u'usage_id': unicode(self.html_module_1.location),
                    u'updated': datetime(2016, 01, 26, 8, 5, 16)
                },
                {
                    'section': {},
                    'chapter': {},
                    "unit": {
                        u"url": self._get_unit_url(self.course, self.chapter, self.sequential),
                        u"display_name": self.vertical.display_name_with_default_escaped,
                        u"location": unicode(self.vertical.location),
                    },
                    u'text': u'text2',
                    u'quote': u'quote text2',
                    u'usage_id': unicode(self.html_module_2.location),
                    u'updated': datetime(2016, 01, 26, 9, 6, 17)
                }
            ],
            helpers.preprocess_collection(self.user, self.course, initial_collection)
        )

695 696 697 698 699 700
    def test_get_module_context_sequential(self):
        """
        Tests `get_module_context` method for the sequential.
        """
        self.assertDictEqual(
            {
701
                u"display_name": self.sequential.display_name_with_default_escaped,
702 703 704 705 706 707 708 709 710 711 712 713
                u"location": unicode(self.sequential.location),
                u"children": [unicode(self.vertical.location), unicode(self.vertical_with_container.location)],
            },
            helpers.get_module_context(self.course, self.sequential)
        )

    def test_get_module_context_html_component(self):
        """
        Tests `get_module_context` method for the components.
        """
        self.assertDictEqual(
            {
714
                u"display_name": self.html_module_1.display_name_with_default_escaped,
715 716 717 718 719 720 721 722 723 724 725
                u"location": unicode(self.html_module_1.location),
            },
            helpers.get_module_context(self.course, self.html_module_1)
        )

    def test_get_module_context_chapter(self):
        """
        Tests `get_module_context` method for the chapters.
        """
        self.assertDictEqual(
            {
726
                u"display_name": self.chapter.display_name_with_default_escaped,
727 728 729 730 731 732 733 734
                u"index": 0,
                u"location": unicode(self.chapter.location),
                u"children": [unicode(self.sequential.location)],
            },
            helpers.get_module_context(self.course, self.chapter)
        )
        self.assertDictEqual(
            {
735
                u"display_name": self.chapter_2.display_name_with_default_escaped,
736 737 738 739 740 741 742
                u"index": 1,
                u"location": unicode(self.chapter_2.location),
                u"children": [],
            },
            helpers.get_module_context(self.course, self.chapter_2)
        )

743 744
    @override_settings(EDXNOTES_PUBLIC_API="http://example.com")
    @override_settings(EDXNOTES_INTERNAL_API="http://example.com")
745 746 747
    @patch("edxnotes.helpers.anonymous_id_for_user", autospec=True)
    @patch("edxnotes.helpers.get_edxnotes_id_token", autospec=True)
    @patch("edxnotes.helpers.requests.get", autospec=True)
748
    def test_send_request_with_text_param(self, mock_get, mock_get_id_token, mock_anonymous_id_for_user):
749 750 751 752 753 754
        """
        Tests that requests are send with correct information.
        """
        mock_get_id_token.return_value = "test_token"
        mock_anonymous_id_for_user.return_value = "anonymous_id"
        helpers.send_request(
755 756 757 758 759 760
            self.user,
            self.course.id,
            path="test",
            text="text",
            page=helpers.DEFAULT_PAGE,
            page_size=helpers.DEFAULT_PAGE_SIZE
761 762 763 764 765 766 767 768 769 770 771
        )
        mock_get.assert_called_with(
            "http://example.com/test/",
            headers={
                "x-annotator-auth-token": "test_token"
            },
            params={
                "user": "anonymous_id",
                "course_id": unicode(self.course.id),
                "text": "text",
                "highlight": True,
772
                'page': 1,
773
                'page_size': 25,
774 775
            },
            timeout=(settings.EDXNOTES_CONNECT_TIMEOUT, settings.EDXNOTES_READ_TIMEOUT)
776 777
        )

778 779
    @override_settings(EDXNOTES_PUBLIC_API="http://example.com")
    @override_settings(EDXNOTES_INTERNAL_API="http://example.com")
780 781 782
    @patch("edxnotes.helpers.anonymous_id_for_user", autospec=True)
    @patch("edxnotes.helpers.get_edxnotes_id_token", autospec=True)
    @patch("edxnotes.helpers.requests.get", autospec=True)
783
    def test_send_request_without_text_param(self, mock_get, mock_get_id_token, mock_anonymous_id_for_user):
784 785 786 787 788 789
        """
        Tests that requests are send with correct information.
        """
        mock_get_id_token.return_value = "test_token"
        mock_anonymous_id_for_user.return_value = "anonymous_id"
        helpers.send_request(
790
            self.user, self.course.id, path="test", page=1, page_size=25
791 792 793 794 795 796 797 798 799
        )
        mock_get.assert_called_with(
            "http://example.com/test/",
            headers={
                "x-annotator-auth-token": "test_token"
            },
            params={
                "user": "anonymous_id",
                "course_id": unicode(self.course.id),
800 801
                'page': helpers.DEFAULT_PAGE,
                'page_size': helpers.DEFAULT_PAGE_SIZE,
802 803
            },
            timeout=(settings.EDXNOTES_CONNECT_TIMEOUT, settings.EDXNOTES_READ_TIMEOUT)
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
        )

    def test_get_course_position_no_chapter(self):
        """
        Returns `None` if no chapter found.
        """
        mock_course_module = MagicMock()
        mock_course_module.position = 3
        mock_course_module.get_display_items.return_value = []
        self.assertIsNone(helpers.get_course_position(mock_course_module))

    def test_get_course_position_to_chapter(self):
        """
        Returns a position that leads to COURSE/CHAPTER if this isn't the users's
        first time.
        """
        mock_course_module = MagicMock(id=self.course.id, position=3)

        mock_chapter = MagicMock()
        mock_chapter.url_name = 'chapter_url_name'
824
        mock_chapter.display_name_with_default_escaped = 'Test Chapter Display Name'
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853

        mock_course_module.get_display_items.return_value = [mock_chapter]

        self.assertEqual(helpers.get_course_position(mock_course_module), {
            'display_name': 'Test Chapter Display Name',
            'url': '/courses/{}/courseware/chapter_url_name/'.format(self.course.id),
        })

    def test_get_course_position_no_section(self):
        """
        Returns `None` if no section found.
        """
        mock_course_module = MagicMock(id=self.course.id, position=None)
        mock_course_module.get_display_items.return_value = [MagicMock()]
        self.assertIsNone(helpers.get_course_position(mock_course_module))

    def test_get_course_position_to_section(self):
        """
        Returns a position that leads to COURSE/CHAPTER/SECTION if this is the
        user's first time.
        """
        mock_course_module = MagicMock(id=self.course.id, position=None)

        mock_chapter = MagicMock()
        mock_chapter.url_name = 'chapter_url_name'
        mock_course_module.get_display_items.return_value = [mock_chapter]

        mock_section = MagicMock()
        mock_section.url_name = 'section_url_name'
854
        mock_section.display_name_with_default_escaped = 'Test Section Display Name'
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

        mock_chapter.get_display_items.return_value = [mock_section]
        mock_section.get_display_items.return_value = [MagicMock()]

        self.assertEqual(helpers.get_course_position(mock_course_module), {
            'display_name': 'Test Section Display Name',
            'url': '/courses/{}/courseware/chapter_url_name/section_url_name/'.format(self.course.id),
        })

    def test_get_index(self):
        """
        Tests `get_index` method returns unit url.
        """
        children = self.sequential.children
        self.assertEqual(0, helpers.get_index(unicode(self.vertical.location), children))
        self.assertEqual(1, helpers.get_index(unicode(self.vertical_with_container.location), children))

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    @ddt.unpack
    @ddt.data(
        {'previous_api_url': None, 'next_api_url': None},
        {'previous_api_url': None, 'next_api_url': 'edxnotes/?course_id=abc&page=2&page_size=10&user=123'},
        {'previous_api_url': 'edxnotes.org/?course_id=abc&page=2&page_size=10&user=123', 'next_api_url': None},
        {
            'previous_api_url': 'edxnotes.org/?course_id=abc&page_size=10&user=123',
            'next_api_url': 'edxnotes.org/?course_id=abc&page=3&page_size=10&user=123'
        },
        {
            'previous_api_url': 'edxnotes.org/?course_id=abc&page=2&page_size=10&text=wow&user=123',
            'next_api_url': 'edxnotes.org/?course_id=abc&page=4&page_size=10&text=wow&user=123'
        },
    )
    def test_construct_url(self, previous_api_url, next_api_url):
        """
        Verify that `construct_url` works correctly.
        """
        # make absolute url
        # pylint: disable=no-member
        if self.request.is_secure():
            host = 'https://' + self.request.get_host()
        else:
            host = 'http://' + self.request.get_host()
        notes_url = host + reverse("notes", args=[unicode(self.course.id)])

        def verify_url(constructed, expected):
            """
            Verify that constructed url is correct.
            """
            # if api url is None then constructed url should also be None
            if expected is None:
                self.assertEqual(expected, constructed)
            else:
                # constructed url should startswith notes view url instead of api view url
                self.assertTrue(constructed.startswith(notes_url))

                # constructed url should not contain extra params
                self.assertNotIn('user', constructed)

                # constructed url should only has these params if present in api url
                allowed_params = ('page', 'page_size', 'text')

                # extract query params from constructed url
                parsed = urlparse.urlparse(constructed)
                params = urlparse.parse_qs(parsed.query)

                # verify that constructed url has only correct params and params have correct values
                for param, value in params.items():
                    self.assertIn(param, allowed_params)
                    self.assertIn('{}={}'.format(param, value[0]), expected)

        next_url, previous_url = helpers.construct_pagination_urls(
            self.request,
            self.course.id,
            next_api_url, previous_api_url
        )
        verify_url(next_url, next_api_url)
        verify_url(previous_url, previous_api_url)

932

933
@attr(shard=3)
934
@skipUnless(settings.FEATURES["ENABLE_EDXNOTES"], "EdxNotes feature needs to be enabled.")
935
@ddt.ddt
936
class EdxNotesViewsTest(ModuleStoreTestCase):
937 938 939 940 941 942
    """
    Tests for EdxNotes views.
    """
    def setUp(self):
        ClientFactory(name="edx-notes")
        super(EdxNotesViewsTest, self).setUp()
943 944 945 946
        self.course = CourseFactory(edxnotes=True)
        self.user = UserFactory()
        CourseEnrollmentFactory(user=self.user, course_id=self.course.id)
        self.client.login(username=self.user.username, password=UserFactory._DEFAULT_PASSWORD)
947
        self.notes_page_url = reverse("edxnotes", args=[unicode(self.course.id)])
948
        self.notes_url = reverse("notes", args=[unicode(self.course.id)])
949 950 951 952 953 954 955 956
        self.get_token_url = reverse("get_token", args=[unicode(self.course.id)])
        self.visibility_url = reverse("edxnotes_visibility", args=[unicode(self.course.id)])

    def _get_course_module(self):
        """
        Returns the course module.
        """
        field_data_cache = FieldDataCache([self.course], self.course.id, self.user)
957 958 959
        return get_module_for_descriptor(
            self.user, MagicMock(), self.course, field_data_cache, self.course.id, course=self.course
        )
960

961 962 963 964 965 966 967 968 969
    def test_edxnotes_tab(self):
        """
        Tests that edxnotes tab is shown only when the feature is enabled.
        """
        def has_notes_tab(user, course):
            """Returns true if the "Notes" tab is shown."""
            request = RequestFactory().request()
            request.user = user
            tabs = get_course_tab_list(request, course)
970
            return len([tab for tab in tabs if tab.type == 'edxnotes']) == 1
971 972 973

        self.assertFalse(has_notes_tab(self.user, self.course))
        enable_edxnotes_for_the_course(self.course, self.user.id)
974 975 976 977 978 979
        # disable course.edxnotes
        self.course.edxnotes = False
        self.assertFalse(has_notes_tab(self.user, self.course))

        # reenable course.edxnotes
        self.course.edxnotes = True
980 981
        self.assertTrue(has_notes_tab(self.user, self.course))

982 983
    # pylint: disable=unused-argument
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
984
    @patch("edxnotes.views.get_notes", return_value={'results': []})
985 986 987 988 989 990
    def test_edxnotes_view_is_enabled(self, mock_get_notes):
        """
        Tests that appropriate view is received if EdxNotes feature is enabled.
        """
        enable_edxnotes_for_the_course(self.course, self.user.id)
        response = self.client.get(self.notes_page_url)
991
        self.assertContains(response, 'Highlights and notes you've made in course content')
992

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    # pylint: disable=unused-argument
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    @patch("edxnotes.views.get_notes", return_value={'results': []})
    @patch("edxnotes.views.get_course_position", return_value={'display_name': 'Section 1', 'url': 'test_url'})
    def test_edxnotes_html_tags_should_not_be_escaped(self, mock_get_notes, mock_position):
        """
        Tests that explicit html tags rendered correctly.
        """
        enable_edxnotes_for_the_course(self.course, self.user.id)
        response = self.client.get(self.notes_page_url)
        self.assertContains(
            response,
            'Get started by making a note in something you just read, like <a href="test_url">Section 1</a>'
        )

1008 1009 1010 1011 1012 1013 1014 1015 1016
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": False})
    def test_edxnotes_view_is_disabled(self):
        """
        Tests that 404 status code is received if EdxNotes feature is disabled.
        """
        response = self.client.get(self.notes_page_url)
        self.assertEqual(response.status_code, 404)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
1017
    @patch("edxnotes.views.get_notes", autospec=True)
1018 1019
    def test_search_notes_successfully_respond(self, mock_search):
        """
1020
        Tests that search notes successfully respond if EdxNotes feature is enabled.
1021
        """
1022
        mock_search.return_value = NOTES_VIEW_EMPTY_RESPONSE
1023
        enable_edxnotes_for_the_course(self.course, self.user.id)
1024
        response = self.client.get(self.notes_url, {"text": "test"})
1025
        self.assertEqual(json.loads(response.content), NOTES_VIEW_EMPTY_RESPONSE)
1026 1027 1028
        self.assertEqual(response.status_code, 200)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": False})
1029
    def test_search_notes_is_disabled(self):
1030 1031 1032
        """
        Tests that 404 status code is received if EdxNotes feature is disabled.
        """
1033
        response = self.client.get(self.notes_url, {"text": "test"})
1034 1035 1036
        self.assertEqual(response.status_code, 404)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
1037 1038
    @patch("edxnotes.views.get_notes", autospec=True)
    def test_search_500_service_unavailable(self, mock_search):
1039
        """
1040
        Tests that 500 status code is received if EdxNotes service is unavailable.
1041 1042 1043
        """
        mock_search.side_effect = EdxNotesServiceUnavailable
        enable_edxnotes_for_the_course(self.course, self.user.id)
1044
        response = self.client.get(self.notes_url, {"text": "test"})
1045 1046 1047 1048
        self.assertEqual(response.status_code, 500)
        self.assertIn("error", response.content)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
1049
    @patch("edxnotes.views.get_notes", autospec=True)
1050 1051 1052 1053 1054 1055 1056
    def test_search_notes_exception(self, mock_search):
        """
        Tests that 500 status code is received if invalid data was received from
        EdXNotes service.
        """
        mock_search.side_effect = EdxNotesParseError
        enable_edxnotes_for_the_course(self.course, self.user.id)
1057
        response = self.client.get(self.notes_url, {"text": "test"})
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        self.assertEqual(response.status_code, 500)
        self.assertIn("error", response.content)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    def test_get_id_token(self):
        """
        Test generation of ID Token.
        """
        response = self.client.get(self.get_token_url)
        self.assertEqual(response.status_code, 200)
        client = Client.objects.get(name='edx-notes')
1069
        jwt.decode(response.content, client.client_secret, audience=client.client_id)
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 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

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    def test_get_id_token_anonymous(self):
        """
        Test that generation of ID Token does not work for anonymous user.
        """
        self.client.logout()
        response = self.client.get(self.get_token_url)
        self.assertEqual(response.status_code, 302)

    def test_edxnotes_visibility(self):
        """
        Can update edxnotes_visibility value successfully.
        """
        enable_edxnotes_for_the_course(self.course, self.user.id)
        response = self.client.post(
            self.visibility_url,
            data=json.dumps({"visibility": False}),
            content_type="application/json",
        )
        self.assertEqual(response.status_code, 200)
        course_module = self._get_course_module()
        self.assertFalse(course_module.edxnotes_visibility)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": False})
    def test_edxnotes_visibility_if_feature_is_disabled(self):
        """
        Tests that 404 response is received if EdxNotes feature is disabled.
        """
        response = self.client.post(self.visibility_url)
        self.assertEqual(response.status_code, 404)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    def test_edxnotes_visibility_invalid_json(self):
        """
        Tests that 400 response is received if invalid JSON is sent.
        """
        enable_edxnotes_for_the_course(self.course, self.user.id)
        response = self.client.post(
            self.visibility_url,
            data="string",
            content_type="application/json",
        )
        self.assertEqual(response.status_code, 400)

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_EDXNOTES": True})
    def test_edxnotes_visibility_key_error(self):
        """
        Tests that 400 response is received if invalid data structure is sent.
        """
        enable_edxnotes_for_the_course(self.course, self.user.id)
        response = self.client.post(
            self.visibility_url,
            data=json.dumps({'test_key': 1}),
            content_type="application/json",
        )
        self.assertEqual(response.status_code, 400)
1127 1128


1129
@attr(shard=3)
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
@skipUnless(settings.FEATURES["ENABLE_EDXNOTES"], "EdxNotes feature needs to be enabled.")
@ddt.ddt
class EdxNotesPluginTest(ModuleStoreTestCase):
    """
    EdxNotesTab tests.
    """

    def setUp(self):
        super(EdxNotesPluginTest, self).setUp()
        self.course = CourseFactory.create(edxnotes=True)
1140
        self.user = UserFactory()
1141 1142
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)

1143 1144 1145
    def test_edxnotes_tab_with_unenrolled_user(self):
        user = UserFactory()
        assert not EdxNotesTab.is_enabled(self.course, user=user)
1146

1147 1148
    @ddt.data(True, False)
    def test_edxnotes_tab_with_feature_flag(self, enabled):
1149 1150 1151
        """
        Verify EdxNotesTab visibility when ENABLE_EDXNOTES feature flag is enabled/disabled.
        """
1152
        FEATURES['ENABLE_EDXNOTES'] = enabled
1153
        with override_settings(FEATURES=FEATURES):
1154
            assert EdxNotesTab.is_enabled(self.course, self.user) == enabled
1155

1156
    @ddt.data(True, False)
1157 1158 1159 1160 1161 1162
    def test_edxnotes_tab_with_harvard_notes(self, harvard_notes_enabled):
        """
        Verify EdxNotesTab visibility when harvard notes feature is enabled/disabled.
        """
        with patch("edxnotes.plugins.is_harvard_notes_enabled") as mock_harvard_notes_enabled:
            mock_harvard_notes_enabled.return_value = harvard_notes_enabled
1163
            assert EdxNotesTab.is_enabled(self.course, self.user) == (not harvard_notes_enabled)