test_recommender.py 29.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
"""
This test file will run through some XBlock test scenarios regarding the
recommender system
"""
import json
import itertools
import StringIO
from ddt import ddt, data
from copy import deepcopy

from django.core.urlresolvers import reverse

from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
Ned Batchelder committed
14
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

from courseware.tests.helpers import LoginEnrollmentTestCase
from courseware.tests.factories import GlobalStaffFactory

from lms.djangoapps.lms_xblock.runtime import quote_slashes


class TestRecommender(ModuleStoreTestCase, LoginEnrollmentTestCase):
    """
    Check that Recommender state is saved properly
    """
    STUDENTS = [
        {'email': 'view@test.com', 'password': 'foo'},
        {'email': 'view2@test.com', 'password': 'foo'}
    ]
    XBLOCK_NAMES = ['recommender', 'recommender_second']

    def setUp(self):
33 34
        super(TestRecommender, self).setUp()

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        self.course = CourseFactory.create(
            display_name='Recommender_Test_Course'
        )
        self.chapter = ItemFactory.create(
            parent=self.course, display_name='Overview'
        )
        self.section = ItemFactory.create(
            parent=self.chapter, display_name='Welcome'
        )
        self.unit = ItemFactory.create(
            parent=self.section, display_name='New Unit'
        )
        self.xblock = ItemFactory.create(
            parent=self.unit,
            category='recommender',
            display_name='recommender'
        )
        self.xblock2 = ItemFactory.create(
            parent=self.unit,
            category='recommender',
            display_name='recommender_second'
        )

        self.course_url = reverse(
            'courseware_section',
            kwargs={
                'course_id': self.course.id.to_deprecated_string(),
                'chapter': 'Overview',
                'section': 'Welcome',
            }
        )

        self.resource_urls = [
            (
                "https://courses.edx.org/courses/MITx/3.091X/"
                "2013_Fall/courseware/SP13_Week_4/"
                "SP13_Periodic_Trends_and_Bonding/"
            ),
            (
                "https://courses.edx.org/courses/MITx/3.091X/"
                "2013_Fall/courseware/SP13_Week_4/SP13_Covalent_Bonding/"
            )
        ]

        self.test_recommendations = {
            self.resource_urls[0]: {
                "title": "Covalent bonding and periodic trends",
                "url": self.resource_urls[0],
                "description": (
                    "http://people.csail.mit.edu/swli/edx/"
                    "recommendation/img/videopage1.png"
                ),
                "descriptionText": (
                    "short description for Covalent bonding "
                    "and periodic trends"
                )
            },
            self.resource_urls[1]: {
                "title": "Polar covalent bonds and electronegativity",
                "url": self.resource_urls[1],
                "description": (
                    "http://people.csail.mit.edu/swli/edx/"
                    "recommendation/img/videopage2.png"
                ),
                "descriptionText": (
                    "short description for Polar covalent "
                    "bonds and electronegativity"
                )
            }
        }

        for idx, student in enumerate(self.STUDENTS):
            username = "u{}".format(idx)
            self.create_account(username, student['email'], student['password'])
            self.activate_user(student['email'])

        self.staff_user = GlobalStaffFactory()

    def get_handler_url(self, handler, xblock_name=None):
        """
        Get url for the specified xblock handler
        """
        if xblock_name is None:
            xblock_name = TestRecommender.XBLOCK_NAMES[0]
        return reverse('xblock_handler', kwargs={
            'course_id': self.course.id.to_deprecated_string(),
            'usage_id': quote_slashes(self.course.id.make_usage_key('recommender', xblock_name).to_deprecated_string()),
            'handler': handler,
            'suffix': ''
        })

    def enroll_student(self, email, password):
        """
        Student login and enroll for the course
        """
        self.login(email, password)
        self.enroll(self.course, verify=True)

    def enroll_staff(self, staff):
        """
        Staff login and enroll for the course
        """
        email = staff.email
        password = 'test'
        self.login(email, password)
        self.enroll(self.course, verify=True)

    def initialize_database_by_id(self, handler, resource_id, times, xblock_name=None):
        """
        Call a ajax event (vote, delete, endorse) on a resource by its id
        several times
        """
        if xblock_name is None:
            xblock_name = TestRecommender.XBLOCK_NAMES[0]
        url = self.get_handler_url(handler, xblock_name)
        for _ in range(0, times):
            self.client.post(url, json.dumps({'id': resource_id}), '')

    def call_event(self, handler, resource, xblock_name=None):
        """
        Call a ajax event (add, edit, flag, etc.) by specifying the resource
        it takes
        """
        if xblock_name is None:
            xblock_name = TestRecommender.XBLOCK_NAMES[0]
        url = self.get_handler_url(handler, xblock_name)
swdanielli committed
161
        return self.client.post(url, json.dumps(resource), '')
162

swdanielli committed
163
    def check_event_response_by_key(self, handler, resource, resp_key, resp_val, xblock_name=None):
164 165
        """
        Call the event specified by the handler with the resource, and check
swdanielli committed
166
        whether the key (resp_key) in response is as expected (resp_val)
167 168 169
        """
        if xblock_name is None:
            xblock_name = TestRecommender.XBLOCK_NAMES[0]
swdanielli committed
170
        resp = json.loads(self.call_event(handler, resource, xblock_name).content)
171 172 173
        self.assertEqual(resp[resp_key], resp_val)
        self.assert_request_status_code(200, self.course_url)

swdanielli committed
174 175 176 177 178 179 180 181 182 183 184
    def check_event_response_by_http_status(self, handler, resource, http_status_code, xblock_name=None):
        """
        Call the event specified by the handler with the resource, and check
        whether the http_status in response is as expected
        """
        if xblock_name is None:
            xblock_name = TestRecommender.XBLOCK_NAMES[0]
        resp = self.call_event(handler, resource, xblock_name)
        self.assertEqual(resp.status_code, http_status_code)
        self.assert_request_status_code(200, self.course_url)

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

class TestRecommenderCreateFromEmpty(TestRecommender):
    """
    Check whether we can add resources to an empty database correctly
    """
    def test_add_resource(self):
        """
        Verify the addition of new resource is handled correctly
        """
        self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'])
        # Check whether adding new resource is successful
        for resource_id, resource in self.test_recommendations.iteritems():
            for xblock_name in self.XBLOCK_NAMES:
                result = self.call_event('add_resource', resource, xblock_name)

                expected_result = {
                    'upvotes': 0,
                    'downvotes': 0,
                    'id': resource_id
                }
                for field in resource:
                    expected_result[field] = resource[field]

swdanielli committed
208
                self.assertDictEqual(json.loads(result.content), expected_result)
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                self.assert_request_status_code(200, self.course_url)


class TestRecommenderWithResources(TestRecommender):
    """
    Check whether we can add/edit/flag/export resources correctly
    """
    def setUp(self):
        # call the setUp function from the superclass
        super(TestRecommenderWithResources, self).setUp()
        self.resource_id = self.resource_urls[0]
        self.resource_id_second = self.resource_urls[1]
        self.non_existing_resource_id = 'An non-existing id'
        self.set_up_resources()

    def set_up_resources(self):
        """
        Set up resources and enroll staff
        """
        self.logout()
        self.enroll_staff(self.staff_user)
        # Add resources, assume correct here, tested in test_add_resource
        for resource, xblock_name in itertools.product(self.test_recommendations.values(), self.XBLOCK_NAMES):
            self.call_event('add_resource', resource, xblock_name)

    def generate_edit_resource(self, resource_id):
        """
        Based on the given resource (specified by resource_id), this function
        generate a new one for testing 'edit_resource' event
        """
        resource = {"id": resource_id}
        edited_recommendations = {
            key: value + " edited" for key, value in self.test_recommendations[self.resource_id].iteritems()
        }
        resource.update(edited_recommendations)
        return resource

    def test_add_redundant_resource(self):
        """
        Verify the addition of a redundant resource (url) is rejected
        """
        for suffix in ['', '#IAmSuffix', '%23IAmSuffix']:
            resource = deepcopy(self.test_recommendations[self.resource_id])
            resource['url'] += suffix
swdanielli committed
253
            self.check_event_response_by_http_status('add_resource', resource, 409)
254

swdanielli committed
255
    def test_add_removed_resource(self):
256
        """
swdanielli committed
257
        Verify the addition of a removed resource (url) is rejected
258
        """
swdanielli committed
259
        self.call_event('remove_resource', {"id": self.resource_id, 'reason': ''})
260 261 262
        for suffix in ['', '#IAmSuffix', '%23IAmSuffix']:
            resource = deepcopy(self.test_recommendations[self.resource_id])
            resource['url'] += suffix
swdanielli committed
263
            self.check_event_response_by_http_status('add_resource', resource, 405)
264 265 266 267 268

    def test_edit_resource_non_existing(self):
        """
        Edit a non-existing resource
        """
swdanielli committed
269 270 271 272
        self.check_event_response_by_http_status(
            'edit_resource',
            self.generate_edit_resource(self.non_existing_resource_id),
            400
273 274 275 276 277 278 279 280 281 282
        )

    def test_edit_redundant_resource(self):
        """
        Check whether changing the url to the one of 'another' resource is
        rejected
        """
        for suffix in ['', '#IAmSuffix', '%23IAmSuffix']:
            resource = self.generate_edit_resource(self.resource_id)
            resource['url'] = self.resource_id_second + suffix
swdanielli committed
283
            self.check_event_response_by_http_status('edit_resource', resource, 409)
284

swdanielli committed
285
    def test_edit_removed_resource(self):
286
        """
swdanielli committed
287
        Check whether changing the url to the one of a removed resource is
288 289
        rejected
        """
swdanielli committed
290
        self.call_event('remove_resource', {"id": self.resource_id_second, 'reason': ''})
291 292 293
        for suffix in ['', '#IAmSuffix', '%23IAmSuffix']:
            resource = self.generate_edit_resource(self.resource_id)
            resource['url'] = self.resource_id_second + suffix
swdanielli committed
294
            self.check_event_response_by_http_status('edit_resource', resource, 405)
295 296 297 298 299

    def test_edit_resource(self):
        """
        Check whether changing the content of resource is successful
        """
swdanielli committed
300 301 302 303
        self.check_event_response_by_http_status(
            'edit_resource',
            self.generate_edit_resource(self.resource_id),
            200
304 305 306 307 308 309 310 311 312
        )

    def test_edit_resource_same_url(self):
        """
        Check whether changing the content (except for url) of resource is successful
        """
        resource = self.generate_edit_resource(self.resource_id)
        for suffix in ['', '#IAmSuffix', '%23IAmSuffix']:
            resource['url'] = self.resource_id + suffix
swdanielli committed
313
            self.check_event_response_by_http_status('edit_resource', resource, 200)
314 315 316 317 318 319 320

    def test_edit_then_add_resource(self):
        """
        Check whether we can add back an edited resource
        """
        self.call_event('edit_resource', self.generate_edit_resource(self.resource_id))
        # Test
swdanielli committed
321 322 323 324 325 326
        self.check_event_response_by_key(
            'add_resource',
            self.test_recommendations[self.resource_id],
            'id',
            self.resource_id
        )
327 328 329 330 331 332 333 334

    def test_edit_resources_in_different_xblocks(self):
        """
        Check whether changing the content of resource is successful in two
        different xblocks
        """
        resource = self.generate_edit_resource(self.resource_id)
        for xblock_name in self.XBLOCK_NAMES:
swdanielli committed
335
            self.check_event_response_by_http_status('edit_resource', resource, 200, xblock_name)
336 337 338 339 340 341 342

    def test_flag_resource_wo_reason(self):
        """
        Flag a resource as problematic, without providing the reason
        """
        resource = {'id': self.resource_id, 'isProblematic': True, 'reason': ''}
        # Test
swdanielli committed
343
        self.check_event_response_by_key('flag_resource', resource, 'reason', '')
344 345 346 347 348 349 350

    def test_flag_resource_w_reason(self):
        """
        Flag a resource as problematic, with providing the reason
        """
        resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'}
        # Test
swdanielli committed
351
        self.check_event_response_by_key('flag_resource', resource, 'reason', 'reason 0')
352 353 354 355 356 357 358 359 360

    def test_flag_resource_change_reason(self):
        """
        Flag a resource as problematic twice, with different reasons
        """
        resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'}
        self.call_event('flag_resource', resource)
        # Test
        resource['reason'] = 'reason 1'
swdanielli committed
361
        resp = json.loads(self.call_event('flag_resource', resource).content)
362 363 364 365 366 367 368 369 370 371 372
        self.assertEqual(resp['oldReason'], 'reason 0')
        self.assertEqual(resp['reason'], 'reason 1')
        self.assert_request_status_code(200, self.course_url)

    def test_flag_resources_in_different_xblocks(self):
        """
        Flag resources as problematic in two different xblocks
        """
        resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'}
        # Test
        for xblock_name in self.XBLOCK_NAMES:
swdanielli committed
373
            self.check_event_response_by_key('flag_resource', resource, 'reason', 'reason 0', xblock_name)
374 375 376 377 378 379 380 381 382 383

    def test_flag_resources_by_different_users(self):
        """
        Different users can't see the flag result of each other
        """
        resource = {'id': self.resource_id, 'isProblematic': True, 'reason': 'reason 0'}
        self.call_event('flag_resource', resource)
        self.logout()
        self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'])
        # Test
swdanielli committed
384
        resp = json.loads(self.call_event('flag_resource', resource).content)
385 386 387 388 389 390 391 392 393
        # The second user won't see the reason provided by the first user
        self.assertNotIn('oldReason', resp)
        self.assertEqual(resp['reason'], 'reason 0')
        self.assert_request_status_code(200, self.course_url)

    def test_export_resources(self):
        """
        Test the function for exporting all resources from the Recommender.
        """
swdanielli committed
394
        self.call_event('remove_resource', {"id": self.resource_id, 'reason': ''})
395 396
        self.call_event('endorse_resource', {"id": self.resource_id_second, 'reason': ''})
        # Test
swdanielli committed
397
        resp = json.loads(self.call_event('export_resources', {}).content)
398 399 400 401

        self.assertIn(self.resource_id_second, resp['export']['recommendations'])
        self.assertNotIn(self.resource_id, resp['export']['recommendations'])
        self.assertIn(self.resource_id_second, resp['export']['endorsed_recommendation_ids'])
swdanielli committed
402
        self.assertIn(self.resource_id, resp['export']['removed_recommendations'])
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
        self.assert_request_status_code(200, self.course_url)


@ddt
class TestRecommenderVoteWithResources(TestRecommenderWithResources):
    """
    Check whether we can vote resources correctly
    """
    def setUp(self):
        # call the setUp function from the superclass
        super(TestRecommenderVoteWithResources, self).setUp()

    @data(
        {'event': 'recommender_upvote'},
        {'event': 'recommender_downvote'}
    )
    def test_vote_resource_non_existing(self, test_case):
        """
        Vote a non-existing resource
        """
        resource = {"id": self.non_existing_resource_id, 'event': test_case['event']}
swdanielli committed
424
        self.check_event_response_by_http_status('handle_vote', resource, 400)
425 426 427 428 429 430 431 432 433 434

    @data(
        {'event': 'recommender_upvote', 'new_votes': 1},
        {'event': 'recommender_downvote', 'new_votes': -1}
    )
    def test_vote_resource_once(self, test_case):
        """
        Vote a resource
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
swdanielli committed
435
        self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes'])
436 437 438 439 440 441 442 443 444 445 446 447

    @data(
        {'event': 'recommender_upvote', 'new_votes': 0},
        {'event': 'recommender_downvote', 'new_votes': 0}
    )
    def test_vote_resource_twice(self, test_case):
        """
        Vote a resource twice
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
        self.call_event('handle_vote', resource)
        # Test
swdanielli committed
448
        self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes'])
449 450 451 452 453 454 455 456 457 458 459 460 461

    @data(
        {'event': 'recommender_upvote', 'new_votes': 1},
        {'event': 'recommender_downvote', 'new_votes': -1}
    )
    def test_vote_resource_thrice(self, test_case):
        """
        Vote a resource thrice
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
        for _ in range(0, 2):
            self.call_event('handle_vote', resource)
        # Test
swdanielli committed
462
        self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes'])
463 464 465 466 467 468 469 470 471 472 473 474 475

    @data(
        {'event': 'recommender_upvote', 'event_second': 'recommender_downvote', 'new_votes': -1},
        {'event': 'recommender_downvote', 'event_second': 'recommender_upvote', 'new_votes': 1}
    )
    def test_switch_vote_resource(self, test_case):
        """
        Switch the vote of a resource
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
        self.call_event('handle_vote', resource)
        # Test
        resource['event'] = test_case['event_second']
swdanielli committed
476
        self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes'])
477 478 479 480 481 482 483 484 485 486 487 488 489

    @data(
        {'event': 'recommender_upvote', 'new_votes': 1},
        {'event': 'recommender_downvote', 'new_votes': -1}
    )
    def test_vote_different_resources(self, test_case):
        """
        Vote two different resources
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
        self.call_event('handle_vote', resource)
        # Test
        resource['id'] = self.resource_id_second
swdanielli committed
490
        self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes'])
491 492 493 494 495 496 497 498 499 500 501 502

    @data(
        {'event': 'recommender_upvote', 'new_votes': 1},
        {'event': 'recommender_downvote', 'new_votes': -1}
    )
    def test_vote_resources_in_different_xblocks(self, test_case):
        """
        Vote two resources in two different xblocks
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
        self.call_event('handle_vote', resource)
        # Test
swdanielli committed
503 504 505
        self.check_event_response_by_key(
            'handle_vote', resource, 'newVotes', test_case['new_votes'], self.XBLOCK_NAMES[1]
        )
506 507 508 509 510 511 512 513 514 515 516 517 518 519

    @data(
        {'event': 'recommender_upvote', 'new_votes': 2},
        {'event': 'recommender_downvote', 'new_votes': -2}
    )
    def test_vote_resource_by_different_users(self, test_case):
        """
        Vote resource by two different users
        """
        resource = {"id": self.resource_id, 'event': test_case['event']}
        self.call_event('handle_vote', resource)
        self.logout()
        self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'])
        # Test
swdanielli committed
520
        self.check_event_response_by_key('handle_vote', resource, 'newVotes', test_case['new_votes'])
521 522 523 524 525


@ddt
class TestRecommenderStaffFeedbackWithResources(TestRecommenderWithResources):
    """
swdanielli committed
526
    Check whether we can remove/endorse resources correctly
527 528 529 530 531
    """
    def setUp(self):
        # call the setUp function from the superclass
        super(TestRecommenderStaffFeedbackWithResources, self).setUp()

swdanielli committed
532 533
    @data('remove_resource', 'endorse_resource')
    def test_remove_or_endorse_resource_non_existing(self, test_case):
534
        """
swdanielli committed
535
        Remove/endorse a non-existing resource
536 537
        """
        resource = {"id": self.non_existing_resource_id, 'reason': ''}
swdanielli committed
538
        self.check_event_response_by_http_status(test_case, resource, 400)
539 540

    @data(
swdanielli committed
541 542 543
        {'times': 1, 'key': 'status', 'val': 'endorsement'},
        {'times': 2, 'key': 'status', 'val': 'undo endorsement'},
        {'times': 3, 'key': 'status', 'val': 'endorsement'}
544
    )
swdanielli committed
545
    def test_endorse_resource_multiple_times(self, test_case):
546
        """
swdanielli committed
547
        Endorse a resource once/twice/thrice
548 549
        """
        resource = {"id": self.resource_id, 'reason': ''}
swdanielli committed
550 551
        for _ in range(0, test_case['times'] - 1):
            self.call_event('endorse_resource', resource)
552
        # Test
swdanielli committed
553
        self.check_event_response_by_key('endorse_resource', resource, test_case['key'], test_case['val'])
554 555

    @data(
swdanielli committed
556 557 558
        {'times': 1, 'status': 200},
        {'times': 2, 'status': 400},
        {'times': 3, 'status': 400}
559
    )
swdanielli committed
560
    def test_remove_resource_multiple_times(self, test_case):
561
        """
swdanielli committed
562
        Remove a resource once/twice/thrice
563 564
        """
        resource = {"id": self.resource_id, 'reason': ''}
swdanielli committed
565 566
        for _ in range(0, test_case['times'] - 1):
            self.call_event('remove_resource', resource)
567
        # Test
swdanielli committed
568
        self.check_event_response_by_http_status('remove_resource', resource, test_case['status'])
569 570

    @data(
swdanielli committed
571
        {'handler': 'remove_resource', 'status': 200},
572 573
        {'handler': 'endorse_resource', 'key': 'status', 'val': 'endorsement'}
    )
swdanielli committed
574
    def test_remove_or_endorse_different_resources(self, test_case):
575
        """
swdanielli committed
576
        Remove/endorse two different resources
577 578 579 580
        """
        self.call_event(test_case['handler'], {"id": self.resource_id, 'reason': ''})
        # Test
        resource = {"id": self.resource_id_second, 'reason': ''}
swdanielli committed
581 582 583 584
        if test_case['handler'] == 'remove_resource':
            self.check_event_response_by_http_status(test_case['handler'], resource, test_case['status'])
        else:
            self.check_event_response_by_key(test_case['handler'], resource, test_case['key'], test_case['val'])
585 586

    @data(
swdanielli committed
587
        {'handler': 'remove_resource', 'status': 200},
588 589
        {'handler': 'endorse_resource', 'key': 'status', 'val': 'endorsement'}
    )
swdanielli committed
590
    def test_remove_or_endorse_resources_in_different_xblocks(self, test_case):
591
        """
swdanielli committed
592
        Remove/endorse two resources in two different xblocks
593 594 595 596
        """
        self.call_event(test_case['handler'], {"id": self.resource_id, 'reason': ''})
        # Test
        resource = {"id": self.resource_id, 'reason': ''}
swdanielli committed
597 598 599 600 601 602 603 604
        if test_case['handler'] == 'remove_resource':
            self.check_event_response_by_http_status(
                test_case['handler'], resource, test_case['status'], self.XBLOCK_NAMES[1]
            )
        else:
            self.check_event_response_by_key(
                test_case['handler'], resource, test_case['key'], test_case['val'], self.XBLOCK_NAMES[1]
            )
605 606

    @data(
swdanielli committed
607 608
        {'handler': 'remove_resource', 'status': 400},
        {'handler': 'endorse_resource', 'status': 400}
609
    )
swdanielli committed
610
    def test_remove_or_endorse_resource_by_student(self, test_case):
611
        """
swdanielli committed
612
        Remove/endorse resource by a student
613 614 615 616 617
        """
        self.logout()
        self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'])
        # Test
        resource = {"id": self.resource_id, 'reason': ''}
swdanielli committed
618
        self.check_event_response_by_http_status(test_case['handler'], resource, test_case['status'])
619 620 621 622 623 624 625 626 627 628


@ddt
class TestRecommenderFileUploading(TestRecommender):
    """
    Check whether we can handle file uploading correctly
    """
    def setUp(self):
        # call the setUp function from the superclass
        super(TestRecommenderFileUploading, self).setUp()
swdanielli committed
629 630 631 632 633 634 635
        self.initial_configuration = {
            'flagged_accum_resources': {},
            'endorsed_recommendation_reasons': [],
            'endorsed_recommendation_ids': [],
            'removed_recommendations': {},
            'recommendations': self.test_recommendations[self.resource_urls[0]]
        }
636

swdanielli committed
637
    def attempt_upload_file_and_verify_result(self, test_case, event_name, content=None):
638 639 640 641 642
        """
        Running on a test case, creating a temp file, uploading it by
        calling the corresponding ajax event, and verifying that upload
        happens or is rejected as expected.
        """
swdanielli committed
643 644 645 646 647 648 649
        if 'magic_number' in test_case:
            f_handler = StringIO.StringIO(test_case['magic_number'].decode('hex'))
        elif content is not None:
            f_handler = StringIO.StringIO(json.dumps(content, sort_keys=True))
        else:
            f_handler = StringIO.StringIO('')

650 651
        f_handler.content_type = test_case['mimetypes']
        f_handler.name = 'file' + test_case['suffixes']
swdanielli committed
652
        url = self.get_handler_url(event_name)
653
        resp = self.client.post(url, {'file': f_handler})
swdanielli committed
654
        self.assertEqual(resp.status_code, test_case['status'])
655 656 657 658 659 660 661
        self.assert_request_status_code(200, self.course_url)

    @data(
        {
            'suffixes': '.csv',
            'magic_number': 'ffff',
            'mimetypes': 'text/plain',
swdanielli committed
662
            'status': 415
663 664 665 666 667
        },  # Upload file with wrong extension name
        {
            'suffixes': '.gif',
            'magic_number': '89504e470d0a1a0a',
            'mimetypes': 'image/gif',
swdanielli committed
668
            'status': 415
669 670 671 672 673
        },  # Upload file with wrong magic number
        {
            'suffixes': '.jpg',
            'magic_number': '89504e470d0a1a0a',
            'mimetypes': 'image/jpeg',
swdanielli committed
674
            'status': 415
675 676 677 678 679
        },  # Upload file with wrong magic number
        {
            'suffixes': '.png',
            'magic_number': '474946383761',
            'mimetypes': 'image/png',
swdanielli committed
680
            'status': 415
681 682 683 684 685
        },  # Upload file with wrong magic number
        {
            'suffixes': '.jpg',
            'magic_number': '474946383761',
            'mimetypes': 'image/jpeg',
swdanielli committed
686
            'status': 415
687 688 689 690 691
        },  # Upload file with wrong magic number
        {
            'suffixes': '.png',
            'magic_number': 'ffd8ffd9',
            'mimetypes': 'image/png',
swdanielli committed
692
            'status': 415
693 694 695 696 697
        },  # Upload file with wrong magic number
        {
            'suffixes': '.gif',
            'magic_number': 'ffd8ffd9',
            'mimetypes': 'image/gif',
swdanielli committed
698
            'status': 415
699 700 701 702 703 704 705 706 707
        }
    )
    def test_upload_screenshot_wrong_file_type(self, test_case):
        """
        Verify the file uploading fails correctly when file with wrong type
        (extension/magic number) is provided
        """
        self.enroll_staff(self.staff_user)
        # Upload file with wrong extension name or magic number
swdanielli committed
708
        self.attempt_upload_file_and_verify_result(test_case, 'upload_screenshot')
709 710 711 712 713 714

    @data(
        {
            'suffixes': '.png',
            'magic_number': '89504e470d0a1a0a',
            'mimetypes': 'image/png',
swdanielli committed
715
            'status': 200
716 717 718 719 720
        },
        {
            'suffixes': '.gif',
            'magic_number': '474946383961',
            'mimetypes': 'image/gif',
swdanielli committed
721
            'status': 200
722 723 724 725 726
        },
        {
            'suffixes': '.gif',
            'magic_number': '474946383761',
            'mimetypes': 'image/gif',
swdanielli committed
727
            'status': 200
728 729 730 731 732
        },
        {
            'suffixes': '.jpg',
            'magic_number': 'ffd8ffd9',
            'mimetypes': 'image/jpeg',
swdanielli committed
733
            'status': 200
734 735 736 737 738 739 740 741 742
        }
    )
    def test_upload_screenshot_correct_file_type(self, test_case):
        """
        Verify the file type checking in the file uploading method is
        successful.
        """
        self.enroll_staff(self.staff_user)
        # Upload file with correct extension name and magic number
swdanielli committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
        self.attempt_upload_file_and_verify_result(test_case, 'upload_screenshot')

    @data(
        {
            'suffixes': '.json',
            'mimetypes': 'application/json',
            'status': 403
        }
    )
    def test_import_resources_by_student(self, test_case):
        """
        Test the function for importing all resources into the Recommender
        by a student.
        """
        self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'])
        self.attempt_upload_file_and_verify_result(test_case, 'import_resources', self.initial_configuration)

    @data(
        {
            'suffixes': '.csv',
            'mimetypes': 'application/json',
            'status': 415
        },  # Upload file with wrong extension name
        {
            'suffixes': '.json',
            'mimetypes': 'application/json',
            'status': 200
        }
    )
    def test_import_resources(self, test_case):
        """
        Test the function for importing all resources into the Recommender.
        """
        self.enroll_staff(self.staff_user)
        self.attempt_upload_file_and_verify_result(test_case, 'import_resources', self.initial_configuration)

    @data(
        {
            'suffixes': '.json',
            'mimetypes': 'application/json',
            'status': 415
        }
    )
    def test_import_resources_wrong_format(self, test_case):
        """
        Test the function for importing empty dictionary into the Recommender.
        This should fire an error.
        """
        self.enroll_staff(self.staff_user)
        self.attempt_upload_file_and_verify_result(test_case, 'import_resources', {})