Skip to content
test_admin.py 17.6 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
from __future__ import division

__copyright__ = "Copyright (C) 2018 Dong Zhuang"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import six
from unittest import skipIf

from django.test import TestCase, RequestFactory
from django.urls import reverse
from django.utils.timezone import now
from django.contrib.auth import get_user_model
from django.contrib.admin import site
from django.contrib.admin.models import LogEntry

from course.models import Participation
from accounts.admin import UserAdmin
from accounts.models import User

from tests.base_test_mixins import AdminTestMixin


class AccountsAdminTest(AdminTestMixin, TestCase):

    @classmethod
    def setUpTestData(cls):  # noqa
        super(AccountsAdminTest, cls).setUpTestData()

        cls.user_change_list_url = cls.get_admin_change_list_view_url()
        cls.superuser_change_url = (
            cls.get_admin_change_view_url(args=(cls.superuser.pk,)))
        cls.instructor1_change_url = (
            cls.get_admin_change_view_url(args=(cls.instructor1.pk,)))
        cls.student1_change_url = (
            cls.get_admin_change_view_url(
                args=(cls.course1_student_participation.user.pk,)))
        cls.student2_change_url = (
            cls.get_admin_change_view_url(
                args=(cls.course1_student_participation2.user.pk,)))

    @classmethod
    def get_admin_change_list_view_url(cls):
        return super(AccountsAdminTest, cls).get_admin_change_list_view_url(
            app_name="accounts", model_name="user")

    @classmethod
    def get_admin_change_view_url(cls, args=None):
        return super(AccountsAdminTest, cls).get_admin_change_view_url(
            app_name="accounts", model_name="user", args=args)

    def setUp(self):
        super(AccountsAdminTest, self).setUp()
        self.superuser.refresh_from_db()
        self.rf = RequestFactory()

    @skipIf(six.PY2, "PY2 doesn't support subTest")
    def test_change_view(self):

        with self.subTest("superuser admin change/changelist for "
                          "accounts.user"):
            with self.temporarily_switch_to_user(self.superuser):
                # list view
                resp = self.c.get(self.user_change_list_url)
                self.assertEqual(resp.status_code, 200)

                # change view
                resp = self.c.get(self.superuser_change_url)
                self.assertEqual(resp.status_code, 200)

                resp = self.c.get(self.instructor1_change_url)
                self.assertEqual(resp.status_code, 200)

        with self.subTest("staff 1 admin change/changelist for "
                          "accounts.user"):
            with self.temporarily_switch_to_user(self.instructor1):
                resp = self.c.get(self.user_change_list_url)
                self.assertEqual(resp.status_code, 200)

                resp = self.c.get(self.superuser_change_url)
                self.assertEqual(resp.status_code, 302)

                resp = self.c.get(self.instructor1_change_url)
                self.assertEqual(resp.status_code, 200)

                resp = self.c.get(self.student2_change_url)
                self.assertEqual(resp.status_code, 200)

                # because that student joined 2 courses
                resp = self.c.get(self.student1_change_url)
                self.assertEqual(resp.status_code, 302)

        with self.subTest("staff 2 admin change/changelist for "
                          "accounts.user"):
            with self.temporarily_switch_to_user(self.instructor2):
                resp = self.c.get(self.user_change_list_url)
                self.assertEqual(resp.status_code, 200)

                resp = self.c.get(self.superuser_change_url)
                self.assertEqual(resp.status_code, 302)

                # Because instructor 1 is also a staff
                resp = self.c.get(self.instructor1_change_url)
                self.assertEqual(resp.status_code, 302)

                # because that student joined 2 courses
                resp = self.c.get(self.student1_change_url)
                self.assertEqual(resp.status_code, 302)

                # because that student didn't join this course
                resp = self.c.get(self.student2_change_url)
                self.assertEqual(resp.status_code, 302)

    def test_admin_add_user(self):
        # This is to make sure admin can add user without email.
        # Make sure https://github.com/inducer/relate/issues/447 is fixed
        with self.temporarily_switch_to_user(self.instructor1):
            user_count = get_user_model().objects.count()
            resp = self.c.post(reverse('admin:accounts_user_add'), {
                'username': 'newuser',
                'password1': 'newpassword',
                'password2': 'newpassword',
            })
            new_user = get_user_model().objects.get(username='newuser')
            self.assertRedirects(resp, reverse('admin:accounts_user_change',
                                                   args=(new_user.pk,)))
            self.assertEqual(get_user_model().objects.count(), user_count + 1)
            self.assertTrue(new_user.has_usable_password())

    @skipIf(six.PY2, "PY2 doesn't support subTest")
    def test_admin_user_change_fieldsets(self):
        # This test is using request factory
        change_url = reverse('admin:accounts_user_change',
                    args=(self.course1_student_participation3.user.pk,))

        common_fields = (
            "username",
            "password",
            "status",
            "first_name",
            "last_name",
            "name_verified",
            "email",
            "institutional_id",
            "institutional_id_verified",
            "editor_mode",
            "last_login",
            "date_joined",
        )

        superuser_only_fields = (
            "is_active",
            "is_staff",
            "is_superuser",
            "groups",
            "user_permissions",
        )

        test_dicts = [{"user": self.superuser,
                       "see_common_fields": True,
                       "see_superuser_only_fields": True},
                      {"user": self.instructor1,
                       "see_common_fields": True,
                       "see_superuser_only_fields": False}]

        for td in test_dicts:
            with self.subTest(user=td["user"]):
                with self.temporarily_switch_to_user(td["user"]):
                    resp = self.c.get(change_url)
                    self.assertEqual(resp.status_code, 200)
                    field_names = self.get_admin_form_fields_names(resp)

                    for f in common_fields:
                        self.assertEqual(
                            td["see_common_fields"], f in field_names,
                            "'%s' unexpectedly %s SHOWN in %s"
                            % (f,
                               "NOT" if td["see_superuser_only_fields"]
                               else "",
                               repr(field_names))
                        )
                    for f in superuser_only_fields:
                        self.assertEqual(
                            td["see_superuser_only_fields"], f in field_names,
                            "'%s' unexpectedly %s SHOWN in %s"
                            % (f,
                              "NOT" if td["see_superuser_only_fields"]
                              else "",
                              repr(field_names)))

    def test_list_display_is_staff_field(self):
        modeladmin = UserAdmin(User, site)
        request = self.rf.get(self.user_change_list_url, {})
        request.user = self.superuser
        list_display = modeladmin.get_list_display(request)
        self.assertIn("is_staff", list_display)

        # ensure "is_staff" not present in list_display of staff view
        request.user = self.instructor1
        list_display = modeladmin.get_list_display(request)
        self.assertNotIn("is_staff", list_display)

    def test_list_filter_is_staff_field(self):
        modeladmin = UserAdmin(User, site)
        request = self.rf.get(self.user_change_list_url, {})
        request.user = self.superuser
        list_filter = modeladmin.get_list_filter(request)
        self.assertIn("is_staff", list_filter)

        # ensure "is_staff" not present in list_filter of staff view
        request.user = self.instructor1
        list_filter = modeladmin.get_list_filter(request)
        self.assertNotIn("is_staff", list_filter)

    def test_list_editable_is_staff_field(self):
        # ensuer "is_staff" not present in list_editable
        # notice that, list_editable must be a subset of list_display,
        # or it will raise an check error.
        modeladmin = UserAdmin(User, site)
        request = self.rf.get(self.user_change_list_url, {})
        request.user = self.superuser

        changelist = self.get_changelist(request, User, modeladmin)
        self.assertNotIn("is_staff", changelist.list_editable)

        request.user = self.instructor1
        changelist = self.get_changelist(request, User, modeladmin)
        self.assertNotIn("is_staff", changelist.list_editable)

    def test_list_filter_queryset_filter(self):
        """
        A list filter that filters the queryset by default gives the correct
        full_result_count.
        """
        total_user_count = User.objects.count()
        modeladmin = UserAdmin(User, site)

        # {{{ not filtered
        request = self.rf.get(self.user_change_list_url, {})
        request.user = self.superuser
        changelist = self.get_changelist(request, User, modeladmin)

        changelist.get_results(request)
        self.assertEqual(changelist.full_result_count, total_user_count)

        filterspec_list = self.get_filterspec_list(request, changelist)
        self.assertIn(('All', self.course1.identifier, self.course2.identifier),
                      filterspec_list)

        request = self.rf.get(self.user_change_list_url, {})
        request.user = self.instructor1
        changelist = self.get_changelist(request, User, modeladmin)
        changelist.get_results(request)
        filterspec_list = self.get_filterspec_list(request, changelist)

        # 2 users created in setUp 'testuser_001', 'testuser_000',
        # 4 non-participation users 'test_user4', 'test_user3', 'test_user2',
        # 'test_user1',
        # 1 instructor 'test_instructor' (request.user)
        self.assertEqual(changelist.full_result_count, 7)

        queryset = changelist.get_queryset(request)
        self.assertIn(self.instructor1, queryset)

        # Besides 'test_admin' (superuser),  'test_ta' (who is also a staff)
        # and 'test_student' (who attend two courses) were not included
        self.assertNotIn(self.superuser, queryset)
        self.assertNotIn(self.course1_student_participation.user, queryset)
        self.assertNotIn(self.instructor2, queryset)

        # Although instructor 1 attended course2, the list_filter did not have that
        # choice, because he/she has no view_admin_interface pperm in that course
        self.assertIn(('All', self.course1.identifier), filterspec_list)

        # }}}

        # {{{ filtered by course 1

        request = self.rf.get(self.user_change_list_url,
                              {"course__identifier": self.course1.identifier})
        request.user = self.superuser
        changelist = self.get_changelist(request, User, modeladmin)

        queryset = changelist.get_queryset(request)
        self.assertEqual(
            queryset.count(),
            Participation.objects.filter(
                course__identifier=self.course1.identifier).count())

        request = self.rf.get(self.user_change_list_url,
                              {"course__identifier": self.course1.identifier})
        request.user = self.instructor1
        changelist = self.get_changelist(request, User, modeladmin)
        queryset = changelist.get_queryset(request)

        # 2 users created in setUp 'testuser_001', 'testuser_000',
        # 1 instructor 'test_instructor'
        self.assertEqual(queryset.count(), 3)

        # }}}

    def get_user_data(self, user):
        if not user.last_login:
            user.last_login = now()
        if not user.date_joined:
            user.date_joined = now()
        return {
            'username': user.username,
            'password': user.password,
            'email': user.email,
            'is_active': user.is_active,
            'is_staff': user.is_staff,
            'is_superuser': user.is_superuser,
            'last_login_0': user.last_login.strftime('%Y-%m-%d'),
            'last_login_1': user.last_login.strftime('%H:%M:%S'),
            'initial-last_login_0': user.last_login.strftime('%Y-%m-%d'),
            'initial-last_login_1': user.last_login.strftime('%H:%M:%S'),
            'date_joined_0': user.date_joined.strftime('%Y-%m-%d'),
            'date_joined_1': user.date_joined.strftime('%H:%M:%S'),
            'initial-date_joined_0': user.date_joined.strftime('%Y-%m-%d'),
            'initial-date_joined_1': user.date_joined.strftime('%H:%M:%S'),
            'first_name': user.first_name,
            'last_name': user.last_name,
            'editor_mode': user.editor_mode,
            'status': user.status
        }

    def test_set_superuser_and_staff_by_superuser(self):
        user = self.course1_student_participation2.user
        with self.temporarily_switch_to_user(self.superuser):
            staff_count = User.objects.filter(is_staff=True).count()
            superuser_count = User.objects.filter(is_superuser=True).count()
            data = self.get_user_data(user)
            data["is_staff"] = True
            resp = self.c.post(self.student2_change_url, data)
            self.assertEqual(resp.status_code, 302)
            self.assertEqual(User.objects.filter(is_staff=True).count(),
                             staff_count + 1)
            row = LogEntry.objects.latest('id')
            self.assertIn("Changed", row.get_change_message())
            self.assertIn("is_staff", row.get_change_message())

            data = self.get_user_data(user)
            data["is_superuser"] = True
            self.c.post(self.student2_change_url, data)
            self.assertEqual(User.objects.filter(is_superuser=True).count(),
                             superuser_count + 1)
            row = LogEntry.objects.latest('id')
            self.assertIn("Changed", row.get_change_message())
            self.assertIn("is_superuser", row.get_change_message())

    def test_set_superuser_and_staff_by_staff(self):
        user = self.course1_student_participation2.user
        with self.temporarily_switch_to_user(self.instructor1):
            staff_count = User.objects.filter(is_staff=True).count()
            superuser_count = User.objects.filter(is_superuser=True).count()
            data = self.get_user_data(user)
            data["is_staff"] = True
            resp = self.c.post(self.student2_change_url, data)
            self.assertEqual(resp.status_code, 302)

            # non-superuser staff can't post create staff
            self.assertEqual(User.objects.filter(is_staff=True).count(),
                             staff_count)
            row = LogEntry.objects.latest('id')
            self.assertNotIn("is_staff", row.get_change_message())

            data = self.get_user_data(user)
            data["is_superuser"] = True
            self.c.post(self.student2_change_url, data)

            # non-superuser staff can't post create superuser
            self.assertEqual(User.objects.filter(is_superuser=True).count(),
                             superuser_count)
            row = LogEntry.objects.latest('id')
            self.assertNotIn("is_superuser", row.get_change_message())

    def test_add_permissions_by_superuser(self):
        user = self.course1_student_participation2.user
        with self.temporarily_switch_to_user(self.superuser):
            data = self.get_user_data(user)
            # add a permission in post data
            data["user_permissions"] = [1, ]

            self.c.post(self.student2_change_url, data)

            row = LogEntry.objects.latest('id')
            self.assertIn("Changed", row.get_change_message())
            self.assertIn("user_permissions",  row.get_change_message())

    def test_add_permissions_by_staff(self):
        user = self.course1_student_participation2.user
        with self.temporarily_switch_to_user(self.instructor1):
            data = self.get_user_data(user)
            # try to add a permission in post data
            data["user_permissions"] = [1, ]

            self.c.post(self.student2_change_url, data)

            row = LogEntry.objects.latest('id')
            self.assertIn("Changed", row.get_change_message())

            # no change was made to user_permissions
            self.assertNotIn("user_permissions", row.get_change_message())

# vim: foldmethod=marker