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.utils import override_settings
11
from django.utils.timezone import utc
12
from nose.plugins.attrib import attr
13
from opaque_keys.edx.keys import CourseKey
14 15 16

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

from ..views import tools

DATE_FIELD = Date()


27
@attr(shard=1)
28 29 30 31 32 33 34 35 36 37
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!'})


38
@attr(shard=1)
39 40 41 42 43
class TestHandleDashboardError(unittest.TestCase):
    """
    Test handle_dashboard_error decorator.
    """
    def test_error(self):
44
        # pylint: disable=unused-argument
45 46 47 48 49 50 51 52 53 54 55
        @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):
56
        # pylint: disable=unused-argument
57 58 59 60 61 62 63 64 65 66
        @tools.handle_dashboard_error
        def view(request, course_id):
            """
            Returns "Oh yes!"
            """
            return "Oh yes!"

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


67
@attr(shard=1)
68 69 70 71 72 73 74 75
class TestRequireStudentIdentifier(unittest.TestCase):
    """
    Test require_student_from_identifier()
    """
    def setUp(self):
        """
        Fixtures
        """
76
        super(TestRequireStudentIdentifier, self).setUp()
77 78 79 80 81 82 83 84 85 86 87 88 89
        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")


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

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


105
@attr(shard=1)
106
class TestFindUnit(SharedModuleStoreTestCase):
107 108 109
    """
    Test the find_unit function.
    """
110 111 112 113 114 115 116
    @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)
117 118 119 120 121

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

    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)


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

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

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

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

    def test_it(self):

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

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


171
@attr(shard=1)
172 173 174 175 176 177 178 179 180 181
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)
182
        unit.location.to_deprecated_string.return_value = 'test:hello'
183 184 185
        self.assertEquals(tools.title_or_url(unit), 'test:hello')


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

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

        user = UserFactory.create()

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

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

    def tearDown(self):
222
        super(TestSetDueDateExtension, self).tearDown()
223 224 225 226 227 228 229 230 231 232 233
        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
234 235 236

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

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

249 250 251 252 253 254 255 256 257
    def test_set_due_date_extension_invalid_date(self):
        extended = datetime.datetime(2009, 1, 1, 0, 0, tzinfo=utc)
        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):
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=utc)
        with self.assertRaises(tools.DashboardError):
            tools.set_due_date_extension(self.course, self.week3, self.user, extended)
258 259

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


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

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

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

        homework = ItemFactory.create(
284
            parent=week1,
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 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
            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):
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=utc)
        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):
        extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=utc)
        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"}])


336 337 338 339 340 341 342 343 344 345
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)