test_views.py 47.4 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-
"""Tests for the teams API at the HTTP request level."""
import json
4 5 6
import pytz
from datetime import datetime
from dateutil import parser
7 8 9
import ddt

from django.core.urlresolvers import reverse
10
from django.conf import settings
11
from django.db.models.signals import post_save
Diana Huang committed
12
from nose.plugins.attrib import attr
13 14 15
from rest_framework.test import APITestCase, APIClient

from courseware.tests.factories import StaffFactory
16
from common.test.utils import skip_signal
17 18
from student.tests.factories import UserFactory, AdminFactory, CourseEnrollmentFactory
from student.models import CourseEnrollment
19
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
Diana Huang committed
20
from xmodule.modulestore.tests.factories import CourseFactory
21
from .factories import CourseTeamFactory, LAST_ACTIVITY_AT
22
from ..search_indexes import CourseTeamIndexer, CourseTeam, course_team_post_save_callback
Diana Huang committed
23

24 25 26
from django_comment_common.models import Role, FORUM_ROLE_COMMUNITY_TA
from django_comment_common.utils import seed_permissions_roles

Diana Huang committed
27 28

@attr('shard_1')
29
class TestDashboard(SharedModuleStoreTestCase):
30
    """Tests for the Teams dashboard."""
Diana Huang committed
31 32
    test_password = "test"

33 34 35 36 37 38 39
    @classmethod
    def setUpClass(cls):
        super(TestDashboard, cls).setUpClass()
        cls.course = CourseFactory.create(
            teams_configuration={"max_team_size": 10, "topics": [{"name": "foo", "id": 0, "description": "test topic"}]}
        )

Diana Huang committed
40 41 42 43 44 45 46 47 48 49
    def setUp(self):
        """
        Set up tests
        """
        super(TestDashboard, self).setUp()
        # will be assigned to self.client by default
        self.user = UserFactory.create(password=self.test_password)
        self.teams_url = reverse('teams_dashboard', args=[self.course.id])

    def test_anonymous(self):
50 51
        """Verifies that an anonymous client cannot access the team
        dashboard, and is redirected to the login page."""
Diana Huang committed
52 53
        anonymous_client = APIClient()
        response = anonymous_client.get(self.teams_url)
54 55
        redirect_url = '{0}?next={1}'.format(settings.LOGIN_URL, self.teams_url)
        self.assertRedirects(response, redirect_url)
Diana Huang committed
56 57 58

    def test_not_enrolled_not_staff(self):
        """ Verifies that a student who is not enrolled cannot access the team dashboard. """
59
        self.client.login(username=self.user.username, password=self.test_password)
Diana Huang committed
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
        response = self.client.get(self.teams_url)
        self.assertEqual(404, response.status_code)

    def test_not_enrolled_staff(self):
        """
        Verifies that a user with global access who is not enrolled in the course can access the team dashboard.
        """
        staff_user = UserFactory(is_staff=True, password=self.test_password)
        staff_client = APIClient()
        staff_client.login(username=staff_user.username, password=self.test_password)
        response = staff_client.get(self.teams_url)
        self.assertContains(response, "TeamsTabFactory", status_code=200)

    def test_enrolled_not_staff(self):
        """
        Verifies that a user without global access who is enrolled in the course can access the team dashboard.
        """
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
        self.client.login(username=self.user.username, password=self.test_password)
        response = self.client.get(self.teams_url)
        self.assertContains(response, "TeamsTabFactory", status_code=200)

    def test_enrolled_teams_not_enabled(self):
        """
        Verifies that a user without global access who is enrolled in the course cannot access the team dashboard
        if the teams feature is not enabled.
        """
        course = CourseFactory.create()
        teams_url = reverse('teams_dashboard', args=[course.id])
        CourseEnrollmentFactory.create(user=self.user, course_id=course.id)
        self.client.login(username=self.user.username, password=self.test_password)
        response = self.client.get(teams_url)
        self.assertEqual(404, response.status_code)

    def test_bad_course_id(self):
        """
        Verifies expected behavior when course_id does not reference an existing course or is invalid.
        """
        bad_org = "badorgxxx"
        bad_team_url = self.teams_url.replace(self.course.id.org, bad_org)
100 101
        CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id)
        self.client.login(username=self.user.username, password=self.test_password)
Diana Huang committed
102 103 104 105 106 107
        response = self.client.get(bad_team_url)
        self.assertEqual(404, response.status_code)

        bad_team_url = bad_team_url.replace(bad_org, "invalid/course/id")
        response = self.client.get(bad_team_url)
        self.assertEqual(404, response.status_code)
108 109


110
class TeamAPITestCase(APITestCase, SharedModuleStoreTestCase):
111 112 113 114
    """Base class for Team API test cases."""

    test_password = 'password'

115 116 117
    @classmethod
    def setUpClass(cls):
        super(TeamAPITestCase, cls).setUpClass()
118
        teams_configuration_1 = {
119 120 121 122 123 124 125 126 127
            'topics':
            [
                {
                    'id': 'topic_{}'.format(i),
                    'name': name,
                    'description': 'Description for topic {}.'.format(i)
                } for i, name in enumerate([u'sólar power', 'Wind Power', 'Nuclear Power', 'Coal Power'])
            ]
        }
128
        cls.test_course_1 = CourseFactory.create(
129 130 131
            org='TestX',
            course='TS101',
            display_name='Test Course',
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
            teams_configuration=teams_configuration_1
        )

        teams_configuration_2 = {
            'topics':
            [
                {
                    'id': 'topic_5',
                    'name': 'Other Interests',
                    'description': 'Description for topic 5.'
                },
                {
                    'id': 'topic_6',
                    'name': 'Public Profiles',
                    'description': 'Description for topic 6.'
                },
148 149
            ],
            'max_team_size': 1
150 151 152 153 154 155
        }
        cls.test_course_2 = CourseFactory.create(
            org='MIT',
            course='6.002x',
            display_name='Circuits',
            teams_configuration=teams_configuration_2
156 157
        )

158 159 160
    def setUp(self):
        super(TeamAPITestCase, self).setUp()
        self.topics_count = 4
161 162 163 164
        self.users = {
            'staff': AdminFactory.create(password=self.test_password),
            'course_staff': StaffFactory.create(course_key=self.test_course_1.id, password=self.test_password)
        }
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        self.create_and_enroll_student(username='student_enrolled')
        self.create_and_enroll_student(username='student_enrolled_not_on_team')
        self.create_and_enroll_student(username='student_unenrolled', courses=[])

        # Make this student a community TA.
        self.create_and_enroll_student(username='community_ta')
        seed_permissions_roles(self.test_course_1.id)
        community_ta_role = Role.objects.get(name=FORUM_ROLE_COMMUNITY_TA, course_id=self.test_course_1.id)
        community_ta_role.users.add(self.users['community_ta'])

        # This student is enrolled in both test courses and is a member of a team in each course, but is not on the
        # same team as student_enrolled.
        self.create_and_enroll_student(
            courses=[self.test_course_1, self.test_course_2],
            username='student_enrolled_both_courses_other_team'
        )

182 183 184 185 186 187 188 189 190
        # Make this student have a public profile
        self.create_and_enroll_student(
            courses=[self.test_course_2],
            username='student_enrolled_public_profile'
        )
        profile = self.users['student_enrolled_public_profile'].profile
        profile.year_of_birth = 1970
        profile.save()

191 192 193 194 195 196 197
        # This student is enrolled in the other course, but not yet a member of a team. This is to allow
        # course_2 to use a max_team_size of 1 without breaking other tests on course_1
        self.create_and_enroll_student(
            courses=[self.test_course_2],
            username='student_enrolled_other_course_not_on_team'
        )

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
        with skip_signal(
            post_save,
            receiver=course_team_post_save_callback,
            sender=CourseTeam,
            dispatch_uid='teams.signals.course_team_post_save_callback'
        ):
            # 'solar team' is intentionally lower case to test case insensitivity in name ordering
            self.test_team_1 = CourseTeamFactory.create(
                name=u'sólar team',
                course_id=self.test_course_1.id,
                topic_id='topic_0'
            )
            self.test_team_2 = CourseTeamFactory.create(name='Wind Team', course_id=self.test_course_1.id)
            self.test_team_3 = CourseTeamFactory.create(name='Nuclear Team', course_id=self.test_course_1.id)
            self.test_team_4 = CourseTeamFactory.create(
                name='Coal Team',
                course_id=self.test_course_1.id,
                is_active=False
            )
            self.test_team_5 = CourseTeamFactory.create(name='Another Team', course_id=self.test_course_2.id)
            self.test_team_6 = CourseTeamFactory.create(
                name='Public Profile Team',
                course_id=self.test_course_2.id,
                topic_id='topic_6'
            )
            self.test_team_7 = CourseTeamFactory.create(
                name='Search',
                description='queryable text',
                country='GS',
                language='to',
                course_id=self.test_course_2.id,
                topic_id='topic_7'
            )
231

232 233 234 235 236 237
        self.test_team_name_id_map = {team.name: team for team in (
            self.test_team_1,
            self.test_team_2,
            self.test_team_3,
            self.test_team_4,
            self.test_team_5,
238 239
            self.test_team_6,
            self.test_team_7,
240 241
        )}

242
        for user, course in [('staff', self.test_course_1), ('course_staff', self.test_course_1)]:
243 244 245
            CourseEnrollment.enroll(
                self.users[user], course.id, check_access=True
            )
246

247 248
        self.test_team_1.add_user(self.users['student_enrolled'])
        self.test_team_3.add_user(self.users['student_enrolled_both_courses_other_team'])
249
        self.test_team_5.add_user(self.users['student_enrolled_both_courses_other_team'])
250
        self.test_team_6.add_user(self.users['student_enrolled_public_profile'])
251

252 253 254 255 256 257 258 259
    def build_membership_data_raw(self, username, team):
        """Assembles a membership creation payload based on the raw values provided."""
        return {'username': username, 'team_id': team}

    def build_membership_data(self, username, team):
        """Assembles a membership creation payload based on the username and team model provided."""
        return self.build_membership_data_raw(self.users[username].username, team.team_id)

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    def create_and_enroll_student(self, courses=None, username=None):
        """ Creates a new student and enrolls that student in the course.

        Adds the new user to the self.users dictionary with the username as the key.

        Returns the username once the user has been created.
        """
        if username is not None:
            user = UserFactory.create(password=self.test_password, username=username)
        else:
            user = UserFactory.create(password=self.test_password)
        courses = courses if courses is not None else [self.test_course_1]
        for course in courses:
            CourseEnrollment.enroll(user, course.id, check_access=True)
        self.users[user.username] = user

        return user.username

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    def login(self, user):
        """Given a user string, logs the given user in.

        Used for testing with ddt, which does not have access to self in
        decorators. If user is 'student_inactive', then an inactive user will
        be both created and logged in.
        """
        if user == 'student_inactive':
            student_inactive = UserFactory.create(password=self.test_password)
            self.client.login(username=student_inactive.username, password=self.test_password)
            student_inactive.is_active = False
            student_inactive.save()
        else:
            self.client.login(username=self.users[user].username, password=self.test_password)

    def make_call(self, url, expected_status=200, method='get', data=None, content_type=None, **kwargs):
        """Makes a call to the Team API at the given url with method and data.

        If a user is specified in kwargs, that user is first logged in.
        """
298
        user = kwargs.pop('user', 'student_enrolled_not_on_team')
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
        if user:
            self.login(user)
        func = getattr(self.client, method)
        if content_type:
            response = func(url, data=data, content_type=content_type)
        else:
            response = func(url, data=data)
        self.assertEqual(expected_status, response.status_code)
        if expected_status == 200:
            return json.loads(response.content)
        else:
            return response

    def get_teams_list(self, expected_status=200, data=None, no_course_id=False, **kwargs):
        """Gets the list of teams as the given user with data as query params. Verifies expected_status."""
        data = data if data else {}
        if 'course_id' not in data and not no_course_id:
            data.update({'course_id': self.test_course_1.id})
        return self.make_call(reverse('teams_list'), expected_status, 'get', data, **kwargs)

    def build_team_data(self, name="Test team", course=None, description="Filler description", **kwargs):
        """Creates the payload for creating a team. kwargs can be used to specify additional fields."""
        data = kwargs
        course = course if course else self.test_course_1
        data.update({
            'name': name,
            'course_id': str(course.id),
            'description': description,
        })
        return data

    def post_create_team(self, expected_status=200, data=None, **kwargs):
        """Posts data to the team creation endpoint. Verifies expected_status."""
        return self.make_call(reverse('teams_list'), expected_status, 'post', data, **kwargs)

334
    def get_team_detail(self, team_id, expected_status=200, data=None, **kwargs):
335
        """Gets detailed team information for team_id. Verifies expected_status."""
336
        return self.make_call(reverse('teams_detail', args=[team_id]), expected_status, 'get', data, **kwargs)
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

    def patch_team_detail(self, team_id, expected_status, data=None, **kwargs):
        """Patches the team with team_id using data. Verifies expected_status."""
        return self.make_call(
            reverse('teams_detail', args=[team_id]),
            expected_status,
            'patch',
            json.dumps(data) if data else None,
            'application/merge-patch+json',
            **kwargs
        )

    def get_topics_list(self, expected_status=200, data=None, **kwargs):
        """Gets the list of topics, passing data as query params. Verifies expected_status."""
        return self.make_call(reverse('topics_list'), expected_status, 'get', data, **kwargs)

    def get_topic_detail(self, topic_id, course_id, expected_status=200, data=None, **kwargs):
        """Gets a single topic, passing data as query params. Verifies expected_status."""
        return self.make_call(
            reverse('topics_detail', kwargs={'topic_id': topic_id, 'course_id': str(course_id)}),
            expected_status,
            'get',
            data,
            **kwargs
        )

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
    def get_membership_list(self, expected_status=200, data=None, **kwargs):
        """Gets the membership list, passing data as query params. Verifies expected_status."""
        return self.make_call(reverse('team_membership_list'), expected_status, 'get', data, **kwargs)

    def post_create_membership(self, expected_status=200, data=None, **kwargs):
        """Posts data to the membership creation endpoint. Verifies expected_status."""
        return self.make_call(reverse('team_membership_list'), expected_status, 'post', data, **kwargs)

    def get_membership_detail(self, team_id, username, expected_status=200, data=None, **kwargs):
        """Gets an individual membership record, passing data as query params. Verifies expected_status."""
        return self.make_call(
            reverse('team_membership_detail', args=[team_id, username]),
            expected_status,
            'get',
            data,
            **kwargs
        )

    def delete_membership(self, team_id, username, expected_status=200, **kwargs):
        """Deletes an individual membership record. Verifies expected_status."""
        return self.make_call(
            reverse('team_membership_detail', args=[team_id, username]),
            expected_status,
            'delete',
            **kwargs
        )

390
    def verify_expanded_public_user(self, user):
391
        """Verifies that fields exist on the returned user json indicating that it is expanded."""
392
        for field in ['username', 'url', 'bio', 'country', 'profile_image', 'time_zone', 'language_proficiencies']:
393 394
            self.assertIn(field, user)

395 396 397 398 399 400 401
    def verify_expanded_private_user(self, user):
        """Verifies that fields exist on the returned user json indicating that it is expanded."""
        for field in ['username', 'url', 'profile_image']:
            self.assertIn(field, user)
        for field in ['bio', 'country', 'time_zone', 'language_proficiencies']:
            self.assertNotIn(field, user)

402 403 404 405 406
    def verify_expanded_team(self, team):
        """Verifies that fields exist on the returned team json indicating that it is expanded."""
        for field in ['id', 'name', 'is_active', 'course_id', 'topic_id', 'date_created', 'description']:
            self.assertIn(field, team)

407 408 409 410 411 412

@ddt.ddt
class TestListTeamsAPI(TeamAPITestCase):
    """Test cases for the team listing API endpoint."""

    @ddt.data(
413 414
        (None, 401),
        ('student_inactive', 401),
415 416 417 418
        ('student_unenrolled', 403),
        ('student_enrolled', 200),
        ('staff', 200),
        ('course_staff', 200),
419
        ('community_ta', 200),
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    )
    @ddt.unpack
    def test_access(self, user, status):
        teams = self.get_teams_list(user=user, expected_status=status)
        if status == 200:
            self.assertEqual(3, teams['count'])

    def test_missing_course_id(self):
        self.get_teams_list(400, no_course_id=True)

    def verify_names(self, data, status, names=None, **kwargs):
        """Gets a team listing with data as query params, verifies status, and then verifies team names if specified."""
        teams = self.get_teams_list(data=data, expected_status=status, **kwargs)
        if names:
            self.assertEqual(names, [team['name'] for team in teams['results']])

    def test_filter_invalid_course_id(self):
437
        self.verify_names({'course_id': 'no_such_course'}, 400)
438 439

    def test_filter_course_id(self):
440 441 442
        self.verify_names(
            {'course_id': self.test_course_2.id},
            200,
443
            ['Another Team', 'Public Profile Team', 'Search'],
444 445
            user='staff'
        )
446 447

    def test_filter_topic_id(self):
448
        self.verify_names({'course_id': self.test_course_1.id, 'topic_id': 'topic_0'}, 200, [u'sólar team'])
449 450 451 452 453 454 455

    def test_filter_include_inactive(self):
        self.verify_names({'include_inactive': True}, 200, ['Coal Team', 'Nuclear Team', u'sólar team', 'Wind Team'])

    @ddt.data(
        (None, 200, ['Nuclear Team', u'sólar team', 'Wind Team']),
        ('name', 200, ['Nuclear Team', u'sólar team', 'Wind Team']),
456 457 458 459 460 461
        # Note that "Nuclear Team" and "solar team" have the same open_slots.
        # "solar team" comes first due to secondary sort by last_activity_at.
        ('open_slots', 200, ['Wind Team', u'sólar team', 'Nuclear Team']),
        # Note that "Wind Team" and "Nuclear Team" have the same last_activity_at.
        # "Wind Team" comes first due to secondary sort by open_slots.
        ('last_activity_at', 200, [u'sólar team', 'Wind Team', 'Nuclear Team']),
462 463 464
    )
    @ddt.unpack
    def test_order_by(self, field, status, names):
465 466 467
        # Make "solar team" the most recently active team.
        # The CourseTeamFactory sets the last_activity_at to a fixed time (in the past), so all of the
        # other teams have the same last_activity_at.
468 469 470 471 472 473 474 475 476
        with skip_signal(
            post_save,
            receiver=course_team_post_save_callback,
            sender=CourseTeam,
            dispatch_uid='teams.signals.course_team_post_save_callback'
        ):
            solar_team = self.test_team_name_id_map[u'sólar team']
            solar_team.last_activity_at = datetime.utcnow().replace(tzinfo=pytz.utc)
            solar_team.save()
477

478 479 480
        data = {'order_by': field} if field else {}
        self.verify_names(data, status, names)

481 482 483 484
    def test_order_by_with_text_search(self):
        data = {'order_by': 'name', 'text_search': 'search'}
        self.verify_names(data, 400, [])

485 486 487 488
    @ddt.data((404, {'course_id': 'no/such/course'}), (400, {'topic_id': 'no_such_topic'}))
    @ddt.unpack
    def test_no_results(self, status, data):
        self.get_teams_list(status, data)
489 490 491 492 493 494 495 496 497 498 499

    def test_page_size(self):
        result = self.get_teams_list(200, {'page_size': 2})
        self.assertEquals(2, result['num_pages'])

    def test_page(self):
        result = self.get_teams_list(200, {'page_size': 1, 'page': 3})
        self.assertEquals(3, result['num_pages'])
        self.assertIsNone(result['next'])
        self.assertIsNotNone(result['previous'])

500 501
    def test_expand_private_user(self):
        # Use the default user which is already private because to year_of_birth is set
502
        result = self.get_teams_list(200, {'expand': 'user', 'topic_id': 'topic_0'})
503 504 505 506 507 508 509 510 511 512 513 514 515
        self.verify_expanded_private_user(result['results'][0]['membership'][0]['user'])

    def test_expand_public_user(self):
        result = self.get_teams_list(
            200,
            {
                'expand': 'user',
                'topic_id': 'topic_6',
                'course_id': self.test_course_2.id
            },
            user='student_enrolled_public_profile'
        )
        self.verify_expanded_public_user(result['results'][0]['membership'][0]['user'])
516

517 518 519 520 521 522 523 524 525 526
    @ddt.data(
        ('search', ['Search']),
        ('queryable', ['Search']),
        ('Tonga', ['Search']),
        ('Island', ['Search']),
        ('search queryable', []),
        ('team', ['Another Team', 'Public Profile Team']),
    )
    @ddt.unpack
    def test_text_search(self, text_search, expected_team_names):
527 528 529 530 531 532
        # clear out the teams search index before reindexing
        CourseTeamIndexer.engine().destroy()

        for team in self.test_team_name_id_map.values():
            CourseTeamIndexer.index(team)

533 534 535 536 537 538 539
        self.verify_names(
            {'course_id': self.test_course_2.id, 'text_search': text_search},
            200,
            expected_team_names,
            user='student_enrolled_public_profile'
        )

540 541 542 543 544 545

@ddt.ddt
class TestCreateTeamAPI(TeamAPITestCase):
    """Test cases for the team creation endpoint."""

    @ddt.data(
546 547
        (None, 401),
        ('student_inactive', 401),
548
        ('student_unenrolled', 403),
549
        ('student_enrolled_not_on_team', 200),
550
        ('staff', 200),
551 552
        ('course_staff', 200),
        ('community_ta', 200),
553 554 555 556 557
    )
    @ddt.unpack
    def test_access(self, user, status):
        team = self.post_create_team(status, self.build_team_data(name="New Team"), user=user)
        if status == 200:
558
            self.verify_expected_team_id(team, 'new-team')
559 560 561
            teams = self.get_teams_list(user=user)
            self.assertIn("New Team", [team['name'] for team in teams['results']])

562 563 564 565 566 567
    def verify_expected_team_id(self, team, expected_prefix):
        """ Verifies that the team id starts with the specified prefix and ends with the discussion_topic_id """
        self.assertIn('id', team)
        self.assertIn('discussion_topic_id', team)
        self.assertEqual(team['id'], expected_prefix + '-' + team['discussion_topic_id'])

568 569
    def test_naming(self):
        new_teams = [
570
            self.post_create_team(data=self.build_team_data(name=name), user=self.create_and_enroll_student())
571
            for name in ["The Best Team", "The Best Team", "A really long team name"]
572
        ]
573 574 575 576 577 578 579
        # Check that teams with the same name have unique IDs.
        self.verify_expected_team_id(new_teams[0], 'the-best-team')
        self.verify_expected_team_id(new_teams[1], 'the-best-team')
        self.assertNotEqual(new_teams[0]['id'], new_teams[1]['id'])

        # Verify expected truncation behavior with names > 20 characters.
        self.verify_expected_team_id(new_teams[2], 'a-really-long-team-n')
580 581

    @ddt.data((400, {
582
        'name': 'Bad Course ID',
583
        'course_id': 'no_such_course',
584 585
        'description': "Filler Description"
    }), (404, {
586
        'name': "Non-existent course ID",
587
        'course_id': 'no/such/course',
588 589 590 591 592 593
        'description': "Filler Description"
    }))
    @ddt.unpack
    def test_bad_course_data(self, status, data):
        self.post_create_team(status, data)

594
    def test_student_in_team(self):
595
        response = self.post_create_team(
596
            400,
597 598 599 600 601
            data=self.build_team_data(
                name="Doomed team",
                course=self.test_course_1,
                description="Overly ambitious student"
            ),
602 603
            user='student_enrolled'
        )
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        self.assertEqual(
            "You are already in a team in this course.",
            json.loads(response.content)["user_message"]
        )

    @ddt.data('staff', 'course_staff', 'community_ta')
    def test_privileged_create_multiple_teams(self, user):
        """ Privileged users can create multiple teams, even if they are already in one. """
        # First add the privileged user to a team.
        self.post_create_membership(
            200,
            self.build_membership_data(user, self.test_team_1),
            user=user
        )

        self.post_create_team(
            data=self.build_team_data(
                name="Another team",
                course=self.test_course_1,
                description="Privileged users are the best"
            ),
            user=user
        )
627 628 629 630 631

    @ddt.data({'description': ''}, {'name': 'x' * 1000}, {'name': ''})
    def test_bad_fields(self, kwargs):
        self.post_create_team(400, self.build_team_data(**kwargs))

632 633 634 635 636 637
    def test_missing_name(self):
        self.post_create_team(400, {
            'course_id': str(self.test_course_1.id),
            'description': "foobar"
        })

638 639
    def test_full_student_creator(self):
        creator = self.create_and_enroll_student()
640 641 642 643 644 645 646
        team = self.post_create_team(data=self.build_team_data(
            name="Fully specified team",
            course=self.test_course_1,
            description="Another fantastic team",
            topic_id='great-topic',
            country='CA',
            language='fr'
647
        ), user=creator)
648

649 650 651 652
        # Verify the id (it ends with a unique hash, which is the same as the discussion_id).
        self.verify_expected_team_id(team, 'fully-specified-team')
        del team['id']

653
        # Remove date_created and discussion_topic_id because they change between test runs
654
        del team['date_created']
655
        del team['discussion_topic_id']
656 657 658 659 660

        # Since membership is its own list, we want to examine this separately.
        team_membership = team['membership']
        del team['membership']

661 662 663 664 665 666 667
        # verify that it's been set to a time today.
        self.assertEqual(
            parser.parse(team['last_activity_at']).date(),
            datetime.utcnow().replace(tzinfo=pytz.utc).date()
        )
        del team['last_activity_at']

668 669 670
        # Verify that the creating user gets added to the team.
        self.assertEqual(len(team_membership), 1)
        member = team_membership[0]['user']
671
        self.assertEqual(member['username'], creator)
672 673

        self.assertEqual(team, {
674 675 676 677 678 679 680 681 682
            'name': 'Fully specified team',
            'language': 'fr',
            'country': 'CA',
            'is_active': True,
            'topic_id': 'great-topic',
            'course_id': str(self.test_course_1.id),
            'description': 'Another fantastic team'
        })

683 684 685 686 687 688 689 690 691 692 693 694
    @ddt.data('staff', 'course_staff', 'community_ta')
    def test_membership_staff_creator(self, user):
        # Verify that staff do not automatically get added to a team
        # when they create one.
        team = self.post_create_team(data=self.build_team_data(
            name="New team",
            course=self.test_course_1,
            description="Another fantastic team",
        ), user=user)

        self.assertEqual(team['membership'], [])

695 696 697 698 699 700

@ddt.ddt
class TestDetailTeamAPI(TeamAPITestCase):
    """Test cases for the team detail endpoint."""

    @ddt.data(
701 702
        (None, 401),
        ('student_inactive', 401),
703 704 705 706
        ('student_unenrolled', 403),
        ('student_enrolled', 200),
        ('staff', 200),
        ('course_staff', 200),
707
        ('community_ta', 200),
708 709 710 711 712
    )
    @ddt.unpack
    def test_access(self, user, status):
        team = self.get_team_detail(self.test_team_1.team_id, status, user=user)
        if status == 200:
713 714
            self.assertEqual(team['description'], self.test_team_1.description)
            self.assertEqual(team['discussion_topic_id'], self.test_team_1.discussion_topic_id)
715
            self.assertEqual(parser.parse(team['last_activity_at']), LAST_ACTIVITY_AT)
716 717

    def test_does_not_exist(self):
718 719
        self.get_team_detail('no_such_team', 404)

720 721
    def test_expand_private_user(self):
        # Use the default user which is already private because to year_of_birth is set
722
        result = self.get_team_detail(self.test_team_1.team_id, 200, {'expand': 'user'})
723 724 725 726 727 728 729 730 731 732
        self.verify_expanded_private_user(result['membership'][0]['user'])

    def test_expand_public_user(self):
        result = self.get_team_detail(
            self.test_team_6.team_id,
            200,
            {'expand': 'user'},
            user='student_enrolled_public_profile'
        )
        self.verify_expanded_public_user(result['membership'][0]['user'])
733 734 735 736 737 738 739


@ddt.ddt
class TestUpdateTeamAPI(TeamAPITestCase):
    """Test cases for the team update endpoint."""

    @ddt.data(
740 741
        (None, 401),
        ('student_inactive', 401),
742 743 744 745
        ('student_unenrolled', 403),
        ('student_enrolled', 403),
        ('staff', 200),
        ('course_staff', 200),
746
        ('community_ta', 200),
747 748 749 750 751 752 753 754
    )
    @ddt.unpack
    def test_access(self, user, status):
        team = self.patch_team_detail(self.test_team_1.team_id, status, {'name': 'foo'}, user=user)
        if status == 200:
            self.assertEquals(team['name'], 'foo')

    @ddt.data(
755 756
        (None, 401),
        ('student_inactive', 401),
757 758 759 760
        ('student_unenrolled', 404),
        ('student_enrolled', 404),
        ('staff', 404),
        ('course_staff', 404),
761
        ('community_ta', 404),
762 763 764
    )
    @ddt.unpack
    def test_access_bad_id(self, user, status):
765
        self.patch_team_detail("no_such_team", status, {'name': 'foo'}, user=user)
766 767 768 769

    @ddt.data(
        ('id', 'foobar'),
        ('description', ''),
770 771
        ('country', 'no_such_country'),
        ('language', 'no_such_language')
772 773 774 775 776 777 778 779 780 781 782
    )
    @ddt.unpack
    def test_bad_requests(self, key, value):
        self.patch_team_detail(self.test_team_1.team_id, 400, {key: value}, user='staff')

    @ddt.data(('country', 'US'), ('language', 'en'), ('foo', 'bar'))
    @ddt.unpack
    def test_good_requests(self, key, value):
        self.patch_team_detail(self.test_team_1.team_id, 200, {key: value}, user='staff')

    def test_does_not_exist(self):
783
        self.patch_team_detail('no_such_team', 404, user='staff')
784 785 786 787 788 789 790


@ddt.ddt
class TestListTopicsAPI(TeamAPITestCase):
    """Test cases for the topic listing endpoint."""

    @ddt.data(
791 792
        (None, 401),
        ('student_inactive', 401),
793 794 795 796
        ('student_unenrolled', 403),
        ('student_enrolled', 200),
        ('staff', 200),
        ('course_staff', 200),
797
        ('community_ta', 200),
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
    )
    @ddt.unpack
    def test_access(self, user, status):
        topics = self.get_topics_list(status, {'course_id': self.test_course_1.id}, user=user)
        if status == 200:
            self.assertEqual(topics['count'], self.topics_count)

    @ddt.data('A+BOGUS+COURSE', 'A/BOGUS/COURSE')
    def test_invalid_course_key(self, course_id):
        self.get_topics_list(404, {'course_id': course_id})

    def test_without_course_id(self):
        self.get_topics_list(400)

    @ddt.data(
813 814
        (None, 200, ['Coal Power', 'Nuclear Power', u'sólar power', 'Wind Power'], 'name'),
        ('name', 200, ['Coal Power', 'Nuclear Power', u'sólar power', 'Wind Power'], 'name'),
815 816 817
        # Note that "Nuclear Power" and "solar power" both have 2 teams. "Coal Power" and "Window Power"
        # both have 0 teams. The secondary sort is alphabetical by name.
        ('team_count', 200, ['Nuclear Power', u'sólar power', 'Coal Power', 'Wind Power'], 'team_count'),
818
        ('no_such_field', 400, [], None),
819 820
    )
    @ddt.unpack
821
    def test_order_by(self, field, status, names, expected_ordering):
822 823 824 825 826 827 828 829 830 831 832 833 834
        with skip_signal(
            post_save,
            receiver=course_team_post_save_callback,
            sender=CourseTeam,
            dispatch_uid='teams.signals.course_team_post_save_callback'
        ):
            # Add 2 teams to "Nuclear Power", which previously had no teams.
            CourseTeamFactory.create(
                name=u'Nuclear Team 1', course_id=self.test_course_1.id, topic_id='topic_2'
            )
            CourseTeamFactory.create(
                name=u'Nuclear Team 2', course_id=self.test_course_1.id, topic_id='topic_2'
            )
835 836 837 838 839 840
        data = {'course_id': self.test_course_1.id}
        if field:
            data['order_by'] = field
        topics = self.get_topics_list(status, data)
        if status == 200:
            self.assertEqual(names, [topic['name'] for topic in topics['results']])
841
            self.assertEqual(topics['sort_order'], expected_ordering)
842

843 844 845 846 847
    def test_order_by_team_count_secondary(self):
        """
        Ensure that the secondary sort (alphabetical) when primary sort is team_count
        works across pagination boundaries.
        """
848 849 850 851 852 853 854 855 856 857 858 859 860
        with skip_signal(
            post_save,
            receiver=course_team_post_save_callback,
            sender=CourseTeam,
            dispatch_uid='teams.signals.course_team_post_save_callback'
        ):
            # Add 2 teams to "Wind Power", which previously had no teams.
            CourseTeamFactory.create(
                name=u'Wind Team 1', course_id=self.test_course_1.id, topic_id='topic_1'
            )
            CourseTeamFactory.create(
                name=u'Wind Team 2', course_id=self.test_course_1.id, topic_id='topic_1'
            )
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

        topics = self.get_topics_list(data={
            'course_id': self.test_course_1.id,
            'page_size': 2,
            'page': 1,
            'order_by': 'team_count'
        })
        self.assertEqual(["Wind Power", u'sólar power'], [topic['name'] for topic in topics['results']])

        topics = self.get_topics_list(data={
            'course_id': self.test_course_1.id,
            'page_size': 2,
            'page': 2,
            'order_by': 'team_count'
        })
        self.assertEqual(["Coal Power", "Nuclear Power"], [topic['name'] for topic in topics['results']])

878 879 880 881 882 883 884 885 886 887 888 889
    def test_pagination(self):
        response = self.get_topics_list(data={
            'course_id': self.test_course_1.id,
            'page_size': 2,
        })

        self.assertEqual(2, len(response['results']))
        self.assertIn('next', response)
        self.assertIn('previous', response)
        self.assertIsNone(response['previous'])
        self.assertIsNotNone(response['next'])

890 891 892 893
    def test_default_ordering(self):
        response = self.get_topics_list(data={'course_id': self.test_course_1.id})
        self.assertEqual(response['sort_order'], 'name')

894 895 896 897 898 899 900 901 902 903
    def test_team_count(self):
        """Test that team_count is included for each topic"""
        response = self.get_topics_list(data={'course_id': self.test_course_1.id})
        for topic in response['results']:
            self.assertIn('team_count', topic)
            if topic['id'] == u'topic_0':
                self.assertEqual(topic['team_count'], 1)
            else:
                self.assertEqual(topic['team_count'], 0)

904 905 906 907 908 909

@ddt.ddt
class TestDetailTopicAPI(TeamAPITestCase):
    """Test cases for the topic detail endpoint."""

    @ddt.data(
910 911
        (None, 401),
        ('student_inactive', 401),
912 913 914 915
        ('student_unenrolled', 403),
        ('student_enrolled', 200),
        ('staff', 200),
        ('course_staff', 200),
916
        ('community_ta', 200),
917 918 919 920 921 922 923 924 925 926 927 928 929
    )
    @ddt.unpack
    def test_access(self, user, status):
        topic = self.get_topic_detail('topic_0', self.test_course_1.id, status, user=user)
        if status == 200:
            for field in ('id', 'name', 'description'):
                self.assertIn(field, topic)

    @ddt.data('A+BOGUS+COURSE', 'A/BOGUS/COURSE')
    def test_invalid_course_id(self, course_id):
        self.get_topic_detail('topic_0', course_id, 404)

    def test_invalid_topic_id(self):
930 931
        self.get_topic_detail('no_such_topic', self.test_course_1.id, 404)

932 933 934 935 936 937 938
    def test_team_count(self):
        """Test that team_count is included with a topic"""
        topic = self.get_topic_detail(topic_id='topic_0', course_id=self.test_course_1.id)
        self.assertEqual(topic['team_count'], 1)
        topic = self.get_topic_detail(topic_id='topic_1', course_id=self.test_course_1.id)
        self.assertEqual(topic['team_count'], 0)

939 940 941 942 943 944 945 946 947 948 949 950 951

@ddt.ddt
class TestListMembershipAPI(TeamAPITestCase):
    """Test cases for the membership list endpoint."""

    @ddt.data(
        (None, 401),
        ('student_inactive', 401),
        ('student_unenrolled', 404),
        ('student_enrolled', 200),
        ('student_enrolled_both_courses_other_team', 200),
        ('staff', 200),
        ('course_staff', 200),
952
        ('community_ta', 200),
953 954 955 956 957 958
    )
    @ddt.unpack
    def test_access(self, user, status):
        membership = self.get_membership_list(status, {'team_id': self.test_team_1.team_id}, user=user)
        if status == 200:
            self.assertEqual(membership['count'], 1)
959
            self.assertEqual(membership['results'][0]['user']['username'], self.users['student_enrolled'].username)
960 961 962 963 964 965 966 967 968

    @ddt.data(
        (None, 401, False),
        ('student_inactive', 401, False),
        ('student_unenrolled', 200, False),
        ('student_enrolled', 200, True),
        ('student_enrolled_both_courses_other_team', 200, True),
        ('staff', 200, True),
        ('course_staff', 200, True),
969
        ('community_ta', 200, True),
970 971 972 973 974 975 976
    )
    @ddt.unpack
    def test_access_by_username(self, user, status, has_content):
        membership = self.get_membership_list(status, {'username': self.users['student_enrolled'].username}, user=user)
        if status == 200:
            if has_content:
                self.assertEqual(membership['count'], 1)
977
                self.assertEqual(membership['results'][0]['team']['team_id'], self.test_team_1.team_id)
978 979 980
            else:
                self.assertEqual(membership['count'], 0)

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    @ddt.data(
        ('student_enrolled_both_courses_other_team', 'TestX/TS101/Test_Course', 200, 'Nuclear Team'),
        ('student_enrolled_both_courses_other_team', 'MIT/6.002x/Circuits', 200, 'Another Team'),
        ('student_enrolled', 'TestX/TS101/Test_Course', 200, u'sólar team'),
        ('student_enrolled', 'MIT/6.002x/Circuits', 400, ''),
    )
    @ddt.unpack
    def test_course_filter_with_username(self, user, course_id, status, team_name):
        membership = self.get_membership_list(
            status,
            {
                'username': self.users[user],
                'course_id': course_id
            },
            user=user
        )
        if status == 200:
            self.assertEqual(membership['count'], 1)
            self.assertEqual(membership['results'][0]['team']['team_id'], self.test_team_name_id_map[team_name].team_id)

    @ddt.data(
        ('TestX/TS101/Test_Course', 200),
        ('MIT/6.002x/Circuits', 400),
    )
    @ddt.unpack
    def test_course_filter_with_team_id(self, course_id, status):
        membership = self.get_membership_list(status, {'team_id': self.test_team_1.team_id, 'course_id': course_id})
        if status == 200:
            self.assertEqual(membership['count'], 1)
            self.assertEqual(membership['results'][0]['team']['team_id'], self.test_team_1.team_id)

    def test_bad_course_id(self):
        self.get_membership_list(404, {'course_id': 'no_such_course'})

1015 1016 1017 1018 1019 1020
    def test_no_username_or_team_id(self):
        self.get_membership_list(400, {})

    def test_bad_team_id(self):
        self.get_membership_list(404, {'team_id': 'no_such_team'})

1021 1022
    def test_expand_private_user(self):
        # Use the default user which is already private because to year_of_birth is set
1023
        result = self.get_membership_list(200, {'team_id': self.test_team_1.team_id, 'expand': 'user'})
1024 1025 1026 1027 1028 1029 1030 1031 1032
        self.verify_expanded_private_user(result['results'][0]['user'])

    def test_expand_public_user(self):
        result = self.get_membership_list(
            200,
            {'team_id': self.test_team_6.team_id, 'expand': 'user'},
            user='student_enrolled_public_profile'
        )
        self.verify_expanded_public_user(result['results'][0]['user'])
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

    def test_expand_team(self):
        result = self.get_membership_list(200, {'team_id': self.test_team_1.team_id, 'expand': 'team'})
        self.verify_expanded_team(result['results'][0]['team'])


@ddt.ddt
class TestCreateMembershipAPI(TeamAPITestCase):
    """Test cases for the membership creation endpoint."""

    @ddt.data(
        (None, 401),
        ('student_inactive', 401),
        ('student_unenrolled', 404),
        ('student_enrolled_not_on_team', 200),
        ('student_enrolled', 404),
        ('student_enrolled_both_courses_other_team', 404),
        ('staff', 200),
        ('course_staff', 200),
1052
        ('community_ta', 200),
1053 1054 1055 1056 1057 1058 1059 1060 1061
    )
    @ddt.unpack
    def test_access(self, user, status):
        membership = self.post_create_membership(
            status,
            self.build_membership_data('student_enrolled_not_on_team', self.test_team_1),
            user=user
        )
        if status == 200:
1062 1063
            self.assertEqual(membership['user']['username'], self.users['student_enrolled_not_on_team'].username)
            self.assertEqual(membership['team']['team_id'], self.test_team_1.team_id)
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
            memberships = self.get_membership_list(200, {'team_id': self.test_team_1.team_id})
            self.assertEqual(memberships['count'], 2)

    def test_no_username(self):
        response = self.post_create_membership(400, {'team_id': self.test_team_1.team_id})
        self.assertIn('username', json.loads(response.content)['field_errors'])

    def test_no_team(self):
        response = self.post_create_membership(400, {'username': self.users['student_enrolled_not_on_team'].username})
        self.assertIn('team_id', json.loads(response.content)['field_errors'])

    def test_bad_team(self):
        self.post_create_membership(
            404,
            self.build_membership_data_raw(self.users['student_enrolled'].username, 'no_such_team')
        )

    def test_bad_username(self):
        self.post_create_membership(
            404,
            self.build_membership_data_raw('no_such_user', self.test_team_1.team_id),
            user='staff'
        )

    @ddt.data('student_enrolled', 'staff', 'course_staff')
    def test_join_twice(self, user):
        response = self.post_create_membership(
            400,
            self.build_membership_data('student_enrolled', self.test_team_1),
            user=user
        )
        self.assertIn('already a member', json.loads(response.content)['developer_message'])

    def test_join_second_team_in_course(self):
        response = self.post_create_membership(
            400,
            self.build_membership_data('student_enrolled_both_courses_other_team', self.test_team_1),
            user='student_enrolled_both_courses_other_team'
        )
        self.assertIn('already a member', json.loads(response.content)['developer_message'])

    @ddt.data('staff', 'course_staff')
    def test_not_enrolled_in_team_course(self, user):
        response = self.post_create_membership(
            400,
            self.build_membership_data('student_unenrolled', self.test_team_1),
            user=user
        )
        self.assertIn('not enrolled', json.loads(response.content)['developer_message'])

1114 1115 1116 1117 1118 1119 1120 1121
    def test_over_max_team_size_in_course_2(self):
        response = self.post_create_membership(
            400,
            self.build_membership_data('student_enrolled_other_course_not_on_team', self.test_team_5),
            user='student_enrolled_other_course_not_on_team'
        )
        self.assertIn('full', json.loads(response.content)['developer_message'])

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

@ddt.ddt
class TestDetailMembershipAPI(TeamAPITestCase):
    """Test cases for the membership detail endpoint."""

    @ddt.data(
        (None, 401),
        ('student_inactive', 401),
        ('student_unenrolled', 404),
        ('student_enrolled_not_on_team', 200),
        ('student_enrolled', 200),
        ('staff', 200),
        ('course_staff', 200),
1135
        ('community_ta', 200),
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    )
    @ddt.unpack
    def test_access(self, user, status):
        self.get_membership_detail(
            self.test_team_1.team_id,
            self.users['student_enrolled'].username,
            status,
            user=user
        )

    def test_bad_team(self):
        self.get_membership_detail('no_such_team', self.users['student_enrolled'].username, 404)

    def test_bad_username(self):
        self.get_membership_detail(self.test_team_1.team_id, 'no_such_user', 404)

    def test_no_membership(self):
        self.get_membership_detail(
            self.test_team_1.team_id,
            self.users['student_enrolled_not_on_team'].username,
            404
        )

1159 1160
    def test_expand_private_user(self):
        # Use the default user which is already private because to year_of_birth is set
1161 1162 1163 1164 1165 1166
        result = self.get_membership_detail(
            self.test_team_1.team_id,
            self.users['student_enrolled'].username,
            200,
            {'expand': 'user'}
        )
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        self.verify_expanded_private_user(result['user'])

    def test_expand_public_user(self):
        result = self.get_membership_detail(
            self.test_team_6.team_id,
            self.users['student_enrolled_public_profile'].username,
            200,
            {'expand': 'user'},
            user='student_enrolled_public_profile'
        )
        self.verify_expanded_public_user(result['user'])
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200

    def test_expand_team(self):
        result = self.get_membership_detail(
            self.test_team_1.team_id,
            self.users['student_enrolled'].username,
            200,
            {'expand': 'team'}
        )
        self.verify_expanded_team(result['team'])


@ddt.ddt
class TestDeleteMembershipAPI(TeamAPITestCase):
    """Test cases for the membership deletion endpoint."""

    @ddt.data(
        (None, 401),
        ('student_inactive', 401),
        ('student_unenrolled', 404),
        ('student_enrolled_not_on_team', 404),
        ('student_enrolled', 204),
        ('staff', 204),
        ('course_staff', 204),
1201
        ('community_ta', 204),
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
    )
    @ddt.unpack
    def test_access(self, user, status):
        self.delete_membership(
            self.test_team_1.team_id,
            self.users['student_enrolled'].username,
            status,
            user=user
        )

    def test_bad_team(self):
        self.delete_membership('no_such_team', self.users['student_enrolled'].username, 404)

    def test_bad_username(self):
        self.delete_membership(self.test_team_1.team_id, 'no_such_user', 404)

    def test_missing_membership(self):
        self.delete_membership(self.test_team_2.team_id, self.users['student_enrolled'].username, 404)