test_views.py 15.1 KB
Newer Older
1
import unittest
2 3
import decimal
import ddt
4
from mock import patch
5 6 7
from django.conf import settings
from django.core.urlresolvers import reverse

Ned Batchelder committed
8
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
9

10
from util.testing import UrlResetMixin
11
from embargo.test_utils import restrict_course
12
from xmodule.modulestore.tests.factories import CourseFactory
13 14
from course_modes.tests.factories import CourseModeFactory
from student.tests.factories import CourseEnrollmentFactory, UserFactory
15
from student.models import CourseEnrollment
16
from course_modes.models import CourseMode, Mode
17
from openedx.core.djangoapps.theming.test_util import with_is_edx_domain
18 19


20
@ddt.ddt
21
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
22 23
class CourseModeViewTest(UrlResetMixin, ModuleStoreTestCase):
    @patch.dict(settings.FEATURES, {'MODE_CREATION_FOR_TESTING': True})
24
    def setUp(self):
25
        super(CourseModeViewTest, self).setUp('course_modes.urls')
26 27 28
        self.course = CourseFactory.create()
        self.user = UserFactory.create(username="Bob", email="bob@example.com", password="edx")
        self.client.login(username=self.user.username, password="edx")
29

30
    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
31
    @ddt.data(
32 33 34 35 36 37 38 39
        # is_active?, enrollment_mode, redirect?
        (True, 'verified', True),
        (True, 'honor', False),
        (True, 'audit', False),
        (False, 'verified', False),
        (False, 'honor', False),
        (False, 'audit', False),
        (False, None, False),
40 41
    )
    @ddt.unpack
42
    def test_redirect_to_dashboard(self, is_active, enrollment_mode, redirect):
43 44 45 46 47
        # Create the course modes
        for mode in ('audit', 'honor', 'verified'):
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

        # Enroll the user in the test course
48 49 50 51 52 53 54
        if enrollment_mode is not None:
            CourseEnrollmentFactory(
                is_active=is_active,
                mode=enrollment_mode,
                course_id=self.course.id,
                user=self.user
            )
55

56 57
        # Configure whether we're upgrading or not
        url = reverse('course_modes_choose', args=[unicode(self.course.id)])
58
        response = self.client.get(url)
59

60
        # Check whether we were correctly redirected
61
        if redirect:
62
            self.assertRedirects(response, reverse('dashboard'))
63 64 65
        else:
            self.assertEquals(response.status_code, 200)

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    def test_no_id_redirect(self):
        # Create the course modes
        CourseModeFactory(mode_slug=CourseMode.NO_ID_PROFESSIONAL_MODE, course_id=self.course.id, min_price=100)

        # Enroll the user in the test course
        CourseEnrollmentFactory(
            is_active=False,
            mode=CourseMode.NO_ID_PROFESSIONAL_MODE,
            course_id=self.course.id,
            user=self.user
        )

        # Configure whether we're upgrading or not
        url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        response = self.client.get(url)
        # Check whether we were correctly redirected
        start_flow_url = reverse('verify_student_start_flow', args=[unicode(self.course.id)])
        self.assertRedirects(response, start_flow_url)

85
    def test_no_enrollment(self):
86 87 88 89 90 91 92 93
        # Create the course modes
        for mode in ('audit', 'honor', 'verified'):
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

        # User visits the track selection page directly without ever enrolling
        url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        response = self.client.get(url)

94
        self.assertEquals(response.status_code, 200)
95

96 97 98 99 100 101 102 103
    @ddt.data(
        '',
        '1,,2',
        '1, ,2',
        '1, 2, 3'
    )
    def test_suggested_prices(self, price_list):

104
        # Create the course modes
105
        for mode in ('audit', 'honor'):
106
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)
107

108 109 110 111
        CourseModeFactory(
            mode_slug='verified',
            course_id=self.course.id,
            suggested_prices=price_list
112 113
        )

114 115 116 117 118 119 120 121
        # Enroll the user in the test course to emulate
        # automatic enrollment
        CourseEnrollmentFactory(
            is_active=True,
            course_id=self.course.id,
            user=self.user
        )

122
        # Verify that the prices render correctly
123
        response = self.client.get(
124
            reverse('course_modes_choose', args=[unicode(self.course.id)]),
125 126 127 128 129 130
            follow=False,
        )

        self.assertEquals(response.status_code, 200)
        # TODO: Fix it so that response.templates works w/ mako templates, and then assert
        # that the right template rendered
131

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    @ddt.data(
        (['honor', 'verified', 'credit'], True),
        (['honor', 'verified'], False),
    )
    @ddt.unpack
    def test_credit_upsell_message(self, available_modes, show_upsell):
        # Create the course modes
        for mode in available_modes:
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

        # Check whether credit upsell is shown on the page
        # This should *only* be shown when a credit mode is available
        url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        response = self.client.get(url)

        if show_upsell:
            self.assertContains(response, "Credit")
        else:
            self.assertNotContains(response, "Credit")

152 153
    @ddt.data('professional', 'no-id-professional')
    def test_professional_enrollment(self, mode):
154
        # The only course mode is professional ed
155
        CourseModeFactory(mode_slug=mode, course_id=self.course.id, min_price=1)
156

157 158 159
        # Go to the "choose your track" page
        choose_track_url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        response = self.client.get(choose_track_url)
160

161 162 163 164
        # Since the only available track is professional ed, expect that
        # we're redirected immediately to the start of the payment flow.
        start_flow_url = reverse('verify_student_start_flow', args=[unicode(self.course.id)])
        self.assertRedirects(response, start_flow_url)
165 166

        # Now enroll in the course
167 168 169
        CourseEnrollmentFactory(
            user=self.user,
            is_active=True,
170
            mode=mode,
171
            course_id=unicode(self.course.id),
172 173
        )

174 175 176 177 178 179 180
        # Expect that this time we're redirected to the dashboard (since we're already registered)
        response = self.client.get(choose_track_url)
        self.assertRedirects(response, reverse('dashboard'))

    # Mapping of course modes to the POST parameters sent
    # when the user chooses that mode.
    POST_PARAMS_FOR_COURSE_MODE = {
181
        'audit': {},
182 183 184
        'honor': {'honor_mode': True},
        'verified': {'verified_mode': True, 'contribution': '1.23'},
        'unsupported': {'unsupported_mode': True},
185 186 187
    }

    @ddt.data(
188
        ('honor', 'dashboard'),
189
        ('verified', 'start-flow'),
190 191
    )
    @ddt.unpack
192
    def test_choose_mode_redirect(self, course_mode, expected_redirect):
193 194
        # Create the course modes
        for mode in ('audit', 'honor', 'verified'):
195 196
            min_price = 0 if course_mode in ["honor", "audit"] else 1
            CourseModeFactory(mode_slug=mode, course_id=self.course.id, min_price=min_price)
197 198 199

        # Choose the mode (POST request)
        choose_track_url = reverse('course_modes_choose', args=[unicode(self.course.id)])
200
        response = self.client.post(choose_track_url, self.POST_PARAMS_FOR_COURSE_MODE[course_mode])
201 202 203 204

        # Verify the redirect
        if expected_redirect == 'dashboard':
            redirect_url = reverse('dashboard')
205
        elif expected_redirect == 'start-flow':
206
            redirect_url = reverse(
207
                'verify_student_start_flow',
208
                kwargs={'course_id': unicode(self.course.id)}
209
            )
210 211
        else:
            self.fail("Must provide a valid redirect URL name")
212

213
        self.assertRedirects(response, redirect_url)
214 215 216

    def test_remember_donation_for_course(self):
        # Create the course modes
217
        for mode in ('honor', 'verified'):
218 219 220 221 222 223 224 225 226 227 228 229 230
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

        # Choose the mode (POST request)
        choose_track_url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        self.client.post(choose_track_url, self.POST_PARAMS_FOR_COURSE_MODE['verified'])

        # Expect that the contribution amount is stored in the user's session
        self.assertIn('donation_for_course', self.client.session)
        self.assertIn(unicode(self.course.id), self.client.session['donation_for_course'])

        actual_amount = self.client.session['donation_for_course'][unicode(self.course.id)]
        expected_amount = decimal.Decimal(self.POST_PARAMS_FOR_COURSE_MODE['verified']['contribution'])
        self.assertEqual(actual_amount, expected_amount)
231

232
    def test_successful_default_enrollment(self):
233
        # Create the course modes
234
        for mode in (CourseMode.DEFAULT_MODE_SLUG, 'verified'):
235 236
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

237 238 239 240 241 242 243 244 245
        # Enroll the user in the default mode (honor) to emulate
        # automatic enrollment
        params = {
            'enrollment_action': 'enroll',
            'course_id': unicode(self.course.id)
        }
        self.client.post(reverse('change_enrollment'), params)

        # Explicitly select the honor mode (POST request)
246
        choose_track_url = reverse('course_modes_choose', args=[unicode(self.course.id)])
247
        self.client.post(choose_track_url, self.POST_PARAMS_FOR_COURSE_MODE[CourseMode.DEFAULT_MODE_SLUG])
248

249
        # Verify that the user's enrollment remains unchanged
250
        mode, is_active = CourseEnrollment.enrollment_mode_for_user(self.user, self.course.id)
251
        self.assertEqual(mode, CourseMode.DEFAULT_MODE_SLUG)
252
        self.assertEqual(is_active, True)
253 254 255 256 257 258 259 260 261 262 263

    def test_unsupported_enrollment_mode_failure(self):
        # Create the supported course modes
        for mode in ('honor', 'verified'):
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

        # Choose an unsupported mode (POST request)
        choose_track_url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        response = self.client.post(choose_track_url, self.POST_PARAMS_FOR_COURSE_MODE['unsupported'])

        self.assertEqual(400, response.status_code)
264 265 266 267 268 269 270 271 272

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
    def test_default_mode_creation(self):
        # Hit the mode creation endpoint with no querystring params, to create an honor mode
        url = reverse('create_mode', args=[unicode(self.course.id)])
        response = self.client.get(url)

        self.assertEquals(response.status_code, 200)

Diana Huang committed
273
        expected_mode = [Mode(u'honor', u'Honor Code Certificate', 0, '', 'usd', None, None, None)]
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        course_mode = CourseMode.modes_for_course(self.course.id)

        self.assertEquals(course_mode, expected_mode)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
    @ddt.data(
        (u'verified', u'Verified Certificate', 10, '10,20,30', 'usd'),
        (u'professional', u'Professional Education', 100, '100,200', 'usd'),
    )
    @ddt.unpack
    def test_verified_mode_creation(self, mode_slug, mode_display_name, min_price, suggested_prices, currency):
        parameters = {}
        parameters['mode_slug'] = mode_slug
        parameters['mode_display_name'] = mode_display_name
        parameters['min_price'] = min_price
        parameters['suggested_prices'] = suggested_prices
        parameters['currency'] = currency

        url = reverse('create_mode', args=[unicode(self.course.id)])
        response = self.client.get(url, parameters)

        self.assertEquals(response.status_code, 200)

Diana Huang committed
297
        expected_mode = [Mode(mode_slug, mode_display_name, min_price, suggested_prices, currency, None, None, None)]
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        course_mode = CourseMode.modes_for_course(self.course.id)

        self.assertEquals(course_mode, expected_mode)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
    def test_multiple_mode_creation(self):
        # Create an honor mode
        base_url = reverse('create_mode', args=[unicode(self.course.id)])
        self.client.get(base_url)

        # Excluding the currency parameter implicitly tests the mode creation endpoint's ability to
        # use default values when parameters are partially missing.
        parameters = {}
        parameters['mode_slug'] = u'verified'
        parameters['mode_display_name'] = u'Verified Certificate'
        parameters['min_price'] = 10
        parameters['suggested_prices'] = '10,20'

        # Create a verified mode
        url = reverse('create_mode', args=[unicode(self.course.id)])
318
        self.client.get(url, parameters)
319

Diana Huang committed
320 321
        honor_mode = Mode(u'honor', u'Honor Code Certificate', 0, '', 'usd', None, None, None)
        verified_mode = Mode(u'verified', u'Verified Certificate', 10, '10,20', 'usd', None, None, None)
322 323 324 325
        expected_modes = [honor_mode, verified_mode]
        course_modes = CourseMode.modes_for_course(self.course.id)

        self.assertEquals(course_modes, expected_modes)
326

327
    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
328
    @with_is_edx_domain(True)
329 330 331 332 333 334 335 336 337 338 339 340 341 342
    def test_hide_nav(self):
        # Create the course modes
        for mode in ["honor", "verified"]:
            CourseModeFactory(mode_slug=mode, course_id=self.course.id)

        # Load the track selection page
        url = reverse('course_modes_choose', args=[unicode(self.course.id)])
        response = self.client.get(url)

        # Verify that the header navigation links are hidden for the edx.org version
        self.assertNotContains(response, "How it Works")
        self.assertNotContains(response, "Find courses")
        self.assertNotContains(response, "Schools & Partners")

343 344 345 346 347

@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
class TrackSelectionEmbargoTest(UrlResetMixin, ModuleStoreTestCase):
    """Test embargo restrictions on the track selection page. """

348
    @patch.dict(settings.FEATURES, {'EMBARGO': True})
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    def setUp(self):
        super(TrackSelectionEmbargoTest, self).setUp('embargo')

        # Create a course and course modes
        self.course = CourseFactory.create()
        CourseModeFactory(mode_slug='honor', course_id=self.course.id)
        CourseModeFactory(mode_slug='verified', course_id=self.course.id, min_price=10)

        # Create a user and log in
        self.user = UserFactory.create(username="Bob", email="bob@example.com", password="edx")
        self.client.login(username=self.user.username, password="edx")

        # Construct the URL for the track selection page
        self.url = reverse('course_modes_choose', args=[unicode(self.course.id)])

364
    @patch.dict(settings.FEATURES, {'EMBARGO': True})
365 366 367 368 369 370 371 372
    def test_embargo_restrict(self):
        with restrict_course(self.course.id) as redirect_url:
            response = self.client.get(self.url)
            self.assertRedirects(response, redirect_url)

    def test_embargo_allow(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)