test_sysadmin.py 11.8 KB
Newer Older
Carson Gee committed
1 2 3
"""
Provide tests for sysadmin dashboard feature in sysadmin.py
"""
4
import glob
Carson Gee committed
5
import os
6
import re
Carson Gee committed
7
import shutil
8
import unittest
9
from datetime import datetime
10
from uuid import uuid4
Carson Gee committed
11

12
import mongoengine
Carson Gee committed
13 14 15 16
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.client import Client
from django.test.utils import override_settings
17
from pytz import UTC
18
from nose.plugins.attrib import attr
19
from opaque_keys.edx.keys import CourseKey
Carson Gee committed
20

21
from dashboard.git_import import GitImportErrorNoDir
22
from dashboard.models import CourseImportLog
23
from student.roles import CourseStaffRole, GlobalStaff
Carson Gee committed
24
from student.tests.factories import UserFactory
25
from util.date_utils import DEFAULT_DATE_TIME_FORMAT, get_time_display
Carson Gee committed
26
from xmodule.modulestore.django import modulestore
27
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
28
from xmodule.modulestore.tests.mongo_connection import MONGO_HOST, MONGO_PORT_NUM
Carson Gee committed
29 30

TEST_MONGODB_LOG = {
31 32
    'host': MONGO_HOST,
    'port': MONGO_PORT_NUM,
Carson Gee committed
33 34 35 36 37 38
    'user': '',
    'password': '',
    'db': 'test_xlog',
}

FEATURES_WITH_SSL_AUTH = settings.FEATURES.copy()
39
FEATURES_WITH_SSL_AUTH['AUTH_USE_CERTIFICATES'] = True
Carson Gee committed
40 41


42
class SysadminBaseTestCase(SharedModuleStoreTestCase):
Carson Gee committed
43 44 45 46
    """
    Base class with common methods used in XML and Mongo tests
    """

47 48
    TEST_REPO = 'https://github.com/mitocw/edx4edx_lite.git'
    TEST_BRANCH = 'testing_do_not_delete'
49
    TEST_BRANCH_COURSE = CourseKey.from_string('MITx/edx4edx_branch/edx4edx')
50

Carson Gee committed
51 52
    def setUp(self):
        """Setup test case by adding primary user."""
53
        super(SysadminBaseTestCase, self).setUp()
Carson Gee committed
54 55 56 57 58 59 60 61 62 63
        self.user = UserFactory.create(username='test_user',
                                       email='test_user+sysadmin@edx.org',
                                       password='foo')
        self.client = Client()

    def _setstaff_login(self):
        """Makes the test user staff and logs them in"""
        GlobalStaff().add_users(self.user)
        self.client.login(username=self.user.username, password='foo')

64
    def _add_edx4edx(self, branch=None):
Carson Gee committed
65
        """Adds the edx4edx sample course"""
66 67 68 69
        post_dict = {'repo_location': self.TEST_REPO, 'action': 'add_course', }
        if branch:
            post_dict['repo_branch'] = branch
        return self.client.post(reverse('sysadmin_courses'), post_dict)
Carson Gee committed
70 71 72 73

    def _rm_edx4edx(self):
        """Deletes the sample course from the XML store"""
        def_ms = modulestore()
74 75
        course_path = '{0}/edx4edx_lite'.format(
            os.path.abspath(settings.DATA_DIR))
Carson Gee committed
76 77
        try:
            # using XML store
78
            course = def_ms.courses.get(course_path, None)
Carson Gee committed
79 80
        except AttributeError:
            # Using mongo store
81
            course = def_ms.get_course(CourseKey.from_string('MITx/edx4edx/edx4edx'))
Carson Gee committed
82 83

        # Delete git loaded course
84 85 86 87 88 89 90
        response = self.client.post(
            reverse('sysadmin_courses'),
            {
                'course_id': course.id.to_deprecated_string(),
                'action': 'del_course',
            }
        )
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        self.addCleanup(self._rm_glob, '{0}_deleted_*'.format(course_path))

        return response

    def _rm_glob(self, path):
        """
        Create a shell expansion of passed in parameter and iteratively
        remove them.  Must only expand to directories.
        """
        for path in glob.glob(path):
            shutil.rmtree(path)

    def _mkdir(self, path):
        """
        Create directory and add the cleanup for it.
        """
        os.mkdir(path)
        self.addCleanup(shutil.rmtree, path)
Carson Gee committed
109 110


111
@attr(shard=1)
112 113 114 115
@override_settings(
    MONGODB_LOG=TEST_MONGODB_LOG,
    GIT_REPO_DIR=settings.TEST_ROOT / "course_repos_{}".format(uuid4().hex)
)
Carson Gee committed
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
@unittest.skipUnless(settings.FEATURES.get('ENABLE_SYSADMIN_DASHBOARD'),
                     "ENABLE_SYSADMIN_DASHBOARD not set")
class TestSysAdminMongoCourseImport(SysadminBaseTestCase):
    """
    Check that importing into the mongo module store works
    """

    @classmethod
    def tearDownClass(cls):
        """Delete mongo log entries after test."""
        super(TestSysAdminMongoCourseImport, cls).tearDownClass()
        try:
            mongoengine.connect(TEST_MONGODB_LOG['db'])
            CourseImportLog.objects.all().delete()
        except mongoengine.connection.ConnectionError:
            pass

    def _setstaff_login(self):
        """
        Makes the test user staff and logs them in
        """

        self.user.is_staff = True
        self.user.save()

        self.client.login(username=self.user.username, password='foo')

    def test_missing_repo_dir(self):
        """
        Ensure that we handle a missing repo dir
        """

        self._setstaff_login()

150 151
        if os.path.isdir(settings.GIT_REPO_DIR):
            shutil.rmtree(settings.GIT_REPO_DIR)
Carson Gee committed
152 153 154

        # Create git loaded course
        response = self._add_edx4edx()
155
        self.assertIn(GitImportErrorNoDir(settings.GIT_REPO_DIR).message,
Carson Gee committed
156 157 158 159 160 161 162 163 164
                      response.content.decode('UTF-8'))

    def test_mongo_course_add_delete(self):
        """
        This is the same as TestSysadmin.test_xml_course_add_delete,
        but it uses a mongo store
        """

        self._setstaff_login()
165
        self._mkdir(settings.GIT_REPO_DIR)
Carson Gee committed
166 167

        def_ms = modulestore()
168
        self.assertNotEqual('xml', def_ms.get_modulestore_type(None))
Carson Gee committed
169 170

        self._add_edx4edx()
171
        course = def_ms.get_course(CourseKey.from_string('MITx/edx4edx/edx4edx'))
Carson Gee committed
172 173 174
        self.assertIsNotNone(course)

        self._rm_edx4edx()
175
        course = def_ms.get_course(CourseKey.from_string('MITx/edx4edx/edx4edx'))
Carson Gee committed
176 177
        self.assertIsNone(course)

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    def test_course_info(self):
        """
        Check to make sure we are getting git info for courses
        """
        # Regex of first 3 columns of course information table row for
        # test course loaded from git. Would not have sha1 if
        # git_info_for_course failed.
        table_re = re.compile(r"""
            <tr>\s+
            <td>edX\sAuthor\sCourse</td>\s+  # expected test git course name
            <td>MITx/edx4edx/edx4edx</td>\s+  # expected test git course_id
            <td>[a-fA-F\d]{40}</td>  # git sha1 hash
        """, re.VERBOSE)

        self._setstaff_login()
193
        self._mkdir(settings.GIT_REPO_DIR)
194 195 196 197 198 199 200 201 202

        # Make sure we don't have any git hashes on the page
        response = self.client.get(reverse('sysadmin_courses'))
        self.assertNotRegexpMatches(response.content, table_re)

        # Now add the course and make sure it does match
        response = self._add_edx4edx()
        self.assertRegexpMatches(response.content, table_re)

Carson Gee committed
203 204 205 206 207 208
    def test_gitlogs(self):
        """
        Create a log entry and make sure it exists
        """

        self._setstaff_login()
209
        self._mkdir(settings.GIT_REPO_DIR)
Carson Gee committed
210 211 212 213 214 215 216 217 218 219 220

        self._add_edx4edx()
        response = self.client.get(reverse('gitlogs'))

        # Check that our earlier import has a log with a link to details
        self.assertIn('/gitlogs/MITx/edx4edx/edx4edx', response.content)

        response = self.client.get(
            reverse('gitlogs_detail', kwargs={
                'course_id': 'MITx/edx4edx/edx4edx'}))

221
        self.assertIn('======&gt; IMPORTING course',
Carson Gee committed
222 223 224 225
                      response.content)

        self._rm_edx4edx()

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    def test_gitlog_date(self):
        """
        Make sure the date is timezone-aware and being converted/formatted
        properly.
        """

        tz_names = [
            'America/New_York',  # UTC - 5
            'Asia/Pyongyang',    # UTC + 9
            'Europe/London',     # UTC
            'Canada/Yukon',      # UTC - 8
            'Europe/Moscow',     # UTC + 4
        ]
        tz_format = DEFAULT_DATE_TIME_FORMAT

        self._setstaff_login()
242
        self._mkdir(settings.GIT_REPO_DIR)
243 244 245 246 247 248 249 250

        self._add_edx4edx()
        date = CourseImportLog.objects.first().created.replace(tzinfo=UTC)

        for timezone in tz_names:
            with (override_settings(TIME_ZONE=timezone)):
                date_text = get_time_display(date, tz_format, settings.TIME_ZONE)
                response = self.client.get(reverse('gitlogs'))
251
                self.assertIn(date_text, response.content.decode('UTF-8'))
252 253 254

        self._rm_edx4edx()

Carson Gee committed
255 256 257 258 259 260 261 262
    def test_gitlog_bad_course(self):
        """
        Make sure we gracefully handle courses that don't exist.
        """
        self._setstaff_login()
        response = self.client.get(
            reverse('gitlogs_detail', kwargs={
                'course_id': 'Not/Real/Testing'}))
263
        self.assertEqual(404, response.status_code)
Carson Gee committed
264

265 266 267 268 269 270 271
    def test_gitlog_no_logs(self):
        """
        Make sure the template behaves well when rendered despite there not being any logs.
        (This is for courses imported using methods other than the git_add_course command)
        """

        self._setstaff_login()
272
        self._mkdir(settings.GIT_REPO_DIR)
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

        self._add_edx4edx()

        # Simulate a lack of git import logs
        import_logs = CourseImportLog.objects.all()
        import_logs.delete()

        response = self.client.get(
            reverse('gitlogs_detail', kwargs={
                'course_id': 'MITx/edx4edx/edx4edx'
            })
        )
        self.assertIn(
            'No git import logs have been recorded for this course.',
            response.content
        )

        self._rm_edx4edx()

292 293 294 295 296 297 298 299
    def test_gitlog_pagination_out_of_range_invalid(self):
        """
        Make sure the pagination behaves properly when the requested page is out
        of range.
        """

        self._setstaff_login()

300
        mongoengine.connect(TEST_MONGODB_LOG['db'])
301

302 303
        for _ in xrange(15):
            CourseImportLog(
304
                course_id=CourseKey.from_string("test/test/test"),
305 306 307 308 309 310 311 312
                location="location",
                import_log="import_log",
                git_log="git_log",
                repo_dir="repo_dir",
                created=datetime.now()
            ).save()

        for page, expected in [(-1, 1), (1, 1), (2, 2), (30, 2), ('abc', 1)]:
313 314
            response = self.client.get(
                '{}?page={}'.format(
315
                    reverse('gitlogs'),
316 317 318 319
                    page
                )
            )
            self.assertIn(
320
                'Page {} of 2'.format(expected),
321 322 323
                response.content
            )

324
        CourseImportLog.objects.delete()
325

Carson Gee committed
326 327 328 329 330
    def test_gitlog_courseteam_access(self):
        """
        Ensure course team users are allowed to access only their own course.
        """

331
        self._mkdir(settings.GIT_REPO_DIR)
Carson Gee committed
332 333 334 335 336 337 338 339 340 341 342 343

        self._setstaff_login()
        self._add_edx4edx()
        self.user.is_staff = False
        self.user.save()
        logged_in = self.client.login(username=self.user.username,
                                      password='foo')
        response = self.client.get(reverse('gitlogs'))
        # Make sure our non privileged user doesn't have access to all logs
        self.assertEqual(response.status_code, 404)
        # Or specific logs
        response = self.client.get(reverse('gitlogs_detail', kwargs={
344 345
            'course_id': 'MITx/edx4edx/edx4edx'
        }))
Carson Gee committed
346 347 348 349
        self.assertEqual(response.status_code, 404)

        # Add user as staff in course team
        def_ms = modulestore()
350
        course = def_ms.get_course(CourseKey.from_string('MITx/edx4edx/edx4edx'))
351
        CourseStaffRole(course.id).add_users(self.user)
Carson Gee committed
352

353
        self.assertTrue(CourseStaffRole(course.id).has_user(self.user))
Carson Gee committed
354 355 356 357 358 359
        logged_in = self.client.login(username=self.user.username,
                                      password='foo')
        self.assertTrue(logged_in)

        response = self.client.get(
            reverse('gitlogs_detail', kwargs={
360 361 362
                'course_id': 'MITx/edx4edx/edx4edx'
            }))
        self.assertIn('======&gt; IMPORTING course',
Carson Gee committed
363 364 365
                      response.content)

        self._rm_edx4edx()