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 uuid import uuid4
10
from util.date_utils import get_time_display, DEFAULT_DATE_TIME_FORMAT
11
from nose.plugins.attrib import attr
Carson Gee committed
12 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 django.utils.timezone import utc as UTC
Carson Gee committed
18
import mongoengine
19
from opaque_keys.edx.locations import SlashSeparatedCourseKey
Carson Gee committed
20 21

from dashboard.models import CourseImportLog
22
from dashboard.git_import import GitImportErrorNoDir
23
from datetime import datetime
24
from student.roles import CourseStaffRole, GlobalStaff
Carson Gee committed
25 26
from student.tests.factories import UserFactory
from xmodule.modulestore.django import modulestore
27
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
28
from xmodule.modulestore.tests.mongo_connection import MONGO_PORT_NUM, MONGO_HOST
muhammad-ammar committed
29

Carson Gee committed
30 31

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

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


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

48 49
    TEST_REPO = 'https://github.com/mitocw/edx4edx_lite.git'
    TEST_BRANCH = 'testing_do_not_delete'
50
    TEST_BRANCH_COURSE = SlashSeparatedCourseKey('MITx', 'edx4edx_branch', 'edx4edx')
51

Carson Gee committed
52 53
    def setUp(self):
        """Setup test case by adding primary user."""
54
        super(SysadminBaseTestCase, self).setUp()
Carson Gee committed
55 56 57 58 59 60 61 62 63 64
        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')

65
    def _add_edx4edx(self, branch=None):
Carson Gee committed
66
        """Adds the edx4edx sample course"""
67 68 69 70
        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
71 72 73 74

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

        # Delete git loaded course
85 86 87 88 89 90 91
        response = self.client.post(
            reverse('sysadmin_courses'),
            {
                'course_id': course.id.to_deprecated_string(),
                'action': 'del_course',
            }
        )
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        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
110 111


112
@attr(shard=1)
113 114 115 116
@override_settings(
    MONGODB_LOG=TEST_MONGODB_LOG,
    GIT_REPO_DIR=settings.TEST_ROOT / "course_repos_{}".format(uuid4().hex)
)
Carson Gee committed
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
@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()

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

        # Create git loaded course
        response = self._add_edx4edx()
156
        self.assertIn(GitImportErrorNoDir(settings.GIT_REPO_DIR).message,
Carson Gee committed
157 158 159 160 161 162 163 164 165
                      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()
166
        self._mkdir(settings.GIT_REPO_DIR)
Carson Gee committed
167 168

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

        self._add_edx4edx()
172
        course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))
Carson Gee committed
173 174 175
        self.assertIsNotNone(course)

        self._rm_edx4edx()
176
        course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))
Carson Gee committed
177 178
        self.assertIsNone(course)

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    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()
194
        self._mkdir(settings.GIT_REPO_DIR)
195 196 197 198 199 200 201 202 203

        # 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
204 205 206 207 208 209
    def test_gitlogs(self):
        """
        Create a log entry and make sure it exists
        """

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

        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'}))

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

        self._rm_edx4edx()

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    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()
243
        self._mkdir(settings.GIT_REPO_DIR)
244 245 246 247 248 249 250 251

        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'))
252
                self.assertIn(date_text, response.content.decode('UTF-8'))
253 254 255

        self._rm_edx4edx()

Carson Gee committed
256 257 258 259 260 261 262 263
    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'}))
264
        self.assertEqual(404, response.status_code)
Carson Gee committed
265

266 267 268 269 270 271 272
    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()
273
        self._mkdir(settings.GIT_REPO_DIR)
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

        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()

293 294 295 296 297 298 299 300
    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()

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

303 304 305 306 307 308 309 310 311 312 313
        for _ in xrange(15):
            CourseImportLog(
                course_id=SlashSeparatedCourseKey("test", "test", "test"),
                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)]:
314 315
            response = self.client.get(
                '{}?page={}'.format(
316
                    reverse('gitlogs'),
317 318 319 320
                    page
                )
            )
            self.assertIn(
321
                'Page {} of 2'.format(expected),
322 323 324
                response.content
            )

325
        CourseImportLog.objects.delete()
326

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

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

        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={
345 346
            'course_id': 'MITx/edx4edx/edx4edx'
        }))
Carson Gee committed
347 348 349 350
        self.assertEqual(response.status_code, 404)

        # Add user as staff in course team
        def_ms = modulestore()
351 352
        course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))
        CourseStaffRole(course.id).add_users(self.user)
Carson Gee committed
353

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

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

        self._rm_edx4edx()