tests.py 19.3 KB
Newer Older
1
import copy
2
import json
3
import os
4 5
import sys
import time
6

7
from nose import SkipTest
8 9
from path import path
from pprint import pprint
10

11
from django.contrib.auth.models import User, Group
12 13 14 15
from django.test import TestCase
from django.test.client import Client
from django.conf import settings
from django.core.urlresolvers import reverse
16 17
from mock import patch, Mock
from override_settings import override_settings
18

19 20
import xmodule.modulestore.django

21
from student.models import Registration
22
from courseware.courses import course_staff_group_name
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
from xmodule.modulestore.django import modulestore
from xmodule.modulestore import Location
from xmodule.modulestore.xml_importer import import_from_xml


def parse_json(response):
    """Parse response, which is assumed to be json"""
    return json.loads(response.content)


def user(email):
    '''look up a user by email'''
    return User.objects.get(email=email)


def registration(email):
    '''look up registration object by email'''
    return Registration.objects.get(user__email=email)


43 44 45
# A bit of a hack--want mongo modulestore for these tests, until
# jump_to works with the xmlmodulestore or we have an even better solution
# NOTE: this means this test requires mongo to be running.
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60
def mongo_store_config(data_dir):
    return {
    'default': {
        'ENGINE': 'xmodule.modulestore.mongo.MongoModuleStore',
        'OPTIONS': {
            'default_class': 'xmodule.raw_module.RawDescriptor',
            'host': 'localhost',
            'db': 'xmodule',
            'collection': 'modulestore',
            'fs_root': data_dir,
        }
    }
}

61 62 63 64 65 66 67 68 69 70 71 72 73
def xml_store_config(data_dir):
    return {
    'default': {
        'ENGINE': 'xmodule.modulestore.xml.XMLModuleStore',
        'OPTIONS': {
            'data_dir': data_dir,
            'default_class': 'xmodule.hidden_module.HiddenDescriptor',
            'eager': True,
        }
    }
}


74
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
75 76
TEST_DATA_MONGO_MODULESTORE = mongo_store_config(TEST_DATA_DIR)
TEST_DATA_XML_MODULESTORE = xml_store_config(TEST_DATA_DIR)
77 78 79 80 81 82

REAL_DATA_DIR = settings.GITHUB_REPO_ROOT
REAL_DATA_MODULESTORE = mongo_store_config(REAL_DATA_DIR)

class ActivateLoginTestCase(TestCase):
    '''Check that we can activate and log in'''
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

    def setUp(self):
        email = 'view@test.com'
        password = 'foo'
        self.create_account('viewtest', email, password)
        self.activate_user(email)
        self.login(email, password)

    # ============ User creation and login ==============

    def _login(self, email, pw):
        '''Login.  View should always return 200.  The success/fail is in the
        returned json'''
        resp = self.client.post(reverse('login'),
                                {'email': email, 'password': pw})
        self.assertEqual(resp.status_code, 200)
        return resp

    def login(self, email, pw):
        '''Login, check that it worked.'''
        resp = self._login(email, pw)
        data = parse_json(resp)
        self.assertTrue(data['success'])
        return resp

Victor Shnayder committed
108 109 110 111 112 113 114
    def logout(self):
        '''Logout, check that it worked.'''
        resp = self.client.get(reverse('logout'), {})
        # should redirect
        self.assertEqual(resp.status_code, 302)
        return resp

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
    def _create_account(self, username, email, pw):
        '''Try to create an account.  No error checking'''
        resp = self.client.post('/create_account', {
            'username': username,
            'email': email,
            'password': pw,
            'name': 'Fred Weasley',
            'terms_of_service': 'true',
            'honor_code': 'true',
        })
        return resp

    def create_account(self, username, email, pw):
        '''Create the account and check that it worked'''
        resp = self._create_account(username, email, pw)
        self.assertEqual(resp.status_code, 200)
        data = parse_json(resp)
        self.assertEqual(data['success'], True)

        # Check both that the user is created, and inactive
        self.assertFalse(user(email).is_active)

        return resp

    def _activate_user(self, email):
        '''Look up the activation key for the user, then hit the activate view.
        No error checking'''
        activation_key = registration(email).activation_key

        # and now we try to activate
        resp = self.client.get(reverse('activate', kwargs={'key': activation_key}))
        return resp

    def activate_user(self, email):
        resp = self._activate_user(email)
        self.assertEqual(resp.status_code, 200)
        # Now make sure that the user is now actually activated
        self.assertTrue(user(email).is_active)

154 155 156 157
    def test_activate_login(self):
        '''The setup function does all the work'''
        pass

Victor Shnayder committed
158 159 160 161
    def test_logout(self):
        '''Setup function does login'''
        self.logout()

162

163 164 165
class PageLoader(ActivateLoginTestCase):
    ''' Base class that adds a function to load all pages in a modulestore '''

166 167 168 169 170 171 172 173 174 175 176 177 178 179
    def _enroll(self, course):
        """Post to the enrollment view, and return the parsed json response"""
        resp = self.client.post('/change_enrollment', {
            'enrollment_action': 'enroll',
            'course_id': course.id,
            })
        return parse_json(resp)

    def try_enroll(self, course):
        """Try to enroll.  Return bool success instead of asserting it."""
        data = self._enroll(course)
        print 'Enrollment in {} result: {}'.format(course.location.url(), data)
        return data['success']

Victor Shnayder committed
180
    def enroll(self, course):
Victor Shnayder committed
181
        """Enroll the currently logged-in user, and check that it worked."""
182 183 184 185 186
        data = self._enroll(course)
        self.assertTrue(data['success'])

    def unenroll(self, course):
        """Unenroll the currently logged-in user, and check that it worked."""
Victor Shnayder committed
187 188 189 190 191 192 193
        resp = self.client.post('/change_enrollment', {
            'enrollment_action': 'enroll',
            'course_id': course.id,
            })
        data = parse_json(resp)
        self.assertTrue(data['success'])

194
    def check_pages_load(self, course_name, data_dir, modstore):
195
        """Make all locations in course load"""
196 197
        print "Checking course {0} in {1}".format(course_name, data_dir)
        import_from_xml(modstore, data_dir, [course_name])
198

Victor Shnayder committed
199 200 201 202 203 204
        # enroll in the course before trying to access pages
        courses = modstore.get_courses()
        self.assertEqual(len(courses), 1)
        course = courses[0]
        self.enroll(course)

205 206 207
        n = 0
        num_bad = 0
        all_ok = True
208
        for descriptor in modstore.get_items(
209 210 211 212 213 214 215 216 217 218 219 220 221
                Location(None, None, None, None, None)):
            n += 1
            print "Checking ", descriptor.location.url()
            #print descriptor.__class__, descriptor.location
            resp = self.client.get(reverse('jump_to',
                                   kwargs={'location': descriptor.location.url()}))
            msg = str(resp.status_code)

            if resp.status_code != 200:
                msg = "ERROR " + msg
                all_ok = False
                num_bad += 1
            print msg
222
            self.assertTrue(all_ok)  # fail fast
223 224

        print "{0}/{1} good".format(n - num_bad, n)
225 226
        self.assertTrue(all_ok)

227

228
@override_settings(MODULESTORE=TEST_DATA_MONGO_MODULESTORE)
229 230 231 232 233 234 235
class TestCoursesLoadTestCase(PageLoader):
    '''Check that all pages in test courses load properly'''

    def setUp(self):
        ActivateLoginTestCase.setUp(self)
        xmodule.modulestore.django._MODULESTORES = {}
        xmodule.modulestore.django.modulestore().collection.drop()
236 237

    def test_toy_course_loads(self):
238
        self.check_pages_load('toy', TEST_DATA_DIR, modulestore())
239 240

    def test_full_course_loads(self):
241 242 243
        self.check_pages_load('full', TEST_DATA_DIR, modulestore())


244
@override_settings(MODULESTORE=TEST_DATA_XML_MODULESTORE)
245 246
class TestViewAuth(PageLoader):
    """Check that view authentication works properly"""
Victor Shnayder committed
247

248 249
    # NOTE: setUpClass() runs before override_settings takes effect, so
    # can't do imports there without manually hacking settings.
Victor Shnayder committed
250 251 252 253

    def setUp(self):
        xmodule.modulestore.django._MODULESTORES = {}
        courses = modulestore().get_courses()
254 255 256 257 258 259 260

        def find_course(name):
            """Assumes the course is present"""
            return [c for c in courses if c.location.course==name][0]

        self.full = find_course("full")
        self.toy = find_course("toy")
Victor Shnayder committed
261 262 263 264 265 266 267 268 269 270 271 272

        # Create two accounts
        self.student = 'view@test.com'
        self.instructor = 'view2@test.com'
        self.password = 'foo'
        self.create_account('u1', self.student, self.password)
        self.create_account('u2', self.instructor, self.password)
        self.activate_user(self.student)
        self.activate_user(self.instructor)

    def check_for_get_code(self, code, url):
        resp = self.client.get(url)
273 274 275 276
        # HACK: workaround the bug that returns 200 instead of 404.
        # TODO (vshnayder): once we're returning 404s, get rid of this if.
        if code != 404:
            self.assertEqual(resp.status_code, code)
277 278
            # And 'page not found' shouldn't be in the returned page
            self.assertTrue(resp.content.lower().find('page not found') == -1)
279 280
        else:
            # look for "page not found" instead of the status code
281
            #print resp.content
282
            self.assertTrue(resp.content.lower().find('page not found') != -1)
Victor Shnayder committed
283

284 285 286
    def test_instructor_pages(self):
        """Make sure only instructors for the course or staff can load the instructor
        dashboard, the grade views, and student profile pages"""
Victor Shnayder committed
287 288 289 290 291 292 293 294 295 296 297

        # First, try with an enrolled student
        self.login(self.student, self.password)
        # shouldn't work before enroll
        self.check_for_get_code(302, reverse('courseware', kwargs={'course_id': self.toy.id}))
        self.enroll(self.toy)
        self.enroll(self.full)
        # should work now
        self.check_for_get_code(200, reverse('courseware', kwargs={'course_id': self.toy.id}))

        def instructor_urls(course):
298
            "list of urls that only instructors/staff should be able to see"
Victor Shnayder committed
299 300 301 302
            urls = [reverse(name, kwargs={'course_id': course.id}) for name in (
                'instructor_dashboard',
                'gradebook',
                'grade_summary',)]
303 304
            urls.append(reverse('student_profile', kwargs={'course_id': course.id,
                                                     'student_id': user(self.student).id}))
Victor Shnayder committed
305 306 307 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
            return urls

        # shouldn't be able to get to the instructor pages
        for url in instructor_urls(self.toy) + instructor_urls(self.full):
            print 'checking for 404 on {}'.format(url)
            self.check_for_get_code(404, url)

        # Make the instructor staff in the toy course
        group_name = course_staff_group_name(self.toy)
        g = Group.objects.create(name=group_name)
        g.user_set.add(user(self.instructor))

        self.logout()
        self.login(self.instructor, self.password)

        # Now should be able to get to the toy course, but not the full course
        for url in instructor_urls(self.toy):
            print 'checking for 200 on {}'.format(url)
            self.check_for_get_code(200, url)

        for url in instructor_urls(self.full):
            print 'checking for 404 on {}'.format(url)
            self.check_for_get_code(404, url)


        # now also make the instructor staff
        u = user(self.instructor)
        u.is_staff = True
        u.save()

        # and now should be able to load both
        for url in instructor_urls(self.toy) + instructor_urls(self.full):
            print 'checking for 200 on {}'.format(url)
            self.check_for_get_code(200, url)


341 342 343 344 345 346 347
    def run_wrapped(self, test):
        """
        test.py turns off start dates.  Enable them and DARK_LAUNCH.
        Because settings is global, be careful not to mess it up for other tests
        (Can't use override_settings because we're only changing part of the
        MITX_FEATURES dict)
        """
348 349 350 351 352 353
        oldDSD = settings.MITX_FEATURES['DISABLE_START_DATES']
        oldDL = settings.MITX_FEATURES['DARK_LAUNCH']

        try:
            settings.MITX_FEATURES['DISABLE_START_DATES'] = False
            settings.MITX_FEATURES['DARK_LAUNCH'] = True
354
            test()
355 356 357 358 359
        finally:
            settings.MITX_FEATURES['DISABLE_START_DATES'] = oldDSD
            settings.MITX_FEATURES['DARK_LAUNCH'] = oldDL


360 361 362 363 364 365 366 367 368 369
    def test_dark_launch(self):
        """Make sure that when dark launch is on, students can't access course
        pages, but instructors can"""
        self.run_wrapped(self._do_test_dark_launch)

    def test_enrollment_period(self):
        """Check that enrollment periods work"""
        self.run_wrapped(self._do_test_enrollment_period)


370 371 372 373 374 375 376 377 378 379 380 381 382 383
    def _do_test_dark_launch(self):
        """Actually do the test, relying on settings to be right."""

        # Make courses start in the future
        tomorrow = time.time() + 24*3600
        self.toy.start = self.toy.metadata['start'] = time.gmtime(tomorrow)
        self.full.start = self.full.metadata['start'] = time.gmtime(tomorrow)

        self.assertFalse(self.toy.has_started())
        self.assertFalse(self.full.has_started())
        self.assertFalse(settings.MITX_FEATURES['DISABLE_START_DATES'])
        self.assertTrue(settings.MITX_FEATURES['DARK_LAUNCH'])

        def reverse_urls(names, course):
384
            """Reverse a list of course urls"""
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
            return [reverse(name, kwargs={'course_id': course.id}) for name in names]

        def dark_student_urls(course):
            """
            list of urls that students should be able to see only
            after launch, but staff should see before
            """
            urls = reverse_urls(['info', 'book', 'courseware', 'profile'], course)
            return urls

        def light_student_urls(course):
            """
            list of urls that students should be able to see before
            launch.
            """
            urls = reverse_urls(['about_course'], course)
            urls.append(reverse('courses'))
            # Need separate test for change_enrollment, since it's a POST view
            #urls.append(reverse('change_enrollment'))

            return urls
Victor Shnayder committed
406

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        def instructor_urls(course):
            """list of urls that only instructors/staff should be able to see"""
            urls = reverse_urls(['instructor_dashboard','gradebook','grade_summary'],
                                course)
            urls.append(reverse('student_profile', kwargs={'course_id': course.id,
                                                     'student_id': user(self.student).id}))
            return urls

        def check_non_staff(course):
            """Check that access is right for non-staff in course"""
            print '=== Checking non-staff access for {}'.format(course.id)
            for url in instructor_urls(course) + dark_student_urls(course):
                print 'checking for 404 on {}'.format(url)
                self.check_for_get_code(404, url)

            for url in light_student_urls(course):
                print 'checking for 200 on {}'.format(url)
                self.check_for_get_code(200, url)

        def check_staff(course):
            """Check that access is right for staff in course"""
            print '=== Checking staff access for {}'.format(course.id)
            for url in (instructor_urls(course) +
                        dark_student_urls(course) +
                        light_student_urls(course)):
                print 'checking for 200 on {}'.format(url)
                self.check_for_get_code(200, url)

        # First, try with an enrolled student
        print '=== Testing student access....'
        self.login(self.student, self.password)
        self.enroll(self.toy)
        self.enroll(self.full)

        # shouldn't be able to get to anything except the light pages
        check_non_staff(self.toy)
        check_non_staff(self.full)

        print '=== Testing course instructor access....'
        # Make the instructor staff in the toy course
        group_name = course_staff_group_name(self.toy)
        g = Group.objects.create(name=group_name)
        g.user_set.add(user(self.instructor))

        self.logout()
        self.login(self.instructor, self.password)
        # Enroll in the classes---can't see courseware otherwise.
        self.enroll(self.toy)
        self.enroll(self.full)

        # should now be able to get to everything for toy course
        check_non_staff(self.full)
        check_staff(self.toy)

        print '=== Testing staff access....'
        # now also make the instructor staff
        u = user(self.instructor)
        u.is_staff = True
        u.save()

        # and now should be able to load both
        check_staff(self.toy)
        check_staff(self.full)
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    def _do_test_enrollment_period(self):
        """Actually do the test, relying on settings to be right."""

        # Make courses start in the future
        tomorrow = time.time() + 24 * 3600
        nextday = tomorrow + 24 * 3600
        yesterday = time.time() - 24 * 3600

        print "changing"
        # toy course's enrollment period hasn't started
        self.toy.enrollment_start = time.gmtime(tomorrow)
        self.toy.enrollment_end = time.gmtime(nextday)

        # full course's has
        self.full.enrollment_start = time.gmtime(yesterday)
        self.full.enrollment_end = time.gmtime(tomorrow)

        print "login"
        # First, try with an enrolled student
        print '=== Testing student access....'
        self.login(self.student, self.password)
        self.assertFalse(self.try_enroll(self.toy))
        self.assertTrue(self.try_enroll(self.full))

        print '=== Testing course instructor access....'
        # Make the instructor staff in the toy course
        group_name = course_staff_group_name(self.toy)
        g = Group.objects.create(name=group_name)
        g.user_set.add(user(self.instructor))

        print "logout/login"
        self.logout()
        self.login(self.instructor, self.password)
        print "Instructor should be able to enroll in toy course"
        self.assertTrue(self.try_enroll(self.toy))

        print '=== Testing staff access....'
        # now make the instructor global staff, but not in the instructor group
        g.user_set.remove(user(self.instructor))
        u = user(self.instructor)
        u.is_staff = True
        u.save()

        # unenroll and try again
        self.unenroll(self.toy)
        self.assertTrue(self.try_enroll(self.toy))

518 519 520 521 522 523 524 525 526 527

@override_settings(MODULESTORE=REAL_DATA_MODULESTORE)
class RealCoursesLoadTestCase(PageLoader):
    '''Check that all pages in real courses load properly'''

    def setUp(self):
        ActivateLoginTestCase.setUp(self)
        xmodule.modulestore.django._MODULESTORES = {}
        xmodule.modulestore.django.modulestore().collection.drop()

528
    def test_real_courses_loads(self):
529 530 531
        '''See if any real courses are available at the REAL_DATA_DIR.
        If they are, check them.'''

532 533
        # TODO: Disabled test for now..  Fix once things are cleaned up.
        raise SkipTest
534 535 536 537 538 539 540 541 542
        # TODO: adjust staticfiles_dirs
        if not os.path.isdir(REAL_DATA_DIR):
            # No data present.  Just pass.
            return

        courses = [course_dir for course_dir in os.listdir(REAL_DATA_DIR)
                   if os.path.isdir(REAL_DATA_DIR / course_dir)]
        for course in courses:
            self.check_pages_load(course, REAL_DATA_DIR, modulestore())
543 544 545


    # ========= TODO: check ajax interaction here too?