test_tools.py 11.2 KB
Newer Older
1 2 3 4 5 6 7 8
"""
Tests for views/tools.py.
"""

import datetime
import json
import unittest

9
import mock
10
from django.test import TestCase
11
from django.test.utils import override_settings
12
from pytz import UTC
13
from nose.plugins.attrib import attr
14
from opaque_keys.edx.keys import CourseKey
15 16 17

from courseware.field_overrides import OverrideFieldData
from lms.djangoapps.ccx.tests.test_overrides import inject_field_overrides
18
from student.tests.factories import UserFactory
19
from xmodule.fields import Date
20
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase
21 22 23 24 25 26 27
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory

from ..views import tools

DATE_FIELD = Date()


28
@attr(shard=1)
29 30 31 32 33 34 35 36 37 38
class TestDashboardError(unittest.TestCase):
    """
    Test DashboardError exceptions.
    """
    def test_response(self):
        error = tools.DashboardError(u'Oh noes!')
        response = json.loads(error.response().content)
        self.assertEqual(response, {'error': 'Oh noes!'})


39
@attr(shard=1)
40 41 42 43 44
class TestHandleDashboardError(unittest.TestCase):
    """
    Test handle_dashboard_error decorator.
    """
    def test_error(self):
45
        # pylint: disable=unused-argument
46 47 48 49 50 51 52 53 54 55 56
        @tools.handle_dashboard_error
        def view(request, course_id):
            """
            Raises DashboardError.
            """
            raise tools.DashboardError("Oh noes!")

        response = json.loads(view(None, None).content)
        self.assertEqual(response, {'error': 'Oh noes!'})

    def test_no_error(self):
57
        # pylint: disable=unused-argument
58 59 60 61 62 63 64 65 66 67
        @tools.handle_dashboard_error
        def view(request, course_id):
            """
            Returns "Oh yes!"
            """
            return "Oh yes!"

        self.assertEqual(view(None, None), "Oh yes!")


68
@attr(shard=1)
69
class TestRequireStudentIdentifier(TestCase):
70 71 72 73 74 75 76
    """
    Test require_student_from_identifier()
    """
    def setUp(self):
        """
        Fixtures
        """
77
        super(TestRequireStudentIdentifier, self).setUp()
78 79 80 81 82 83 84 85 86 87 88 89 90
        self.student = UserFactory.create()

    def test_valid_student_id(self):
        self.assertEqual(
            self.student,
            tools.require_student_from_identifier(self.student.username)
        )

    def test_invalid_student_id(self):
        with self.assertRaises(tools.DashboardError):
            tools.require_student_from_identifier("invalid")


91
@attr(shard=1)
92 93 94 95 96 97 98
class TestParseDatetime(unittest.TestCase):
    """
    Test date parsing.
    """
    def test_parse_no_error(self):
        self.assertEqual(
            tools.parse_datetime('5/12/2010 2:42'),
99
            datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC))
100 101 102 103 104 105

    def test_parse_error(self):
        with self.assertRaises(tools.DashboardError):
            tools.parse_datetime('foo')


106
@attr(shard=1)
107
class TestFindUnit(SharedModuleStoreTestCase):
108 109 110
    """
    Test the find_unit function.
    """
111 112 113 114 115 116 117
    @classmethod
    def setUpClass(cls):
        super(TestFindUnit, cls).setUpClass()
        cls.course = CourseFactory.create()
        with cls.store.bulk_operations(cls.course.id, emit_signals=False):
            week1 = ItemFactory.create(parent=cls.course)
            cls.homework = ItemFactory.create(parent=week1)
118 119 120 121 122

    def test_find_unit_success(self):
        """
        Test finding a nested unit.
        """
123
        url = self.homework.location.to_deprecated_string()
jsa committed
124 125
        found_unit = tools.find_unit(self.course, url)
        self.assertEqual(found_unit.location, self.homework.location)
126 127 128 129 130 131 132 133 134 135

    def test_find_unit_notfound(self):
        """
        Test attempt to find a unit that does not exist.
        """
        url = "i4x://MITx/999/chapter/notfound"
        with self.assertRaises(tools.DashboardError):
            tools.find_unit(self.course, url)


136
@attr(shard=1)
137 138 139 140 141 142 143 144
class TestGetUnitsWithDueDate(ModuleStoreTestCase):
    """
    Test the get_units_with_due_date function.
    """
    def setUp(self):
        """
        Fixtures.
        """
145 146
        super(TestGetUnitsWithDueDate, self).setUp()

147
        due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC)
148
        course = CourseFactory.create()
149 150
        week1 = ItemFactory.create(due=due, parent=course)
        week2 = ItemFactory.create(due=due, parent=course)
151

stv committed
152
        ItemFactory.create(
153
            parent=week1,
154 155 156 157 158 159 160 161 162 163 164
            due=due
        )

        self.course = course
        self.week1 = week1
        self.week2 = week2

    def test_it(self):

        def urls(seq):
            "URLs for sequence of nodes."
165
            return sorted(i.location.to_deprecated_string() for i in seq)
166 167 168 169 170 171

        self.assertEquals(
            urls(tools.get_units_with_due_date(self.course)),
            urls((self.week1, self.week2)))


172
@attr(shard=1)
173 174 175 176 177 178 179 180 181 182
class TestTitleOrUrl(unittest.TestCase):
    """
    Test the title_or_url funciton.
    """
    def test_title(self):
        unit = mock.Mock(display_name='hello')
        self.assertEquals(tools.title_or_url(unit), 'hello')

    def test_url(self):
        unit = mock.Mock(display_name=None)
183
        unit.location.to_deprecated_string.return_value = 'test:hello'
184 185 186
        self.assertEquals(tools.title_or_url(unit), 'test:hello')


187
@attr(shard=1)
188 189 190 191
@override_settings(
    FIELD_OVERRIDE_PROVIDERS=(
        'courseware.student_field_overrides.IndividualStudentOverrideProvider',),
)
192 193 194 195 196 197 198 199
class TestSetDueDateExtension(ModuleStoreTestCase):
    """
    Test the set_due_date_extensions function.
    """
    def setUp(self):
        """
        Fixtures.
        """
200 201
        super(TestSetDueDateExtension, self).setUp()

202
        self.due = due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC)
203
        course = CourseFactory.create()
204 205
        week1 = ItemFactory.create(due=due, parent=course)
        week2 = ItemFactory.create(due=due, parent=course)
206
        week3 = ItemFactory.create(parent=course)
207 208
        homework = ItemFactory.create(parent=week1)
        assignment = ItemFactory.create(parent=homework, due=due)
209 210 211 212 213 214

        user = UserFactory.create()

        self.course = course
        self.week1 = week1
        self.homework = homework
215
        self.assignment = assignment
216
        self.week2 = week2
217
        self.week3 = week3
218 219
        self.user = user

220
        inject_field_overrides((course, week1, week2, week3, homework, assignment), course, user)
221 222

    def tearDown(self):
223
        super(TestSetDueDateExtension, self).tearDown()
224 225 226 227 228 229 230 231 232 233 234
        OverrideFieldData.provider_classes = None

    def _clear_field_data_cache(self):
        """
        Clear field data cache for xblocks under test. Normally this would be
        done by virtue of the fact that xblocks are reloaded on subsequent
        requests.
        """
        for block in (self.week1, self.week2, self.week3,
                      self.homework, self.assignment):
            block.fields['due']._del_cached_value(block)  # pylint: disable=protected-access
235 236

    def test_set_due_date_extension(self):
237
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC)
238
        tools.set_due_date_extension(self.course, self.week1, self.user, extended)
239 240 241 242
        self._clear_field_data_cache()
        self.assertEqual(self.week1.due, extended)
        self.assertEqual(self.homework.due, extended)
        self.assertEqual(self.assignment.due, extended)
243

244
    def test_set_due_date_extension_num_queries(self):
245
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC)
246
        with self.assertNumQueries(5):
247 248 249
            tools.set_due_date_extension(self.course, self.week1, self.user, extended)
            self._clear_field_data_cache()

250
    def test_set_due_date_extension_invalid_date(self):
251
        extended = datetime.datetime(2009, 1, 1, 0, 0, tzinfo=UTC)
252 253 254 255
        with self.assertRaises(tools.DashboardError):
            tools.set_due_date_extension(self.course, self.week1, self.user, extended)

    def test_set_due_date_extension_no_date(self):
256
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC)
257 258
        with self.assertRaises(tools.DashboardError):
            tools.set_due_date_extension(self.course, self.week3, self.user, extended)
259 260

    def test_reset_due_date_extension(self):
261
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC)
262
        tools.set_due_date_extension(self.course, self.week1, self.user, extended)
263
        tools.set_due_date_extension(self.course, self.week1, self.user, None)
264
        self.assertEqual(self.week1.due, self.due)
265 266


267
@attr(shard=1)
268 269 270 271 272 273 274 275 276
class TestDataDumps(ModuleStoreTestCase):
    """
    Test data dumps for reporting.
    """

    def setUp(self):
        """
        Fixtures.
        """
277 278
        super(TestDataDumps, self).setUp()

279
        due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC)
280
        course = CourseFactory.create()
281 282
        week1 = ItemFactory.create(due=due, parent=course)
        week2 = ItemFactory.create(due=due, parent=course)
283 284

        homework = ItemFactory.create(
285
            parent=week1,
286 287 288 289 290 291 292 293 294 295 296 297 298
            due=due
        )

        user1 = UserFactory.create()
        user2 = UserFactory.create()
        self.course = course
        self.week1 = week1
        self.homework = homework
        self.week2 = week2
        self.user1 = user1
        self.user2 = user2

    def test_dump_module_extensions(self):
299
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        tools.set_due_date_extension(self.course, self.week1, self.user1,
                                     extended)
        tools.set_due_date_extension(self.course, self.week1, self.user2,
                                     extended)
        report = tools.dump_module_extensions(self.course, self.week1)
        self.assertEqual(
            report['title'], u'Users with due date extensions for ' +
            self.week1.display_name)
        self.assertEqual(
            report['header'], ["Username", "Full Name", "Extended Due Date"])
        self.assertEqual(report['data'], [
            {"Username": self.user1.username,
             "Full Name": self.user1.profile.name,
             "Extended Due Date": "2013-12-25 00:00"},
            {"Username": self.user2.username,
             "Full Name": self.user2.profile.name,
             "Extended Due Date": "2013-12-25 00:00"}])

    def test_dump_student_extensions(self):
319
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC)
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        tools.set_due_date_extension(self.course, self.week1, self.user1,
                                     extended)
        tools.set_due_date_extension(self.course, self.week2, self.user1,
                                     extended)
        report = tools.dump_student_extensions(self.course, self.user1)
        self.assertEqual(
            report['title'], u'Due date extensions for %s (%s)' %
            (self.user1.profile.name, self.user1.username))
        self.assertEqual(
            report['header'], ["Unit", "Extended Due Date"])
        self.assertEqual(report['data'], [
            {"Unit": self.week1.display_name,
             "Extended Due Date": "2013-12-25 00:00"},
            {"Unit": self.week2.display_name,
             "Extended Due Date": "2013-12-25 00:00"}])


337 338 339 340 341 342 343 344 345 346
def msk_from_problem_urlname(course_id, urlname, block_type='problem'):
    """
    Convert a 'problem urlname' to a module state key (db field)
    """
    if not isinstance(course_id, CourseKey):
        raise ValueError
    if urlname.endswith(".xml"):
        urlname = urlname[:-4]

    return course_id.make_usage_key(block_type, urlname)