replaced unittest assertions pytest assertions (#26549)

This commit is contained in:
Aarif
2021-02-23 10:24:42 +05:00
committed by GitHub
parent b41cb6a2ae
commit c828beb5d1
20 changed files with 505 additions and 677 deletions

View File

@@ -103,51 +103,51 @@ class PythonAPITests(SharedModuleStoreTestCase):
cls.team2a.add_user(cls.user4)
def test_get_team_by_team_id_non_existence(self):
self.assertIsNone(teams_api.get_team_by_team_id('DO_NOT_EXIST'))
assert teams_api.get_team_by_team_id('DO_NOT_EXIST') is None
def test_get_team_by_team_id_exists(self):
team = teams_api.get_team_by_team_id(self.team1.team_id)
self.assertEqual(team, self.team1)
assert team == self.team1
def test_get_team_by_discussion_non_existence(self):
self.assertIsNone(teams_api.get_team_by_discussion('DO_NOT_EXIST'))
assert teams_api.get_team_by_discussion('DO_NOT_EXIST') is None
def test_get_team_by_discussion_exists(self):
team = teams_api.get_team_by_discussion(DISCUSSION_TOPIC_ID)
self.assertEqual(team, self.team1)
assert team == self.team1
def test_is_team_discussion_private_is_private(self):
self.assertTrue(teams_api.is_team_discussion_private(self.team1))
assert teams_api.is_team_discussion_private(self.team1)
def test_is_team_discussion_private_is_public(self):
self.assertFalse(teams_api.is_team_discussion_private(None))
self.assertFalse(teams_api.is_team_discussion_private(self.team2))
self.assertFalse(teams_api.is_team_discussion_private(self.team3))
assert not teams_api.is_team_discussion_private(None)
assert not teams_api.is_team_discussion_private(self.team2)
assert not teams_api.is_team_discussion_private(self.team3)
def test_is_instructor_managed_team(self):
self.assertTrue(teams_api.is_instructor_managed_team(self.team1))
self.assertFalse(teams_api.is_instructor_managed_team(self.team2))
self.assertTrue(teams_api.is_instructor_managed_team(self.team3))
assert teams_api.is_instructor_managed_team(self.team1)
assert not teams_api.is_instructor_managed_team(self.team2)
assert teams_api.is_instructor_managed_team(self.team3)
def test_is_instructor_managed_topic(self):
self.assertTrue(teams_api.is_instructor_managed_topic(COURSE_KEY1, TOPIC1))
self.assertFalse(teams_api.is_instructor_managed_topic(COURSE_KEY2, TOPIC2))
self.assertTrue(teams_api.is_instructor_managed_topic(COURSE_KEY2, TOPIC3))
assert teams_api.is_instructor_managed_topic(COURSE_KEY1, TOPIC1)
assert not teams_api.is_instructor_managed_topic(COURSE_KEY2, TOPIC2)
assert teams_api.is_instructor_managed_topic(COURSE_KEY2, TOPIC3)
def test_user_is_a_team_member(self):
self.assertTrue(teams_api.user_is_a_team_member(self.user1, self.team1))
self.assertFalse(teams_api.user_is_a_team_member(self.user1, None))
self.assertFalse(teams_api.user_is_a_team_member(self.user1, self.team2))
assert teams_api.user_is_a_team_member(self.user1, self.team1)
assert not teams_api.user_is_a_team_member(self.user1, None)
assert not teams_api.user_is_a_team_member(self.user1, self.team2)
def test_private_discussion_visible_by_user(self):
self.assertTrue(teams_api.discussion_visible_by_user(DISCUSSION_TOPIC_ID, self.user1))
self.assertTrue(teams_api.discussion_visible_by_user(DISCUSSION_TOPIC_ID, self.user2))
assert teams_api.discussion_visible_by_user(DISCUSSION_TOPIC_ID, self.user1)
assert teams_api.discussion_visible_by_user(DISCUSSION_TOPIC_ID, self.user2)
# self.assertFalse(teams_api.discussion_visible_by_user(DISCUSSION_TOPIC_ID, self.user3))
def test_public_discussion_visible_by_user(self):
self.assertTrue(teams_api.discussion_visible_by_user(self.team2.discussion_topic_id, self.user1))
self.assertTrue(teams_api.discussion_visible_by_user(self.team2.discussion_topic_id, self.user2))
self.assertTrue(teams_api.discussion_visible_by_user('DO_NOT_EXISTS', self.user3))
assert teams_api.discussion_visible_by_user(self.team2.discussion_topic_id, self.user1)
assert teams_api.discussion_visible_by_user(self.team2.discussion_topic_id, self.user2)
assert teams_api.discussion_visible_by_user('DO_NOT_EXISTS', self.user3)
@ddt.unpack
@ddt.data(
@@ -162,10 +162,10 @@ class PythonAPITests(SharedModuleStoreTestCase):
user3_team = teams_api.get_team_for_user_course_topic(self.user3, str(course_key), topic_id)
user4_team = teams_api.get_team_for_user_course_topic(self.user4, str(course_key), topic_id)
self.assertEqual(user1_team.team_id if user1_team else None, expected_team_ids[0])
self.assertEqual(user2_team.team_id if user2_team else None, expected_team_ids[1])
self.assertEqual(user3_team.team_id if user3_team else None, expected_team_ids[2])
self.assertEqual(user4_team.team_id if user4_team else None, expected_team_ids[3])
assert (user1_team.team_id if user1_team else None) == expected_team_ids[0]
assert (user2_team.team_id if user2_team else None) == expected_team_ids[1]
assert (user3_team.team_id if user3_team else None) == expected_team_ids[2]
assert (user4_team.team_id if user4_team else None) == expected_team_ids[3]
@mock.patch('lms.djangoapps.teams.api.CourseTeam.objects')
def test_get_team_multiple_teams(self, mocked_manager):
@@ -180,11 +180,11 @@ class PythonAPITests(SharedModuleStoreTestCase):
mock_qs.first.return_value = expected_result
mocked_manager.filter.return_value = mock_qs
result = teams_api.get_team_for_user_course_topic(self.user1, str(COURSE_KEY1), TOPIC1)
self.assertEqual(result, expected_result)
assert result == expected_result
def test_get_team_course_not_found(self):
team = teams_api.get_team_for_user_course_topic(self.user1, 'nonsense/garbage/nonexistant', 'topic')
self.assertIsNone(team)
assert team is None
def test_get_team_invalid_course(self):
invalid_course_id = 'lol!()#^$&course'
@@ -197,8 +197,8 @@ class PythonAPITests(SharedModuleStoreTestCase):
A learner should be able to get the anonymous user IDs of their team members
"""
team_anonymous_user_ids = teams_api.anonymous_user_ids_for_team(self.user1, self.team1)
self.assertTrue(AnonymousUserId.objects.get(user=self.user1, course_id=self.team1.course_id))
self.assertEqual(len(self.team1.users.all()), len(team_anonymous_user_ids))
assert AnonymousUserId.objects.get(user=self.user1, course_id=self.team1.course_id)
assert len(self.team1.users.all()) == len(team_anonymous_user_ids)
def test_anonymous_user_ids_for_team_not_on_team(self):
"""
@@ -221,7 +221,7 @@ class PythonAPITests(SharedModuleStoreTestCase):
CourseStaffRole(COURSE_KEY1).add_users(user_staff)
team_anonymous_user_ids = teams_api.anonymous_user_ids_for_team(user_staff, self.team1)
self.assertEqual(len(self.team1.users.all()), len(team_anonymous_user_ids))
assert len(self.team1.users.all()) == len(team_anonymous_user_ids)
@ddt.ddt
@@ -296,10 +296,7 @@ class TeamAccessTests(SharedModuleStoreTestCase):
@ddt.unpack
def test_has_team_api_access(self, username, expected_have_access):
user = self.users[username]
self.assertEqual(
expected_have_access,
teams_api.has_team_api_access(user, COURSE_KEY1)
)
assert expected_have_access == teams_api.has_team_api_access(user, COURSE_KEY1)
@ddt.data(
('user_audit', teams_api.OrganizationProtectionStatus.unprotected),
@@ -311,12 +308,9 @@ class TeamAccessTests(SharedModuleStoreTestCase):
def test_user_organization_protection_status(self, username, expected_protection_status):
user = self.users[username]
try:
self.assertEqual(
expected_protection_status,
teams_api.user_organization_protection_status(user, COURSE_KEY1)
)
assert expected_protection_status == teams_api.user_organization_protection_status(user, COURSE_KEY1)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, COURSE_KEY1))
assert not CourseEnrollment.is_enrolled(user, COURSE_KEY1)
@ddt.data(
('user_audit', True),
@@ -328,12 +322,9 @@ class TeamAccessTests(SharedModuleStoreTestCase):
def test_has_specific_team_access_unprotected_team(self, username, expected_return):
user = self.users[username]
try:
self.assertEqual(
expected_return,
teams_api.has_specific_team_access(user, self.team_unprotected_1)
)
assert expected_return == teams_api.has_specific_team_access(user, self.team_unprotected_1)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, self.team_unprotected_1.course_id))
assert not CourseEnrollment.is_enrolled(user, self.team_unprotected_1.course_id)
@ddt.data(
('user_audit', False),
@@ -345,12 +336,9 @@ class TeamAccessTests(SharedModuleStoreTestCase):
def test_has_specific_team_access_protected_team(self, username, expected_return):
user = self.users[username]
try:
self.assertEqual(
expected_return,
teams_api.has_specific_team_access(user, self.team_protected_1)
)
assert expected_return == teams_api.has_specific_team_access(user, self.team_protected_1)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, self.team_protected_1.course_id))
assert not CourseEnrollment.is_enrolled(user, self.team_protected_1.course_id)
@ddt.data(
('user_audit', 3),
@@ -367,7 +355,7 @@ class TeamAccessTests(SharedModuleStoreTestCase):
COURSE_KEY1
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, COURSE_KEY1))
assert not CourseEnrollment.is_enrolled(user, COURSE_KEY1)
return
teams_query_set = teams_api.get_teams_accessible_by_user(
user,
@@ -375,10 +363,7 @@ class TeamAccessTests(SharedModuleStoreTestCase):
COURSE_KEY1,
organization_protection_status
)
self.assertEqual(
expected_count,
teams_query_set.count()
)
assert expected_count == teams_query_set.count()
@ddt.data(
('user_audit', 3),
@@ -395,7 +380,7 @@ class TeamAccessTests(SharedModuleStoreTestCase):
COURSE_KEY1
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, COURSE_KEY1))
assert not CourseEnrollment.is_enrolled(user, COURSE_KEY1)
return
topic = {
'id': self.topic_id
@@ -406,7 +391,4 @@ class TeamAccessTests(SharedModuleStoreTestCase):
COURSE_KEY1,
organization_protection_status
)
self.assertEqual(
expected_team_count,
topic.get('team_count')
)
assert expected_team_count == topic.get('team_count')

View File

@@ -128,24 +128,18 @@ class TeamMembershipCsvTests(SharedModuleStoreTestCase):
def test_get_headers(self):
# pylint: disable=protected-access
headers = csv._get_team_membership_csv_headers(self.course)
self.assertEqual(
headers,
['user', 'mode', 'teamset_1', 'teamset_2', 'teamset_3', 'teamset_4']
)
assert headers == ['user', 'mode', 'teamset_1', 'teamset_2', 'teamset_3', 'teamset_4']
def test_get_headers_no_teamsets(self):
# pylint: disable=protected-access
headers = csv._get_team_membership_csv_headers(self.course_no_teamsets)
self.assertEqual(
headers,
['user', 'mode']
)
assert headers == ['user', 'mode']
def test_lookup_team_membership_data(self):
with self.assertNumQueries(3):
# pylint: disable=protected-access
data = csv._lookup_team_membership_data(self.course)
self.assertEqual(len(data), 5)
assert len(data) == 5
self.assert_teamset_membership(data[0], 'user1', 'audit', 'team_1_1', 'team_2_2', 'team_3_1')
self.assert_teamset_membership(data[1], 'user2', 'verified', 'team_1_1', 'team_2_2', 'team_3_1')
self.assert_teamset_membership(data[2], 'user3', 'honors', None, 'team_2_1', 'team_3_1')
@@ -167,11 +161,11 @@ class TeamMembershipCsvTests(SharedModuleStoreTestCase):
-mode
-team name for teamset_(123)
"""
self.assertEqual(user_row['user'], expected_username)
self.assertEqual(user_row['mode'], expected_mode)
self.assertEqual(user_row.get('teamset_1'), expected_teamset_1_team)
self.assertEqual(user_row.get('teamset_2'), expected_teamset_2_team)
self.assertEqual(user_row.get('teamset_3'), expected_teamset_3_team)
assert user_row['user'] == expected_username
assert user_row['mode'] == expected_mode
assert user_row.get('teamset_1') == expected_teamset_1_team
assert user_row.get('teamset_2') == expected_teamset_2_team
assert user_row.get('teamset_3') == expected_teamset_3_team
def test_load_team_membership_csv(self):
expected_csv_headers = ['user', 'mode', 'teamset_1', 'teamset_2', 'teamset_3', 'teamset_4']
@@ -196,7 +190,7 @@ class TeamMembershipCsvTests(SharedModuleStoreTestCase):
self._add_blanks_to_expected_data(expected_data, expected_csv_headers)
reader = csv_export(self.course)
self.assertEqual(expected_csv_headers, reader.fieldnames)
assert expected_csv_headers == reader.fieldnames
self.assertDictEqual(expected_data, _user_keyed_dict(reader))
def _add_blanks_to_expected_data(self, expected_data, headers):
@@ -281,7 +275,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
self.import_manager.add_user_to_team(row)
team = CourseTeam.objects.get(team_id__startswith='new_protected_team')
self.assertTrue(team.organization_protected)
assert team.organization_protected
self.assert_learner_added_emitted(team.team_id, masters_learner.id)
def test_add_user_to_new_unprotected_team(self):
@@ -296,7 +290,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
self.import_manager.add_user_to_team(row)
team = CourseTeam.objects.get(team_id__startswith='new_unprotected_team')
self.assertFalse(team.organization_protected)
assert not team.organization_protected
self.assert_learner_added_emitted(team.team_id, audit_learner.id)
def test_team_removals_are_scoped_correctly(self):
@@ -316,7 +310,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
)
course_2_team.add_user(audit_learner)
self.assertTrue(CourseTeamMembership.is_user_on_team(audit_learner, course_1_team))
assert CourseTeamMembership.is_user_on_team(audit_learner, course_1_team)
# When I try to remove them from the team
row = {
@@ -327,7 +321,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
self.import_manager.remove_user_from_team_for_reassignment(row)
# They are successfully removed from the team
self.assertFalse(CourseTeamMembership.is_user_on_team(audit_learner, course_1_team))
assert not CourseTeamMembership.is_user_on_team(audit_learner, course_1_team)
self.assert_learner_removed_emitted(course_1_team.team_id, audit_learner.id)
def test_user_moved_to_another_team(self):
@@ -343,8 +337,8 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
csv_row = _csv_dict_row(audit_learner, 'audit', teamset_1=team_2.name)
csv_import(self.course, [csv_row])
self.assertFalse(CourseTeamMembership.is_user_on_team(audit_learner, team_1))
self.assertTrue(CourseTeamMembership.is_user_on_team(audit_learner, team_2))
assert not CourseTeamMembership.is_user_on_team(audit_learner, team_1)
assert CourseTeamMembership.is_user_on_team(audit_learner, team_2)
self.assert_learner_removed_emitted(team_1.team_id, audit_learner.id)
self.assert_learner_added_emitted(team_2.team_id, audit_learner.id)
@@ -380,16 +374,13 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data)
# Then the import fails with no events emitted and a "team is full" error
self.assertFalse(result)
assert not result
self.assert_no_events_were_emitted()
self.assertEqual(
self.import_manager.validation_errors[0],
'New membership for team team_1 would exceed max size of 3.'
)
assert self.import_manager.validation_errors[0] == 'New membership for team team_1 would exceed max size of 3.'
# Confirm that memberships were not altered
for i in range(2):
self.assertTrue(CourseTeamMembership.is_user_on_team(user, team))
assert CourseTeamMembership.is_user_on_team(user, team)
def test_remove_from_team(self):
# Given a user already in a course and on a team
@@ -398,7 +389,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
CourseEnrollmentFactory.create(user=user, course_id=self.course.id, mode=mode)
team = CourseTeamFactory(course_id=self.course.id, name='team_1', topic_id='teamset_1')
team.add_user(user)
self.assertTrue(CourseTeamMembership.is_user_on_team(user, team))
assert CourseTeamMembership.is_user_on_team(user, team)
# When I try to remove them from the team
csv_data = self._csv_reader_from_array([
@@ -408,7 +399,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data) # lint-amnesty, pylint: disable=unused-variable
# Then they are removed from the team and the correct events are issued
self.assertFalse(CourseTeamMembership.is_user_on_team(user, team))
assert not CourseTeamMembership.is_user_on_team(user, team)
self.assert_learner_removed_emitted(team.team_id, user.id)
def test_switch_memberships(self):
@@ -435,15 +426,15 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data)
# Then membership size is calculated correctly, import finishes w/out error
self.assertTrue(result)
assert result
# ... and the users are assigned to the correct teams
team_1 = CourseTeam.objects.get(course_id=self.course.id, topic_id='teamset_1', name='team_1')
self.assertTrue(CourseTeamMembership.is_user_on_team(users[4], team_1))
assert CourseTeamMembership.is_user_on_team(users[4], team_1)
self.assert_learner_added_emitted(team_1.team_id, users[4].id)
team_2 = CourseTeam.objects.get(course_id=self.course.id, topic_id='teamset_1', name='team_2')
self.assertTrue(CourseTeamMembership.is_user_on_team(users[0], team_2))
assert CourseTeamMembership.is_user_on_team(users[0], team_2)
self.assert_learner_added_emitted(team_2.team_id, users[0].id)
def test_create_new_team_from_import(self):
@@ -453,7 +444,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
CourseEnrollmentFactory.create(user=user, course_id=self.course.id, mode=mode)
# When I add them to a team that does not exist
self.assertEqual(CourseTeam.objects.all().count(), 0)
assert CourseTeam.objects.all().count() == 0
csv_data = self._csv_reader_from_array([
['user', 'mode', 'teamset_1'],
[user.username, mode, 'new_exciting_team'],
@@ -461,11 +452,11 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data) # lint-amnesty, pylint: disable=unused-variable
# Then a new team is created
self.assertEqual(CourseTeam.objects.all().count(), 1)
assert CourseTeam.objects.all().count() == 1
# ... and the user is assigned to the team
new_team = CourseTeam.objects.get(topic_id='teamset_1', name='new_exciting_team')
self.assertTrue(CourseTeamMembership.is_user_on_team(user, new_team))
assert CourseTeamMembership.is_user_on_team(user, new_team)
self.assert_learner_added_emitted(new_team.team_id, user.id)
# Team protection status tests
@@ -475,7 +466,7 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
masters_learner = self._create_and_enroll_test_user('masters_learner', mode='masters')
# When I attempt to add them to the same team
self.assertEqual(CourseTeam.objects.all().count(), 0)
assert CourseTeam.objects.all().count() == 0
csv_data = self._csv_reader_from_array([
['user', 'mode', 'teamset_1'],
[verified_learner.username, 'verified', 'new_exciting_team'],
@@ -484,13 +475,11 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data)
# The import fails with "mixed users" error and no team was created
self.assertFalse(result)
assert not result
self.assert_no_events_were_emitted()
self.assertEqual(
self.import_manager.validation_errors[0],
'Team new_exciting_team cannot have Masters track users mixed with users in other tracks.'
)
self.assertEqual(CourseTeam.objects.all().count(), 0)
assert self.import_manager.validation_errors[0] ==\
'Team new_exciting_team cannot have Masters track users mixed with users in other tracks.'
assert CourseTeam.objects.all().count() == 0
def test_add_incompatible_mode_to_existing_unprotected_team_fails(self):
# Given an existing unprotected team
@@ -507,13 +496,11 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data)
# The import fails with "mixed users" error and learner not added to team
self.assertFalse(result)
assert not result
self.assert_no_events_were_emitted()
self.assertEqual(
self.import_manager.validation_errors[0],
'Team unprotected_team cannot have Masters track users mixed with users in other tracks.'
)
self.assertFalse(CourseTeamMembership.is_user_on_team(masters_learner, unprotected_team))
assert self.import_manager.validation_errors[0] ==\
'Team unprotected_team cannot have Masters track users mixed with users in other tracks.'
assert not CourseTeamMembership.is_user_on_team(masters_learner, unprotected_team)
def test_add_incompatible_mode_to_existing_protected_team_fails(self):
# Given an existing protected team
@@ -535,13 +522,11 @@ class TeamMembershipImportManagerTests(TeamMembershipEventTestMixin, SharedModul
result = self.import_manager.set_team_memberships(csv_data)
# The import fails with "mixed users" error and learner not added to team
self.assertFalse(result)
assert not result
self.assert_no_events_were_emitted()
self.assertEqual(
self.import_manager.validation_errors[0],
'Team protected_team cannot have Masters track users mixed with users in other tracks.'
)
self.assertFalse(CourseTeamMembership.is_user_on_team(verified_learner, protected_team))
assert self.import_manager.validation_errors[0] ==\
'Team protected_team cannot have Masters track users mixed with users in other tracks.'
assert not CourseTeamMembership.is_user_on_team(verified_learner, protected_team)
def _create_and_enroll_test_user(self, username, course_id=None, mode="audit"):
"""
@@ -628,10 +613,10 @@ class ExternalKeyCsvTests(TeamMembershipEventTestMixin, SharedModuleStoreTestCas
)
def assert_user_on_team(self, user):
self.assertTrue(CourseTeamMembership.is_user_on_team(user, self.team))
assert CourseTeamMembership.is_user_on_team(user, self.team)
def assert_user_not_on_team(self, user):
self.assertFalse(CourseTeamMembership.is_user_on_team(user, self.team))
assert not CourseTeamMembership.is_user_on_team(user, self.team)
def test_add_user_to_team_with_external_key(self):
# Make a new user with an external_user_key who is enrolled in the course and program, with an external_key,
@@ -661,7 +646,7 @@ class ExternalKeyCsvTests(TeamMembershipEventTestMixin, SharedModuleStoreTestCas
Assert that the four test users should be listed as members of the team,
and user_in_program should be identified by their external_user_key
"""
self.assertEqual(len(data), 4)
assert len(data) == 4
expected_data = {
user_identifier: _csv_dict_row(user_identifier, 'audit', teamset_id=self.team.name)
for user_identifier in [

View File

@@ -5,6 +5,7 @@ Tests for the teams API at the HTTP request level.
import itertools
import pytest
from contextlib import contextmanager
from datetime import datetime
@@ -134,16 +135,16 @@ class CourseTeamTest(SharedModuleStoreTestCase):
def test_add_user(self):
"""Test that we can add users with correct protection status to a team"""
self.assertIsNotNone(self.masters_team.add_user(self.masters_learner))
self.assertIsNotNone(self.audit_team.add_user(self.audit_learner))
assert self.masters_team.add_user(self.masters_learner) is not None
assert self.audit_team.add_user(self.audit_learner) is not None
def test_add_user_bad_team_access(self):
"""Test that we are blocked from adding a user to a team of mixed enrollment types"""
with self.assertRaises(AddToIncompatibleTeamError):
with pytest.raises(AddToIncompatibleTeamError):
self.audit_team.add_user(self.masters_learner)
with self.assertRaises(AddToIncompatibleTeamError):
with pytest.raises(AddToIncompatibleTeamError):
self.masters_team.add_user(self.audit_learner)
@@ -189,31 +190,31 @@ class TeamMembershipTest(SharedModuleStoreTestCase):
def test_membership_last_activity_set(self):
current_last_activity = self.team_membership11.last_activity_at
# Assert that the first save in the setUp sets a value.
self.assertIsNotNone(current_last_activity)
assert current_last_activity is not None
self.team_membership11.save()
# Verify that we only change the last activity_at when it doesn't
# already exist.
self.assertEqual(self.team_membership11.last_activity_at, current_last_activity)
assert self.team_membership11.last_activity_at == current_last_activity
def test_team_size_delete_membership(self):
"""Test that the team size field is correctly updated when deleting a
team membership.
"""
self.assertEqual(self.team1.team_size, 2)
assert self.team1.team_size == 2
self.team_membership11.delete()
team = CourseTeam.objects.get(id=self.team1.id)
self.assertEqual(team.team_size, 1)
assert team.team_size == 1
def test_team_size_create_membership(self):
"""Test that the team size field is correctly updated when creating a
team membership.
"""
self.assertEqual(self.team1.team_size, 2)
assert self.team1.team_size == 2
self.team1.add_user(self.user3)
team = CourseTeam.objects.get(id=self.team1.id)
self.assertEqual(team.team_size, 3)
assert team.team_size == 3
@ddt.data(
(None, None, None, 3),
@@ -224,10 +225,9 @@ class TeamMembershipTest(SharedModuleStoreTestCase):
)
@ddt.unpack
def test_get_memberships(self, username, course_ids, team_ids, expected_count):
self.assertEqual(
CourseTeamMembership.get_memberships(username=username, course_ids=course_ids, team_ids=team_ids).count(),
expected_count
)
assert CourseTeamMembership.get_memberships(username=username,
course_ids=course_ids,
team_ids=team_ids).count() == expected_count
@ddt.data(
('user1', COURSE_KEY1, TEAMSET_1_ID, True),
@@ -240,10 +240,7 @@ class TeamMembershipTest(SharedModuleStoreTestCase):
@ddt.unpack
def test_user_in_team_for_course_teamset(self, username, course_id, teamset_id, expected_value):
user = getattr(self, username)
self.assertEqual(
CourseTeamMembership.user_in_team_for_teamset(user, course_id, teamset_id),
expected_value
)
assert CourseTeamMembership.user_in_team_for_teamset(user, course_id, teamset_id) == expected_value
@ddt.ddt
@@ -296,18 +293,18 @@ class TeamSignalsTest(EventTestMixin, SharedModuleStoreTestCase):
team = CourseTeam.objects.get(id=self.team.id)
team_membership = CourseTeamMembership.objects.get(id=self.team_membership.id)
if should_update:
self.assertGreater(team.last_activity_at, team_last_activity)
self.assertGreater(team_membership.last_activity_at, team_membership_last_activity)
assert team.last_activity_at > team_last_activity
assert team_membership.last_activity_at > team_membership_last_activity
now = datetime.utcnow().replace(tzinfo=pytz.utc)
self.assertGreater(now, team.last_activity_at)
self.assertGreater(now, team_membership.last_activity_at)
assert now > team.last_activity_at
assert now > team_membership.last_activity_at
self.assert_event_emitted(
'edx.team.activity_updated',
team_id=team.team_id,
)
else:
self.assertEqual(team.last_activity_at, team_last_activity)
self.assertEqual(team_membership.last_activity_at, team_membership_last_activity)
assert team.last_activity_at == team_last_activity
assert team_membership.last_activity_at == team_membership_last_activity
self.assert_no_events_were_emitted()
@ddt.data(

View File

@@ -55,19 +55,14 @@ class MembershipSerializerTestCase(SerializerTestCase):
'request': RequestFactory().get('/api/team/v0/team_membership')
}).data
username = self.user.username
self.assertEqual(data['user'], {
'url': 'http://testserver/api/user/v1/accounts/' + username,
'username': username,
'profile_image': {
'image_url_full': 'http://testserver/static/default_500.png',
'image_url_large': 'http://testserver/static/default_120.png',
'image_url_medium': 'http://testserver/static/default_50.png',
'image_url_small': 'http://testserver/static/default_30.png',
'has_image': False
},
'account_privacy': 'private'
})
self.assertNotIn('membership', data['team'])
assert data['user'] == {'url': ('http://testserver/api/user/v1/accounts/' + username),
'username': username,
'profile_image': {'image_url_full': 'http://testserver/static/default_500.png',
'image_url_large': 'http://testserver/static/default_120.png',
'image_url_medium': 'http://testserver/static/default_50.png',
'image_url_small': 'http://testserver/static/default_30.png',
'has_image': False}, 'account_privacy': 'private'}
assert 'membership' not in data['team']
class TopicSerializerTestCase(SerializerTestCase):
@@ -86,17 +81,8 @@ class TopicSerializerTestCase(SerializerTestCase):
self.course.teamsets[0].cleaned_data,
context={'course_id': self.course.id},
)
self.assertEqual(
serializer.data,
{
u'name': u'Tøpic',
u'description': u'The bést topic!',
u'id': u'0',
u'team_count': 0,
u'type': u'open',
u'max_team_size': None
}
)
assert serializer.data == {u'name': u'Tøpic', u'description': u'The bést topic!', u'id': u'0',
u'team_count': 0, u'type': u'open', u'max_team_size': None}
def test_topic_with_team_count(self):
"""
@@ -111,17 +97,8 @@ class TopicSerializerTestCase(SerializerTestCase):
self.course.teamsets[0].cleaned_data,
context={'course_id': self.course.id},
)
self.assertEqual(
serializer.data,
{
u'name': u'Tøpic',
u'description': u'The bést topic!',
u'id': u'0',
u'team_count': 1,
u'type': u'open',
u'max_team_size': None
}
)
assert serializer.data == {u'name': u'Tøpic', u'description': u'The bést topic!', u'id': u'0',
u'team_count': 1, u'type': u'open', u'max_team_size': None}
def test_scoped_within_course(self):
"""Verify that team count is scoped within a course."""
@@ -139,17 +116,8 @@ class TopicSerializerTestCase(SerializerTestCase):
self.course.teamsets[0].cleaned_data,
context={'course_id': self.course.id},
)
self.assertEqual(
serializer.data,
{
u'name': u'Tøpic',
u'description': u'The bést topic!',
u'id': u'0',
u'team_count': 1,
u'type': u'open',
u'max_team_size': None
}
)
assert serializer.data == {u'name': u'Tøpic', u'description': u'The bést topic!', u'id': u'0',
u'team_count': 1, u'type': u'open', u'max_team_size': None}
class BaseTopicSerializerTestCase(SerializerTestCase):
@@ -203,10 +171,8 @@ class BaseTopicSerializerTestCase(SerializerTestCase):
).page(1)
# pylint: disable=not-callable
serializer = self.serializer(instance=page, context={'course_id': self.course.id})
self.assertEqual(
serializer.data['results'],
[self._merge_dicts(topic, {u'team_count': num_teams_per_topic}) for topic in topics]
)
assert serializer.data['results'] ==\
[self._merge_dicts(topic, {u'team_count': num_teams_per_topic}) for topic in topics]
def test_no_topics(self):
"""
@@ -295,10 +261,8 @@ class BulkTeamCountTopicSerializerTestCase(BaseTopicSerializerTestCase):
},
many=True
)
self.assertEqual(
serializer.data,
[self._merge_dicts(topic, {u'team_count': num_teams_per_topic}) for topic in topics]
)
assert serializer.data ==\
[self._merge_dicts(topic, {u'team_count': num_teams_per_topic}) for topic in topics]
def test_no_topics(self):
"""

View File

@@ -27,31 +27,22 @@ class TeamsServiceTests(ModuleStoreTestCase):
def test_get_team_by_team_id(self):
team = self.service.get_team_by_team_id('NONEXISTANCE')
self.assertIsNone(team)
assert team is None
team = self.service.get_team_by_team_id(self.team.team_id)
self.assertEqual(team, self.team)
assert team == self.team
def test_get_team(self):
user_team = self.service.get_team(self.user, self.course_key, self.team.topic_id)
self.assertEqual(user_team, self.team)
assert user_team == self.team
user2 = UserFactory.create()
user2_team = self.service.get_team(user2, self.course_key, self.team.topic_id)
self.assertIsNone(user2_team)
assert user2_team is None
def test_get_team_detail_url(self):
# edx.org/courses/blah/teams/#teams/topic_id/team_id
team_detail_url = self.service.get_team_detail_url(self.team)
split_url = team_detail_url.split('/')
self.assertEqual(
split_url[1:],
[
'courses',
str(self.course_run['key']),
'teams',
'#teams',
self.team.topic_id,
self.team.team_id,
]
)
assert split_url[1:] ==\
['courses', str(self.course_run['key']), 'teams', '#teams', self.team.topic_id, self.team.team_id]

View File

@@ -86,7 +86,7 @@ class TestDashboard(SharedModuleStoreTestCase):
""" Verifies that a student who is not enrolled cannot access the team dashboard. """
self.client.login(username=self.user.username, password=self.test_password)
response = self.client.get(self.teams_url)
self.assertEqual(404, response.status_code)
assert 404 == response.status_code
def test_not_enrolled_staff(self):
"""
@@ -117,7 +117,7 @@ class TestDashboard(SharedModuleStoreTestCase):
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)
assert 404 == response.status_code
@unittest.skip("Fix this - getting unreliable query counts")
def test_query_counts(self):
@@ -153,11 +153,11 @@ class TestDashboard(SharedModuleStoreTestCase):
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(bad_team_url)
self.assertEqual(404, response.status_code)
assert 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)
assert 404 == response.status_code
def get_user_course_specific_teams_list(self):
"""Gets the list of user course specific teams."""
@@ -614,15 +614,9 @@ class TeamAPITestCase(APITestCase, SharedModuleStoreTestCase):
response = func(url, data=data, content_type=content_type)
else:
response = func(url, data=data)
self.assertEqual(
expected_status,
response.status_code,
msg=u"Expected status {expected} but got {actual}: {content}".format(
expected=expected_status,
actual=response.status_code,
content=response.content.decode(response.charset),
)
)
assert expected_status == response.status_code, "Expected status {expected} but got {actual}: {content}"\
.format(expected=expected_status, actual=response.status_code,
content=response.content.decode(response.charset))
if expected_status == 200:
return json.loads(response.content.decode('utf-8'))
@@ -649,18 +643,18 @@ class TeamAPITestCase(APITestCase, SharedModuleStoreTestCase):
# Check that initially list of user teams in course one is empty
team_list = self.get_teams_list(user=user, expected_status=200, data=course_one_data)
self.assertEqual(team_list['count'], 0)
assert team_list['count'] == 0
# Add user to a course one team
self.solar_team.add_user(self.users[user])
# Check that list of user teams in course one is not empty now
team_list = self.get_teams_list(user=user, expected_status=200, data=course_one_data)
self.assertEqual(team_list['count'], 1)
assert team_list['count'] == 1
# Check that list of user teams in course two is still empty
team_list = self.get_teams_list(user=user, expected_status=200, data=course_two_data)
self.assertEqual(team_list['count'], 0)
assert team_list['count'] == 0
def build_team_data(
self,
@@ -753,19 +747,19 @@ class TeamAPITestCase(APITestCase, SharedModuleStoreTestCase):
def verify_expanded_public_user(self, user):
"""Verifies that fields exist on the returned user json indicating that it is expanded."""
for field in ['username', 'url', 'bio', 'country', 'profile_image', 'time_zone', 'language_proficiencies']:
self.assertIn(field, user)
assert field in user
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)
assert field in user
for field in ['bio', 'country', 'time_zone', 'language_proficiencies']:
self.assertNotIn(field, user)
assert field not in user
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', 'course_id', 'topic_id', 'date_created', 'description']:
self.assertIn(field, team)
assert field in team
def reset_search_index(self):
"""Clear out the search index and reindex the teams."""
@@ -795,7 +789,7 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
def test_access(self, user, status, expected_teams_count=0):
teams = self.get_teams_list(user=user, expected_status=status)
if status == 200:
self.assertEqual(expected_teams_count, teams['count'])
assert expected_teams_count == teams['count']
def test_missing_course_id(self):
self.get_teams_list(400, no_course_id=True)
@@ -805,7 +799,7 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
teams = self.get_teams_list(data=data, expected_status=status, **kwargs)
if names is not None and 200 <= status < 300:
results = teams['results']
self.assertEqual(sorted(names), sorted([team['name'] for team in results]))
assert sorted(names) == sorted([team['name'] for team in results])
def test_filter_invalid_course_id(self):
self.verify_names({'course_id': 'no_such_course'}, 400)
@@ -866,7 +860,7 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
def test_page_size(self):
result = self.get_teams_list(200, {'page_size': 2})
self.assertEqual(2, result['num_pages'])
assert 2 == result['num_pages']
def test_non_member_trying_to_get_private_topic(self):
"""
@@ -874,7 +868,7 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
a private team set, asks for information about that team set, an empty list is returned.
"""
result = self.get_teams_list(data={'topic_id': 'private_topic_1_id'})
self.assertEqual([], result['results'])
assert [] == result['results']
def test_member_trying_to_get_private_topic(self):
"""
@@ -883,9 +877,9 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
"""
result = self.get_teams_list(data={'topic_id': 'private_topic_1_id'},
user='student_on_team_1_private_set_1')
self.assertEqual(1, len(result['results']))
self.assertEqual('private_topic_1_id', result['results'][0]['topic_id'])
self.assertNotEqual([], result['results'])
assert 1 == len(result['results'])
assert 'private_topic_1_id' == result['results'][0]['topic_id']
assert [] != result['results']
def test_course_staff_getting_information_on_private_topic(self):
"""
@@ -894,7 +888,7 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
"""
result = self.get_teams_list(data={'topic_id': 'private_topic_1_id'},
user='course_staff')
self.assertEqual(2, len(result['results']))
assert 2 == len(result['results'])
@ddt.unpack
@ddt.data(
@@ -914,7 +908,7 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
data={'text_search': 'master'},
user=user,
)
self.assertEqual(result['count'], expected_results)
assert result['count'] == expected_results
@ddt.unpack
@ddt.data(
@@ -943,13 +937,13 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
expected_teams.add(self.team_2_in_private_teamset_1.name)
if can_see_private_2_1:
expected_teams.add(self.team_1_in_private_teamset_2.name)
self.assertEqual(expected_teams, teams)
assert expected_teams == teams
def test_page(self):
result = self.get_teams_list(200, {'page_size': 1, 'page': 3})
self.assertEqual(3, result['num_pages'])
self.assertIsNone(result['next'])
self.assertIsNotNone(result['previous'])
assert 3 == result['num_pages']
assert result['next'] is None
assert result['previous'] is not None
def test_expand_private_user(self):
# Use the default user which is already private because to year_of_birth is set
@@ -1066,17 +1060,12 @@ class TestListTeamsAPI(EventTestMixin, TeamAPITestCase):
teams = self.get_teams_list(data={'topic_id': self.solar_team.topic_id}, user='student_enrolled')
team_names = [team['name'] for team in teams['results']]
team_names.sort()
self.assertEqual(team_names, [
self.solar_team.name,
])
assert team_names == [self.solar_team.name]
teams = self.get_teams_list(data={'topic_id': self.solar_team.topic_id}, user='staff')
team_names = [team['name'] for team in teams['results']]
team_names.sort()
self.assertEqual(team_names, [
self.solar_team.name,
self.masters_only_team.name,
])
assert team_names == [self.solar_team.name, self.masters_only_team.name]
@ddt.ddt
@@ -1101,7 +1090,7 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
if status == 200:
self.verify_expected_team_id(team, 'new-team')
teams = self.get_teams_list(user=user)
self.assertIn("New Team", [team['name'] for team in teams['results']])
assert 'New Team' in [team['name'] for team in teams['results']]
def _expected_team_id(self, team, expected_prefix):
""" Return the team id that we'd expect given this team data and this prefix. """
@@ -1109,9 +1098,9 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
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'], self._expected_team_id(team, expected_prefix))
assert 'id' in team
assert 'discussion_topic_id' in team
assert team['id'] == self._expected_team_id(team, expected_prefix)
def test_naming(self):
new_teams = [
@@ -1121,7 +1110,7 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
# 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'])
assert 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')
@@ -1161,10 +1150,8 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
),
user='student_enrolled'
)
self.assertEqual(
"You are already in a team in this teamset.",
json.loads(response.content.decode('utf-8'))["user_message"]
)
assert 'You are already in a team in this teamset.' ==\
json.loads(response.content.decode('utf-8'))['user_message']
@patch('lms.djangoapps.teams.views.can_user_create_team_in_topic', return_value=False)
@patch('lms.djangoapps.teams.views.has_specific_teamset_access', return_value=True)
@@ -1179,10 +1166,8 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
),
user='student_enrolled_not_on_team'
)
self.assertEqual(
"You can't create a team in an instructor managed topic.",
json.loads(response.content.decode('utf-8'))["user_message"]
)
assert "You can't create a team in an instructor managed topic." ==\
json.loads(response.content.decode('utf-8'))['user_message']
@ddt.data('staff', 'course_staff', 'community_ta')
def test_privileged_create_multiple_teams(self, user):
@@ -1249,26 +1234,17 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
del team['membership']
# 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()
)
assert parser.parse(team['last_activity_at']).date() == datetime.utcnow().replace(tzinfo=pytz.utc).date()
del team['last_activity_at']
# Verify that the creating user gets added to the team.
self.assertEqual(len(team_membership), 1)
assert len(team_membership) == 1
member = team_membership[0]['user']
self.assertEqual(member['username'], creator)
assert member['username'] == creator
self.assertEqual(team, {
'name': 'Fully specified team',
'language': 'fr',
'country': 'CA',
'topic_id': 'topic_1',
'course_id': str(self.test_course_1.id),
'description': 'Another fantastic team',
'organization_protected': False,
})
assert team == {'name': 'Fully specified team', 'language': 'fr', 'country': 'CA', 'topic_id': 'topic_1',
'course_id': str(self.test_course_1.id), 'description': 'Another fantastic team',
'organization_protected': False}
@ddt.data('staff', 'course_staff', 'community_ta')
def test_membership_staff_creator(self, user):
@@ -1280,7 +1256,7 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
description="Another fantastic team",
), user=user)
self.assertEqual(team['membership'], [])
assert team['membership'] == []
@ddt.unpack
@ddt.data(
@@ -1310,7 +1286,7 @@ class TestCreateTeamAPI(EventTestMixin, TeamAPITestCase):
user=user
)
if msg:
self.assertEqual(msg, response.json()['user_message'])
assert msg == response.json()['user_message']
@ddt.ddt
@@ -1330,9 +1306,9 @@ class TestDetailTeamAPI(TeamAPITestCase):
def test_access(self, user, status):
team = self.get_team_detail(self.solar_team.team_id, status, user=user)
if status == 200:
self.assertEqual(team['description'], self.solar_team.description)
self.assertEqual(team['discussion_topic_id'], self.solar_team.discussion_topic_id)
self.assertEqual(parser.parse(team['last_activity_at']), LAST_ACTIVITY_AT)
assert team['description'] == self.solar_team.description
assert team['discussion_topic_id'] == self.solar_team.discussion_topic_id
assert parser.parse(team['last_activity_at']) == LAST_ACTIVITY_AT
def test_does_not_exist(self):
self.get_team_detail('no_such_team', 404)
@@ -1371,7 +1347,7 @@ class TestDetailTeamAPI(TeamAPITestCase):
user=requesting_user
)
if expected_response == 200:
self.assertEqual(team['name'], self.masters_only_team.name)
assert team['name'] == self.masters_only_team.name
@ddt.unpack
@ddt.data(
@@ -1394,7 +1370,7 @@ class TestDetailTeamAPI(TeamAPITestCase):
user=requesting_user
)
if expected_response == 200:
self.assertEqual(team['name'], self.team_1_in_private_teamset_1.name)
assert team['name'] == self.team_1_in_private_teamset_1.name
@ddt.ddt
@@ -1414,12 +1390,12 @@ class TestDeleteTeamAPI(EventTestMixin, TeamAPITestCase):
def test_access(self, user, status):
team_list = self.get_teams_list(user='course_staff', expected_status=200)
previous_count = team_list['count']
self.assertIn(self.solar_team.team_id, [result['id'] for result in team_list.get('results')])
assert self.solar_team.team_id in [result['id'] for result in team_list.get('results')]
self.delete_team(self.solar_team.team_id, status, user=user)
team_list = self.get_teams_list(user='course_staff', expected_status=200)
self.assertEqual(team_list['count'], previous_count - 1)
self.assertNotIn(self.solar_team.team_id, [result['id'] for result in team_list.get('results')])
assert team_list['count'] == (previous_count - 1)
assert self.solar_team.team_id not in [result['id'] for result in team_list.get('results')]
self.assert_event_emitted(
'edx.team.deleted',
team_id=self.solar_team.team_id,
@@ -1439,12 +1415,12 @@ class TestDeleteTeamAPI(EventTestMixin, TeamAPITestCase):
def test_access_forbidden(self, user, status):
team_list = self.get_teams_list(user='course_staff', expected_status=200)
previous_count = team_list['count']
self.assertIn(self.solar_team.team_id, [result['id'] for result in team_list.get('results')])
assert self.solar_team.team_id in [result['id'] for result in team_list.get('results')]
self.delete_team(self.solar_team.team_id, status, user=user)
team_list = self.get_teams_list(user='course_staff', expected_status=200)
self.assertEqual(team_list['count'], previous_count)
self.assertIn(self.solar_team.team_id, [result['id'] for result in team_list.get('results')])
assert team_list['count'] == previous_count
assert self.solar_team.team_id in [result['id'] for result in team_list.get('results')]
@ddt.data(
(None, 401),
@@ -1458,7 +1434,7 @@ class TestDeleteTeamAPI(EventTestMixin, TeamAPITestCase):
self.delete_team('nonexistent', 404)
def test_memberships_deleted(self):
self.assertEqual(CourseTeamMembership.objects.filter(team=self.solar_team).count(), 1)
assert CourseTeamMembership.objects.filter(team=self.solar_team).count() == 1
self.delete_team(self.solar_team.team_id, 204, user='staff')
self.assert_event_emitted(
'edx.team.deleted',
@@ -1470,7 +1446,7 @@ class TestDeleteTeamAPI(EventTestMixin, TeamAPITestCase):
remove_method='team_deleted',
user_id=self.users['student_enrolled'].id
)
self.assertEqual(CourseTeamMembership.objects.filter(team=self.solar_team).count(), 0)
assert CourseTeamMembership.objects.filter(team=self.solar_team).count() == 0
@ddt.unpack
@ddt.data(
@@ -1534,7 +1510,7 @@ class TestUpdateTeamAPI(EventTestMixin, TeamAPITestCase):
prev_name = self.solar_team.name
team = self.patch_team_detail(self.solar_team.team_id, status, {'name': 'foo'}, user=user)
if status == 200:
self.assertEqual(team['name'], 'foo')
assert team['name'] == 'foo'
self.assert_event_emitted(
'edx.team.changed',
team_id=self.solar_team.team_id,
@@ -1609,7 +1585,7 @@ class TestUpdateTeamAPI(EventTestMixin, TeamAPITestCase):
user=requesting_user
)
if expected_status == 200:
self.assertEqual(team['name'], 'foo')
assert team['name'] == 'foo'
@ddt.unpack
@ddt.data(
@@ -1632,7 +1608,7 @@ class TestUpdateTeamAPI(EventTestMixin, TeamAPITestCase):
user=requesting_user
)
if expected_status == 200:
self.assertEqual(team['name'], 'foo')
assert team['name'] == 'foo'
@patch.dict(settings.FEATURES, {'ENABLE_ORA_TEAM_SUBMISSIONS': True})
@@ -1701,12 +1677,12 @@ class TestTeamAssignmentsView(TeamAPITestCase):
if expected_status == 200:
# I successful, I get back the assignments for a team
self.assertEqual(len(assignments), len(self.team_assignments))
assert len(assignments) == len(self.team_assignments)
# ... with the right data structure
for assignment in assignments:
self.assertIn('display_name', assignment.keys())
self.assertIn('location', assignment.keys())
assert 'display_name' in assignment.keys()
assert 'location' in assignment.keys()
def test_get_assignments_bad_team(self):
# Given a bad team is supplied
@@ -1746,7 +1722,7 @@ class TestListTopicsAPI(TeamAPITestCase):
def test_access(self, user, status, expected_topics_count):
topics = self.get_topics_list(status, {'course_id': str(self.test_course_1.id)}, user=user)
if status == 200:
self.assertEqual(topics['count'], expected_topics_count)
assert topics['count'] == expected_topics_count
@ddt.data('A+BOGUS+COURSE', 'A/BOGUS/COURSE')
def test_invalid_course_key(self, course_id):
@@ -1784,8 +1760,8 @@ class TestListTopicsAPI(TeamAPITestCase):
data['order_by'] = field
topics = self.get_topics_list(status, data, user='student_enrolled')
if status == 200:
self.assertEqual(names, [topic['name'] for topic in topics['results']])
self.assertEqual(topics['sort_order'], expected_ordering)
assert names == [topic['name'] for topic in topics['results']]
assert topics['sort_order'] == expected_ordering
def test_order_by_team_count_secondary(self):
"""
@@ -1824,7 +1800,7 @@ class TestListTopicsAPI(TeamAPITestCase):
},
user='student_enrolled'
)
self.assertEqual(["Wind Power", u'Sólar power'], [topic['name'] for topic in topics['results']])
assert ['Wind Power', u'Sólar power'] == [topic['name'] for topic in topics['results']]
# Coal and Nuclear are tied, so they are alphabetically sorted.
topics = self.get_topics_list(
@@ -1836,7 +1812,7 @@ class TestListTopicsAPI(TeamAPITestCase):
},
user='student_enrolled'
)
self.assertEqual(["Coal Power", "Nuclear Power"], [topic['name'] for topic in topics['results']])
assert ['Coal Power', 'Nuclear Power'] == [topic['name'] for topic in topics['results']]
def test_pagination(self):
response = self.get_topics_list(
@@ -1847,15 +1823,15 @@ class TestListTopicsAPI(TeamAPITestCase):
user='student_enrolled'
)
self.assertEqual(2, len(response['results']))
self.assertIn('next', response)
self.assertIn('previous', response)
self.assertIsNone(response['previous'])
self.assertIsNotNone(response['next'])
assert 2 == len(response['results'])
assert 'next' in response
assert 'previous' in response
assert response['previous'] is None
assert response['next'] is not None
def test_default_ordering(self):
response = self.get_topics_list(data={'course_id': str(self.test_course_1.id)})
self.assertEqual(response['sort_order'], 'name')
assert response['sort_order'] == 'name'
def test_team_count(self):
"""Test that team_count is included for each topic"""
@@ -1864,11 +1840,11 @@ class TestListTopicsAPI(TeamAPITestCase):
user='student_enrolled'
)
for topic in response['results']:
self.assertIn('team_count', topic)
assert 'team_count' in topic
if topic['id'] in ('topic_0', 'topic_1', 'topic_2'):
self.assertEqual(topic['team_count'], 1)
assert topic['team_count'] == 1
else:
self.assertEqual(topic['team_count'], 0)
assert topic['team_count'] == 0
@ddt.unpack
@ddt.data(
@@ -1892,7 +1868,7 @@ class TestListTopicsAPI(TeamAPITestCase):
private_teamsets_returned = [
topic['name'] for topic in topics['results'] if topic['type'] == 'private_managed'
]
self.assertEqual(len(private_teamsets_returned), expected_private_teamsets)
assert len(private_teamsets_returned) == expected_private_teamsets
@ddt.unpack
@ddt.data(
@@ -1909,7 +1885,7 @@ class TestListTopicsAPI(TeamAPITestCase):
user=requesting_user
)
private_teamset_1 = [topic for topic in topics['results'] if topic['name'] == 'private_topic_1_name'][0]
self.assertEqual(private_teamset_1['team_count'], expected_team_count)
assert private_teamset_1['team_count'] == expected_team_count
@ddt.ddt
@@ -1930,7 +1906,7 @@ class TestDetailTopicAPI(TeamAPITestCase):
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)
assert field in topic
@ddt.data('A+BOGUS+COURSE', 'A/BOGUS/COURSE')
def test_invalid_course_id(self, course_id):
@@ -1945,13 +1921,13 @@ class TestDetailTopicAPI(TeamAPITestCase):
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)
assert 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'], 1)
assert topic['team_count'] == 1
topic = self.get_topic_detail(topic_id='topic_2', course_id=self.test_course_1.id)
self.assertEqual(topic['team_count'], 1)
assert topic['team_count'] == 1
topic = self.get_topic_detail(topic_id='topic_3', course_id=self.test_course_1.id)
self.assertEqual(topic['team_count'], 0)
assert topic['team_count'] == 0
@ddt.unpack
@ddt.data(
@@ -1976,8 +1952,8 @@ class TestDetailTopicAPI(TeamAPITestCase):
user=requesting_user
)
if expected_status == 200:
self.assertEqual(topic['name'], 'private_topic_1_name')
self.assertEqual(topic['team_count'], expected_team_count)
assert topic['name'] == 'private_topic_1_name'
assert topic['team_count'] == expected_team_count
@ddt.ddt
@@ -1998,8 +1974,8 @@ class TestListMembershipAPI(TeamAPITestCase):
def test_access(self, user, status):
membership = self.get_membership_list(status, {'team_id': self.solar_team.team_id}, user=user)
if status == 200:
self.assertEqual(membership['count'], 1)
self.assertEqual(membership['results'][0]['user']['username'], self.users['student_enrolled'].username)
assert membership['count'] == 1
assert membership['results'][0]['user']['username'] == self.users['student_enrolled'].username
@ddt.data(
(None, 401, False),
@@ -2016,10 +1992,10 @@ class TestListMembershipAPI(TeamAPITestCase):
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)
self.assertEqual(membership['results'][0]['team']['team_id'], self.solar_team.team_id)
assert membership['count'] == 1
assert membership['results'][0]['team']['team_id'] == self.solar_team.team_id
else:
self.assertEqual(membership['count'], 0)
assert membership['count'] == 0
@ddt.data(
('student_masters', True),
@@ -2042,10 +2018,10 @@ class TestListMembershipAPI(TeamAPITestCase):
"""
membership = self.get_membership_list(200, {'username': 'student_masters'}, user=user)
if can_see_bubble_team:
self.assertEqual(membership['count'], 1)
self.assertEqual(membership['results'][0]['team']['team_id'], self.masters_only_team.team_id)
assert membership['count'] == 1
assert membership['results'][0]['team']['team_id'] == self.masters_only_team.team_id
else:
self.assertEqual(membership['count'], 0)
assert membership['count'] == 0
@ddt.unpack
@ddt.data(
@@ -2070,14 +2046,14 @@ class TestListMembershipAPI(TeamAPITestCase):
memberships = self.get_membership_list(200, {'username': 'student_on_team_1_private_set_1'}, user=user)
team_ids = [membership['team']['team_id'] for membership in memberships['results']]
if can_see_private_team:
self.assertEqual(len(team_ids), 2)
self.assertIn(self.team_1_in_private_teamset_1.team_id, team_ids)
self.assertIn(self.masters_only_team.team_id, team_ids)
assert len(team_ids) == 2
assert self.team_1_in_private_teamset_1.team_id in team_ids
assert self.masters_only_team.team_id in team_ids
elif can_see_any_teams:
self.assertEqual(len(team_ids), 1)
self.assertIn(self.masters_only_team.team_id, team_ids)
assert len(team_ids) == 1
assert self.masters_only_team.team_id in team_ids
else:
self.assertEqual(len(team_ids), 0)
assert len(team_ids) == 0
@ddt.unpack
@ddt.data(
@@ -2104,7 +2080,7 @@ class TestListMembershipAPI(TeamAPITestCase):
)
if expected_response == 200:
users = [membership['user']['username'] for membership in memberships['results']]
self.assertEqual(users, ['student_on_team_1_private_set_1'])
assert users == ['student_on_team_1_private_set_1']
@ddt.data(
('student_enrolled_both_courses_other_team', 'TestX/TS101/Test_Course', 200, 'Nuclear Team'),
@@ -2123,8 +2099,8 @@ class TestListMembershipAPI(TeamAPITestCase):
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)
assert membership['count'] == 1
assert membership['results'][0]['team']['team_id'] == self.test_team_name_id_map[team_name].team_id
@ddt.data(
('TestX/TS101/Test_Course', 200),
@@ -2134,12 +2110,12 @@ class TestListMembershipAPI(TeamAPITestCase):
def test_course_filter_with_team_id(self, course_id, status):
membership = self.get_membership_list(status, {'team_id': self.solar_team.team_id, 'course_id': course_id})
if status == 200:
self.assertEqual(membership['count'], 1)
self.assertEqual(membership['results'][0]['team']['team_id'], self.solar_team.team_id)
assert membership['count'] == 1
assert membership['results'][0]['team']['team_id'] == self.solar_team.team_id
def test_nonexistent_user(self):
response = self.get_membership_list(200, {'username': 'this-user-will-not-exist-&&&&#!^'})
self.assertEqual(response['count'], 0)
assert response['count'] == 0
def test_bad_course_id(self):
self.get_membership_list(404, {'course_id': 'no_such_course'})
@@ -2179,11 +2155,11 @@ class TestListMembershipAPI(TeamAPITestCase):
filters['username'] = other_username
result = self.get_membership_list(200, filters)
self.assertEqual(result['count'], 1 if filter_username else 2)
assert result['count'] == (1 if filter_username else 2)
usernames = {enrollment['user']['username'] for enrollment in result['results']}
self.assertIn(other_username, usernames)
assert other_username in usernames
if not filter_username:
self.assertIn('student_enrolled', usernames)
assert 'student_enrolled' in usernames
def test_filter_teamset_team_id(self):
# team_id and teamset_id are mutually exclusive
@@ -2246,7 +2222,7 @@ class TestListMembershipAPI(TeamAPITestCase):
)
if expected_response == 200:
returned_users = {membership['user']['username'] for membership in memberships['results']}
self.assertEqual(returned_users, expected_users)
assert returned_users == expected_users
@ddt.unpack
@ddt.data(
@@ -2280,7 +2256,7 @@ class TestListMembershipAPI(TeamAPITestCase):
)
def test_access_filter_teamset__open_teamset(self, user, expected_response, expected_usernames):
# topic_3 has no teams
self.assertFalse(CourseTeam.objects.filter(topic_id='topic_3').exists())
assert not CourseTeam.objects.filter(topic_id='topic_3').exists()
memberships = self.get_membership_list(
expected_response,
{
@@ -2290,10 +2266,10 @@ class TestListMembershipAPI(TeamAPITestCase):
user=user
)
if expected_response == 200:
self.assertEqual(memberships['count'], 0)
assert memberships['count'] == 0
# topic_0 has teams
self.assertTrue(CourseTeam.objects.filter(topic_id='topic_0').exists())
assert CourseTeam.objects.filter(topic_id='topic_0').exists()
memberships = self.get_membership_list(
expected_response,
{
@@ -2304,7 +2280,7 @@ class TestListMembershipAPI(TeamAPITestCase):
)
if expected_response == 200:
returned_users = {membership['user']['username'] for membership in memberships['results']}
self.assertEqual(returned_users, expected_usernames)
assert returned_users == expected_usernames
@ddt.ddt
@@ -2333,10 +2309,10 @@ class TestCreateMembershipAPI(EventTestMixin, TeamAPITestCase):
user=user
)
if status == 200:
self.assertEqual(membership['user']['username'], self.users['student_enrolled_not_on_team'].username)
self.assertEqual(membership['team']['team_id'], self.solar_team.team_id)
assert membership['user']['username'] == self.users['student_enrolled_not_on_team'].username
assert membership['team']['team_id'] == self.solar_team.team_id
memberships = self.get_membership_list(200, {'team_id': self.solar_team.team_id})
self.assertEqual(memberships['count'], 2)
assert memberships['count'] == 2
add_method = 'joined_from_team_view' if user == 'student_enrolled_not_on_team' else 'added_by_another_user'
@@ -2351,11 +2327,11 @@ class TestCreateMembershipAPI(EventTestMixin, TeamAPITestCase):
def test_no_username(self):
response = self.post_create_membership(400, {'team_id': self.solar_team.team_id})
self.assertIn('username', json.loads(response.content.decode('utf-8'))['field_errors'])
assert 'username' in json.loads(response.content.decode('utf-8'))['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.decode('utf-8'))['field_errors'])
assert 'team_id' in json.loads(response.content.decode('utf-8'))['field_errors']
@ddt.data('staff', 'student_enrolled')
def test_bad_team(self, user):
@@ -2408,7 +2384,7 @@ class TestCreateMembershipAPI(EventTestMixin, TeamAPITestCase):
user=user
)
if expected_message:
self.assertIn(expected_message, json.loads(response.content.decode('utf-8'))['developer_message'])
assert expected_message in json.loads(response.content.decode('utf-8'))['developer_message']
@ddt.unpack
@ddt.data(
@@ -2440,7 +2416,7 @@ class TestCreateMembershipAPI(EventTestMixin, TeamAPITestCase):
self.build_membership_data('student_enrolled', self.solar_team),
user=user
)
self.assertIn('already a member', json.loads(response.content.decode('utf-8'))['developer_message'])
assert 'already a member' in json.loads(response.content.decode('utf-8'))['developer_message']
def test_join_second_team_in_course(self):
"""
@@ -2460,7 +2436,7 @@ class TestCreateMembershipAPI(EventTestMixin, TeamAPITestCase):
self.build_membership_data('student_unenrolled', self.solar_team),
user=user
)
self.assertIn('not enrolled', json.loads(response.content.decode('utf-8'))['developer_message'])
assert 'not enrolled' in json.loads(response.content.decode('utf-8'))['developer_message']
def test_over_max_team_size_in_course_2(self):
response = self.post_create_membership(
@@ -2468,7 +2444,7 @@ class TestCreateMembershipAPI(EventTestMixin, TeamAPITestCase):
self.build_membership_data('student_enrolled_other_course_not_on_team', self.another_team),
user='student_enrolled_other_course_not_on_team'
)
self.assertIn('full', json.loads(response.content.decode('utf-8'))['developer_message'])
assert 'full' in json.loads(response.content.decode('utf-8'))['developer_message']
@ddt.ddt
@@ -2823,7 +2799,7 @@ class TestBulkMembershipManagement(TeamAPITestCase):
user='staff'
)
response_text = json.loads(response.content.decode('utf-8'))
self.assertEqual(response_text['message'], '1 learners were affected.')
assert response_text['message'] == '1 learners were affected.'
def test_upload_invalid_teamset(self):
self.create_and_enroll_student(username='a_user')
@@ -2863,12 +2839,9 @@ class TestBulkMembershipManagement(TeamAPITestCase):
self.client.login(username=self.users['course_staff'].username, password=self.users['course_staff'].password)
response = self.make_call(reverse('team_membership_bulk_management', args=[self.good_course_id]),
201, method='post', data={'csv': csv_file}, user='staff')
self.assertEqual(
CourseTeam.objects.filter(name='team 2', course_id=self.test_course_1.id).count(),
1
)
assert CourseTeam.objects.filter(name='team 2', course_id=self.test_course_1.id).count() == 1
response_text = json.loads(response.content.decode('utf-8'))
self.assertEqual(response_text['message'], '3 learners were affected.')
assert response_text['message'] == '3 learners were affected.'
def test_upload_non_existing_user(self):
csv_content = 'user,mode,topic_0' + '\n'
@@ -2973,7 +2946,7 @@ class TestBulkMembershipManagement(TeamAPITestCase):
)
response_text = json.loads(response.content.decode('utf-8'))
expected_error = 'Team team wind power cannot have Masters track users mixed with users in other tracks.'
self.assertEqual(response_text['errors'][0], expected_error)
assert response_text['errors'][0] == expected_error
def test_upload_learners_exceed_max_team_size(self):
csv_content = 'user,mode,topic_0,topic_1' + '\n'
@@ -2993,20 +2966,14 @@ class TestBulkMembershipManagement(TeamAPITestCase):
data={'csv': csv_file}, user='staff'
)
response_text = json.loads(response.content.decode('utf-8'))
self.assertEqual(
response_text['errors'][0],
'New membership for team {} would exceed max size of {}.'.format(team1, 3)
)
assert response_text['errors'][0] == 'New membership for team {} would exceed max size of {}.'.format(team1, 3)
def test_deletion_via_upload_csv(self):
# create a team membership that will be used further down
self.test_create_membership_via_upload()
username = 'a_user'
topic_0_id = 'topic_0'
self.assertTrue(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__topic_id=topic_0_id
).exists())
assert CourseTeamMembership.objects.filter(user_id=self.users[username].id, team__topic_id=topic_0_id).exists()
csv_content = 'user,mode,{},topic_1'.format(topic_0_id) + '\n'
csv_content += '{},audit'.format(username)
@@ -3019,10 +2986,8 @@ class TestBulkMembershipManagement(TeamAPITestCase):
data={'csv': csv_file},
user='staff'
)
self.assertFalse(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__topic_id=topic_0_id
).exists())
assert not CourseTeamMembership.objects\
.filter(user_id=self.users[username].id, team__topic_id=topic_0_id).exists()
def test_reassignment_via_upload_csv(self):
# create a team membership that will be used further down
@@ -3031,11 +2996,8 @@ class TestBulkMembershipManagement(TeamAPITestCase):
topic_0_id = 'topic_0'
nuclear_team_name = 'team nuclear power'
windpower_team_name = 'team wind power'
self.assertTrue(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__topic_id=topic_0_id,
team__name=windpower_team_name
).exists())
assert CourseTeamMembership.objects\
.filter(user_id=self.users[username].id, team__topic_id=topic_0_id, team__name=windpower_team_name).exists()
csv_content = 'user,mode,{}'.format(topic_0_id) + '\n'
csv_content += '{0},audit,{1}'.format(username, nuclear_team_name)
csv_file = SimpleUploadedFile('test_file.csv', csv_content.encode('utf8'), content_type='text/csv')
@@ -3047,16 +3009,13 @@ class TestBulkMembershipManagement(TeamAPITestCase):
data={'csv': csv_file},
user='staff'
)
self.assertFalse(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__topic_id=topic_0_id,
team__name=windpower_team_name
).exists())
self.assertTrue(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__topic_id=topic_0_id,
team__name=nuclear_team_name
).exists())
assert not CourseTeamMembership.objects.filter(user_id=self.users[username].id,
team__topic_id=topic_0_id,
team__name=windpower_team_name).exists()
assert CourseTeamMembership.objects.filter(user_id=self.users[username].id,
team__topic_id=topic_0_id,
team__name=nuclear_team_name).exists()
def test_upload_file_not_changed_csv(self):
# create a team membership that will be used further down
@@ -3064,10 +3023,7 @@ class TestBulkMembershipManagement(TeamAPITestCase):
username = 'a_user'
topic_0_id = 'topic_0'
nuclear_team_name = 'team wind power'
self.assertEqual(len(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__topic_id=topic_0_id
)), 1)
assert len(CourseTeamMembership.objects.filter(user_id=self.users[username].id, team__topic_id=topic_0_id)) == 1
csv_content = 'user,mode,{}'.format(topic_0_id) + '\n'
csv_content += '{0},audit,{1}'.format(username, nuclear_team_name)
csv_file = SimpleUploadedFile('test_file.csv', csv_content.encode('utf8'), content_type='text/csv')
@@ -3080,14 +3036,10 @@ class TestBulkMembershipManagement(TeamAPITestCase):
data={'csv': csv_file},
user='staff'
)
self.assertEqual(len(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__name=nuclear_team_name
)), 1)
self.assertTrue(CourseTeamMembership.objects.filter(
user_id=self.users[username].id,
team__name=nuclear_team_name
).exists())
assert len(CourseTeamMembership.objects.filter(user_id=self.users[username].id,
team__name=nuclear_team_name)) == 1
assert CourseTeamMembership.objects.filter(user_id=self.users[username].id,
team__name=nuclear_team_name).exists()
def test_create_membership_via_upload_using_external_key(self):
self.create_and_enroll_student(username='a_user', external_key='a_user_external_key')
@@ -3103,7 +3055,7 @@ class TestBulkMembershipManagement(TeamAPITestCase):
user='staff'
)
response_text = json.loads(response.content.decode('utf-8'))
self.assertEqual(response_text['message'], '1 learners were affected.')
assert response_text['message'] == '1 learners were affected.'
def test_create_membership_via_upload_using_external_key_invalid(self):
self.create_and_enroll_student(username='a_user', external_key='a_user_external_key')
@@ -3119,10 +3071,7 @@ class TestBulkMembershipManagement(TeamAPITestCase):
user='staff'
)
response_text = json.loads(response.content.decode('utf-8'))
self.assertEqual(
response_text['errors'],
['User name/email/external key: a_user_external_key_invalid does not exist.']
)
assert response_text['errors'] == ['User name/email/external key: a_user_external_key_invalid does not exist.']
def test_upload_non_ascii(self):
csv_content = 'user,mode,topic_0' + '\n'
@@ -3139,14 +3088,8 @@ class TestBulkMembershipManagement(TeamAPITestCase):
user='staff'
)
team = self.users[user_name].teams.first()
self.assertEqual(
team.name,
team_name
)
self.assertEqual(
[user.username for user in team.users.all()],
[user_name]
)
assert team.name == team_name
assert [user.username for user in team.users.all()] == [user_name]
def test_upload_assign_masters_learner_to_non_protected_team(self):
"""
@@ -3171,4 +3114,4 @@ class TestBulkMembershipManagement(TeamAPITestCase):
expected_message = 'Team {} cannot have Masters track users mixed with users in other tracks.'.format(
team.name
)
self.assertEqual(response_text['errors'][0], expected_message)
assert response_text['errors'][0] == expected_message

View File

@@ -3,7 +3,7 @@ Tests for management command backfill_sso_verifications_for_old_account_links
"""
from mock import patch
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@@ -33,18 +33,18 @@ class TestBackfillSSOVerificationsCommand(TestCase):
self.user1 = self.user_social_auth1.user
def test_fails_without_required_param(self):
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
call_command('backfill_sso_verifications_for_old_account_links')
def test_fails_without_named_provider_config(self):
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
call_command('backfill_sso_verifications_for_old_account_links', '--provider-slug', 'gatech')
def test_sso_updated_single_user(self):
self.assertTrue(SSOVerification.objects.count() == 0) # lint-amnesty, pylint: disable=wrong-assert-type
assert SSOVerification.objects.count() == 0
call_command('backfill_sso_verifications_for_old_account_links', '--provider-slug', self.provider.provider_id)
self.assertTrue(SSOVerification.objects.count() > 0) # lint-amnesty, pylint: disable=wrong-assert-type
self.assertEqual(SSOVerification.objects.get().user.id, self.user1.id)
assert SSOVerification.objects.count() > 0
assert SSOVerification.objects.get().user.id == self.user1.id
def test_performance(self):
# TODO
@@ -55,7 +55,7 @@ class TestBackfillSSOVerificationsCommand(TestCase):
def test_signal_called(self):
with patch('openedx.core.djangoapps.signals.signals.LEARNER_NOW_VERIFIED.send_robust') as mock_signal:
call_command('backfill_sso_verifications_for_old_account_links', '--provider-slug', self.provider.provider_id) # lint-amnesty, pylint: disable=line-too-long
self.assertEqual(mock_signal.call_count, 1)
assert mock_signal.call_count == 1
def test_fine_with_multiple_verification_records(self):
"""
@@ -69,6 +69,6 @@ class TestBackfillSSOVerificationsCommand(TestCase):
status='approved',
user=self.user1,
)
self.assertEqual(SSOVerification.objects.count(), 2)
assert SSOVerification.objects.count() == 2
call_command('backfill_sso_verifications_for_old_account_links', '--provider-slug', self.provider.provider_id)
self.assertEqual(SSOVerification.objects.count(), 2)
assert SSOVerification.objects.count() == 2

View File

@@ -7,7 +7,7 @@ Tests for django admin commands in the verify_student module
import logging
import os
import tempfile
import pytest
import six
from django.core.management import CommandError, call_command
from django.test import TestCase
@@ -50,11 +50,11 @@ class TestVerifyStudentCommand(TestCase):
"""
Tests that the manual_verifications management command executes successfully
"""
self.assertEqual(ManualVerification.objects.filter(status='approved').count(), 0)
assert ManualVerification.objects.filter(status='approved').count() == 0
call_command('manual_verifications', '--email-ids-file', self.tmp_file_path)
self.assertEqual(ManualVerification.objects.filter(status='approved').count(), 3)
assert ManualVerification.objects.filter(status='approved').count() == 3
def test_manual_verifications_created_date(self):
"""
@@ -113,5 +113,5 @@ class TestVerifyStudentCommand(TestCase):
"""
Verify command raises the CommandError for invalid file path.
"""
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
call_command('manual_verifications', '--email-ids-file', u'invalid/email_id/file/path')

View File

@@ -50,7 +50,7 @@ class TestPopulateExpiryDate(MockS3BotoMixin, TestCase):
# Check that the expiry_date for approved verification is not changed when it is already present
verification_expiry_date = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk).expiry_date
self.assertEqual(verification_expiry_date, expiry_date)
assert verification_expiry_date == expiry_date
def test_recent_approved_verification(self):
"""
@@ -74,7 +74,7 @@ class TestPopulateExpiryDate(MockS3BotoMixin, TestCase):
# Check that the expiry_date date set for verification is not for the outdated approved verification
expiry_date = SoftwareSecurePhotoVerification.objects.get(pk=outdated_verification.pk).expiry_date
self.assertIsNone(expiry_date)
assert expiry_date is None
def test_approved_verification_expiry_date(self):
"""
@@ -102,7 +102,7 @@ class TestPopulateExpiryDate(MockS3BotoMixin, TestCase):
# Confirm that expiry_date set for approved verification is correct
approved_verification = SoftwareSecurePhotoVerification.objects.get(pk=approved_verification.pk)
self.assertEqual(approved_verification.expiry_date, expected_date)
assert approved_verification.expiry_date == expected_date
def test_no_approved_verification_found(self):
"""

View File

@@ -76,11 +76,11 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
call_command('send_verification_expiry_email')
# Check that only one email is sent
self.assertEqual(len(mail.outbox), 1)
assert len(mail.outbox) == 1
# Verify that the email is not sent to the out of range verification
expiry_email_date = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk).expiry_email_date
self.assertIsNone(expiry_email_date)
assert expiry_email_date is None
def test_expiry_email_date_range(self):
"""
@@ -99,7 +99,7 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
# Check that email is sent even if the verification is not in expiration_date range but matches
# the criteria to resend email
self.assertEqual(len(mail.outbox), 1)
assert len(mail.outbox) == 1
def test_most_recent_verification(self):
"""
@@ -116,7 +116,7 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
# Check that the expiry_email_date is not set for the outdated verification
expiry_email_date = SoftwareSecurePhotoVerification.objects.get(pk=outdated_verification.pk).expiry_email_date
self.assertIsNone(expiry_email_date)
assert expiry_email_date is None
def test_send_verification_expiry_email(self):
"""
@@ -132,8 +132,8 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
expected_date = now()
attempt = SoftwareSecurePhotoVerification.objects.get(user_id=verification.user_id)
self.assertEqual(attempt.expiry_email_date.date(), expected_date.date())
self.assertEqual(len(mail.outbox), 1)
assert attempt.expiry_email_date.date() == expected_date.date()
assert len(mail.outbox) == 1
def test_verification_expiry_email_not_sent_valid_ssov(self):
"""
@@ -145,7 +145,7 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
SSOVerification.objects.create(user=expired_ssp_verification.user, status='approved')
call_command('send_verification_expiry_email')
self.assertEqual(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def test_verification_expiry_email_not_sent_valid_manual_verification(self):
"""
@@ -157,7 +157,7 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
ManualVerification.objects.create(user=expired_ssp_verification.user, status='approved')
call_command('send_verification_expiry_email')
self.assertEqual(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def test_email_already_sent(self):
"""
@@ -173,7 +173,7 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
call_command('send_verification_expiry_email')
self.assertEqual(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def test_no_verification_found(self):
"""
@@ -214,7 +214,7 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
u"This was a dry run, no email was sent. For the actual run email would have been sent "
u"to {} learner(s)".format(count)
))
self.assertEqual(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def test_not_enrolled_in_verified_course(self):
"""
@@ -235,8 +235,8 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
# check that after sending the default number of emails, the expiry_email_date is set to none for a
# user who is not enrolled in verified track
attempt = SoftwareSecurePhotoVerification.objects.get(pk=verification.id)
self.assertEqual(len(mail.outbox), 1)
self.assertIsNone(attempt.expiry_email_date)
assert len(mail.outbox) == 1
assert attempt.expiry_email_date is None
def test_number_of_emails_sent(self):
"""
@@ -264,8 +264,8 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
break
# expiry_email_date set to None means it no longer will be filtered hence no emails will be sent in future
self.assertIsNone(SoftwareSecurePhotoVerification.objects.get(pk=verification.id).expiry_email_date)
self.assertEqual(len(mail.outbox), self.default_no_of_emails)
assert SoftwareSecurePhotoVerification.objects.get(pk=verification.id).expiry_email_date is None
assert len(mail.outbox) == self.default_no_of_emails
@override_settings(VERIFICATION_EXPIRY_EMAIL={'RESEND_DAYS': 15, 'DAYS_RANGE': 1, 'DEFAULT_EMAILS': 0})
def test_command_error(self):
@@ -299,6 +299,6 @@ class TestSendVerificationExpiryEmail(MockS3BotoMixin, TestCase):
for verification in verifications:
verification.refresh_from_db()
self.assertIsNone(verifications[0].expiry_email_date)
self.assertIsNotNone(verifications[1].expiry_email_date)
self.assertEqual(mock_ace.send.call_count, 2)
assert verifications[0].expiry_email_date is None
assert verifications[1].expiry_email_date is not None
assert mock_ace.send.call_count == 2

View File

@@ -46,7 +46,7 @@ class TestPopulateExpiryationDate(MockS3BotoMixin, TestCase):
call_command('update_expiration_date')
# Check that the `expiration_date` is not changed
expiration_date = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk).expiration_date
self.assertEqual(expiration_date, expected_date)
assert expiration_date == expected_date
def test_expiration_date_updated(self):
"""
@@ -64,9 +64,9 @@ class TestPopulateExpiryationDate(MockS3BotoMixin, TestCase):
call_command('update_expiration_date')
updated_verification = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk)
# Check that the `expiration_date` is updated
self.assertEqual(updated_verification.expiration_date, expected_date)
assert updated_verification.expiration_date == expected_date
# Check that the `expiry_date` is set to NULL
self.assertEqual(updated_verification.expiry_date, None)
assert updated_verification.expiry_date is None
def test_expiration_date_updated_multiple_records(self):
"""
@@ -87,9 +87,9 @@ class TestPopulateExpiryationDate(MockS3BotoMixin, TestCase):
expected_date = updated_verification.created_at + timedelta(
days=settings.VERIFY_STUDENT["DAYS_GOOD_FOR"])
# Check that the `expiration_date` is updated
self.assertEqual(updated_verification.expiration_date, expected_date)
assert updated_verification.expiration_date == expected_date
# Check that the `expiry_date` is set to NULL
self.assertEqual(updated_verification.expiry_date, None)
assert updated_verification.expiry_date is None
def test_no_approved_verification_found(self):
"""

View File

@@ -42,8 +42,8 @@ class TestVerifyStudentCommand(MockS3BotoMixin, TestVerificationBase):
self.create_upload_and_submit_attempt_for_user()
# check to make sure we had two successes and two failures; otherwise we've got problems elsewhere
self.assertEqual(SoftwareSecurePhotoVerification.objects.filter(status="submitted").count(), 1)
self.assertEqual(SoftwareSecurePhotoVerification.objects.filter(status='must_retry').count(), 2)
assert SoftwareSecurePhotoVerification.objects.filter(status='submitted').count() == 1
assert SoftwareSecurePhotoVerification.objects.filter(status='must_retry').count() == 2
with self.immediate_on_commit():
call_command('retry_failed_photo_verifications')

View File

@@ -44,21 +44,21 @@ class TestVerificationBase(TestCase):
"""
# Not active before the created date
before = attempt.created_at - timedelta(minutes=1)
self.assertFalse(attempt.active_at_datetime(before))
assert not attempt.active_at_datetime(before)
# Active immediately after created date
after_created = attempt.created_at + timedelta(seconds=1)
self.assertTrue(attempt.active_at_datetime(after_created))
assert attempt.active_at_datetime(after_created)
# Active immediately before expiration date
expiration = attempt.expiration_datetime
before_expiration = expiration - timedelta(seconds=1)
self.assertTrue(attempt.active_at_datetime(before_expiration))
assert attempt.active_at_datetime(before_expiration)
# Not active after the expiration date
attempt.expiration_date = now() - timedelta(days=1)
attempt.save()
self.assertFalse(attempt.active_at_datetime(now()))
assert not attempt.active_at_datetime(now())
def submit_attempt(self, attempt):
with self.immediate_on_commit():

View File

@@ -46,7 +46,7 @@ class SoftwareSecureFakeViewDisabledTest(SoftwareSecureFakeViewTest):
'/verify_student/software-secure-fake-response'
)
self.assertEqual(response.status_code, 404)
assert response.status_code == 404
class SoftwareSecureFakeViewEnabledTest(SoftwareSecureFakeViewTest):
@@ -66,7 +66,7 @@ class SoftwareSecureFakeViewEnabledTest(SoftwareSecureFakeViewTest):
response = self.client.get(
'/verify_student/software-secure-fake-response'
)
self.assertEqual(response.status_code, 302)
assert response.status_code == 302
def test_get_method(self):
"""

View File

@@ -57,4 +57,4 @@ class TestProfEdVerification(ModuleStoreTestCase):
# For professional ed courses, expect that the student is NOT enrolled
# automatically in the course.
self.assertFalse(CourseEnrollment.is_enrolled(self.user, self.course_key))
assert not CourseEnrollment.is_enrolled(self.user, self.course_key)

View File

@@ -2,7 +2,7 @@
import base64
from datetime import datetime, timedelta
import pytest
import ddt
import mock
import requests.exceptions
@@ -110,22 +110,22 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
"""
user = UserFactory.create()
attempt = SoftwareSecurePhotoVerification(user=user)
self.assertEqual(attempt.status, PhotoVerification.STATUS.created)
assert attempt.status == PhotoVerification.STATUS.created
# These should all fail because we're in the wrong starting state.
self.assertRaises(VerificationException, attempt.submit)
self.assertRaises(VerificationException, attempt.approve)
self.assertRaises(VerificationException, attempt.deny)
self.assertRaises(VerificationException, attempt.mark_must_retry)
self.assertRaises(VerificationException, attempt.mark_submit)
pytest.raises(VerificationException, attempt.submit)
pytest.raises(VerificationException, attempt.approve)
pytest.raises(VerificationException, attempt.deny)
pytest.raises(VerificationException, attempt.mark_must_retry)
pytest.raises(VerificationException, attempt.mark_submit)
# Now let's fill in some values so that we can pass the mark_ready() call
attempt.mark_ready()
self.assertEqual(attempt.status, PhotoVerification.STATUS.ready)
assert attempt.status == PhotoVerification.STATUS.ready
# ready (can't approve or deny unless it's "submitted")
self.assertRaises(VerificationException, attempt.approve)
self.assertRaises(VerificationException, attempt.deny)
pytest.raises(VerificationException, attempt.approve)
pytest.raises(VerificationException, attempt.deny)
attempt.mark_must_retry()
attempt.mark_submit()
@@ -152,17 +152,17 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
attempt.approve()
# approved
self.assertRaises(VerificationException, attempt.submit)
self.assertRaises(VerificationException, attempt.mark_must_retry)
self.assertRaises(VerificationException, attempt.mark_submit)
pytest.raises(VerificationException, attempt.submit)
pytest.raises(VerificationException, attempt.mark_must_retry)
pytest.raises(VerificationException, attempt.mark_submit)
attempt.approve() # no-op
attempt.system_error("System error") # no-op, something processed it without error
attempt.deny(DENY_ERROR_MSG)
# denied
self.assertRaises(VerificationException, attempt.submit)
self.assertRaises(VerificationException, attempt.mark_must_retry)
self.assertRaises(VerificationException, attempt.mark_submit)
pytest.raises(VerificationException, attempt.submit)
pytest.raises(VerificationException, attempt.mark_must_retry)
pytest.raises(VerificationException, attempt.mark_submit)
attempt.deny(DENY_ERROR_MSG) # no-op
attempt.system_error("System error") # no-op, something processed it without error
attempt.approve()
@@ -183,23 +183,23 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
user.profile.name = u"Rusty \u01B4"
self.assertEqual(u"Clyde \u01B4", attempt.name)
assert u'Clyde ƴ' == attempt.name
def test_submissions(self):
"""Test that we set our status correctly after a submission."""
# Basic case, things go well.
attempt = self.create_upload_and_submit_attempt_for_user()
self.assertEqual(attempt.status, PhotoVerification.STATUS.submitted)
assert attempt.status == PhotoVerification.STATUS.submitted
# We post, but Software Secure doesn't like what we send for some reason
with patch('lms.djangoapps.verify_student.tasks.requests.post', new=mock_software_secure_post_error):
attempt = self.create_upload_and_submit_attempt_for_user()
self.assertEqual(attempt.status, PhotoVerification.STATUS.must_retry)
assert attempt.status == PhotoVerification.STATUS.must_retry
# We try to post, but run into an error (in this case a network connection error)
with patch('lms.djangoapps.verify_student.tasks.requests.post', new=mock_software_secure_post_unavailable):
attempt = self.create_upload_and_submit_attempt_for_user()
self.assertEqual(attempt.status, PhotoVerification.STATUS.must_retry)
assert attempt.status == PhotoVerification.STATUS.must_retry
@mock.patch.dict(settings.FEATURES, {'AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING': True})
def test_submission_while_testing_flag_is_true(self):
@@ -208,7 +208,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
is enabled.
"""
attempt = self.create_upload_and_submit_attempt_for_user()
self.assertEqual(attempt.photo_id_key, "fake-photo-id-key")
assert attempt.photo_id_key == 'fake-photo-id-key'
# pylint: disable=line-too-long
def test_parse_error_msg_success(self):
@@ -217,10 +217,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
attempt.status = PhotoVerification.STATUS.denied
attempt.error_msg = '[{"userPhotoReasons": ["Face out of view"]}, {"photoIdReasons": ["Photo hidden/No photo", "ID name not provided"]}]'
parsed_error_msg = attempt.parsed_error_msg()
self.assertEqual(
sorted(parsed_error_msg),
sorted(['id_image_missing_name', 'user_image_not_clear', 'id_image_not_clear'])
)
assert sorted(parsed_error_msg) == sorted(['id_image_missing_name', 'user_image_not_clear', 'id_image_not_clear'])
@ddt.data(
'Not Provided',
@@ -230,7 +227,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
def test_parse_error_msg_failure(self, msg):
user = UserFactory.create()
attempt = SoftwareSecurePhotoVerification.objects.create(user=user, status='denied', error_msg=msg)
self.assertEqual(attempt.parsed_error_msg(), [])
assert attempt.parsed_error_msg() == []
def test_active_at_datetime(self):
user = UserFactory.create()
@@ -246,7 +243,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
# No initial verification for the user
result = SoftwareSecurePhotoVerification.get_initial_verification(user=user)
self.assertIs(result, None)
assert result is None
# Make an initial verification with 'photo_id_key'
attempt = SoftwareSecurePhotoVerification(user=user, photo_id_key="dummy_photo_id_key")
@@ -256,7 +253,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
# Check that method 'get_initial_verification' returns the correct
# initial verification attempt
first_result = SoftwareSecurePhotoVerification.get_initial_verification(user=user)
self.assertIsNotNone(first_result)
assert first_result is not None
# Now create a second verification without 'photo_id_key'
attempt = SoftwareSecurePhotoVerification(user=user)
@@ -266,14 +263,14 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
# Test method 'get_initial_verification' still returns the correct
# initial verification attempt which have 'photo_id_key' set
second_result = SoftwareSecurePhotoVerification.get_initial_verification(user=user)
self.assertIsNotNone(second_result)
self.assertEqual(second_result, first_result)
assert second_result is not None
assert second_result == first_result
# Test method 'get_initial_verification' returns None after expiration
expired_future = now() + timedelta(days=(FAKE_SETTINGS['DAYS_GOOD_FOR'] + 1))
with freeze_time(expired_future):
third_result = SoftwareSecurePhotoVerification.get_initial_verification(user)
self.assertIsNone(third_result)
assert third_result is None
# Test method 'get_initial_verification' returns correct attempt after system expiration,
# but within earliest allowed override.
@@ -281,8 +278,8 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
earliest_allowed = now() - timedelta(days=1)
with freeze_time(expired_future):
fourth_result = SoftwareSecurePhotoVerification.get_initial_verification(user, earliest_allowed)
self.assertIsNotNone(fourth_result)
self.assertEqual(fourth_result, first_result)
assert fourth_result is not None
assert fourth_result == first_result
def test_retire_user(self):
"""
@@ -301,20 +298,20 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
attempt.approve()
# Validate data before retirement
self.assertEqual(attempt.name, user.profile.name)
self.assertEqual(attempt.photo_id_image_url, 'https://example.com/test/image/img.jpg')
self.assertEqual(attempt.face_image_url, 'https://example.com/test/face/img.jpg')
self.assertEqual(attempt.photo_id_key, 'there_was_an_attempt')
assert attempt.name == user.profile.name
assert attempt.photo_id_image_url == 'https://example.com/test/image/img.jpg'
assert attempt.face_image_url == 'https://example.com/test/face/img.jpg'
assert attempt.photo_id_key == 'there_was_an_attempt'
# Retire User
attempt_again = SoftwareSecurePhotoVerification(user=user)
self.assertTrue(attempt_again.retire_user(user_id=user.id))
assert attempt_again.retire_user(user_id=user.id)
# Validate data after retirement
self.assertEqual(attempt_again.name, '')
self.assertEqual(attempt_again.face_image_url, '')
self.assertEqual(attempt_again.photo_id_image_url, '')
self.assertEqual(attempt_again.photo_id_key, '')
assert attempt_again.name == ''
assert attempt_again.face_image_url == ''
assert attempt_again.photo_id_image_url == ''
assert attempt_again.photo_id_key == ''
def test_retire_nonuser(self):
"""
@@ -324,10 +321,10 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
attempt = SoftwareSecurePhotoVerification(user=user)
# User with no records in table
self.assertFalse(attempt.retire_user(user_id=user.id))
assert not attempt.retire_user(user_id=user.id)
# No user
self.assertFalse(attempt.retire_user(user_id=47))
assert not attempt.retire_user(user_id=47)
def test_get_recent_verification(self):
"""Test that method 'get_recent_verification' of model
@@ -348,8 +345,8 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
# Test method 'get_recent_verification' returns the most recent
# verification attempt based on updated_at
recent_verification = SoftwareSecurePhotoVerification.get_recent_verification(user=user)
self.assertIsNotNone(recent_verification)
self.assertEqual(recent_verification.id, attempt.id)
assert recent_verification is not None
assert recent_verification.id == attempt.id
def test_no_approved_verification(self):
"""Test that method 'get_recent_verification' of model
@@ -360,7 +357,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
SoftwareSecurePhotoVerification(user=user)
result = SoftwareSecurePhotoVerification.get_recent_verification(user=user)
self.assertIs(result, None)
assert result is None
def test_update_expiry_email_date_for_user(self):
"""Test that method update_expiry_email_date_for_user of
@@ -374,12 +371,12 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
verification.status = PhotoVerification.STATUS.approved
verification.save()
self.assertIsNone(verification.expiry_email_date)
assert verification.expiry_email_date is None
SoftwareSecurePhotoVerification.update_expiry_email_date_for_user(user, email_config)
result = SoftwareSecurePhotoVerification.get_recent_verification(user=user)
self.assertIsNotNone(result.expiry_email_date)
assert result.expiry_email_date is not None
def test_expiration_date_null(self):
"""
@@ -391,10 +388,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
verification.expiration_date = None
verification.save()
self.assertEqual(
verification.expiration_datetime,
verification.created_at + timedelta(days=FAKE_SETTINGS["DAYS_GOOD_FOR"])
)
assert verification.expiration_datetime == (verification.created_at + timedelta(days=FAKE_SETTINGS['DAYS_GOOD_FOR']))
def test_deprecated_expiry_date(self):
"""
@@ -404,20 +398,14 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
with freeze_time(now()):
verification = SoftwareSecurePhotoVerification(user=user)
# First, assert that expiration_date is set correctly
self.assertEqual(
verification.expiration_datetime,
now() + timedelta(days=FAKE_SETTINGS["DAYS_GOOD_FOR"])
)
assert verification.expiration_datetime == (now() + timedelta(days=FAKE_SETTINGS['DAYS_GOOD_FOR']))
verification.expiry_date = now() + timedelta(days=10)
# Then, assert that expiration_datetime favors expiry_date's value if set
self.assertEqual(
verification.expiration_datetime,
now() + timedelta(days=10)
)
assert verification.expiration_datetime == (now() + timedelta(days=10))
def test_get_verification_from_receipt(self):
result = SoftwareSecurePhotoVerification.get_verification_from_receipt('')
self.assertIs(result, None)
assert result is None
user = UserFactory.create()
attempt = SoftwareSecurePhotoVerification(user=user)
@@ -425,7 +413,7 @@ class TestPhotoVerification(TestVerificationBase, MockS3BotoMixin, ModuleStoreTe
attempt.save()
receipt_id = attempt.receipt_id
result = SoftwareSecurePhotoVerification.get_verification_from_receipt(receipt_id)
self.assertIsNotNone(result)
assert result is not None
class SSOVerificationTest(TestVerificationBase):

View File

@@ -45,11 +45,11 @@ class TestIDVerificationService(ModuleStoreTestCase):
for status in ["created", "ready", "denied", "submitted", "must_retry"]:
attempt.status = status
attempt.save()
self.assertFalse(IDVerificationService.user_is_verified(user), status)
assert not IDVerificationService.user_is_verified(user), status
attempt.status = "approved"
attempt.save()
self.assertTrue(IDVerificationService.user_is_verified(user), attempt.status)
assert IDVerificationService.user_is_verified(user), attempt.status
def test_user_has_valid_or_pending(self):
"""
@@ -63,14 +63,14 @@ class TestIDVerificationService(ModuleStoreTestCase):
for status in ["created", "ready", "denied"]:
attempt.status = status
attempt.save()
self.assertFalse(IDVerificationService.user_has_valid_or_pending(user), status)
assert not IDVerificationService.user_has_valid_or_pending(user), status
# Any of these, and we are. Note the benefit of the doubt we're giving
# -- must_retry, and submitted both count until we hear otherwise
for status in ["submitted", "must_retry", "approved"]:
attempt.status = status
attempt.save()
self.assertTrue(IDVerificationService.user_has_valid_or_pending(user), status)
assert IDVerificationService.user_has_valid_or_pending(user), status
@ddt.unpack
@ddt.data(
@@ -92,7 +92,7 @@ class TestIDVerificationService(ModuleStoreTestCase):
mock_verification.return_value = status
status = IDVerificationService.verification_status_for_user(user, enrollment_mode)
self.assertEqual(status, output)
assert status == output
def test_get_verified_user_ids(self):
"""
@@ -114,7 +114,7 @@ class TestIDVerificationService(ModuleStoreTestCase):
]))
expected_user_ids = {user_a.id, user_b.id, user_c.id}
self.assertEqual(expected_user_ids, verified_user_ids)
assert expected_user_ids == verified_user_ids
def test_get_verify_location_no_course_key(self):
"""
@@ -122,7 +122,7 @@ class TestIDVerificationService(ModuleStoreTestCase):
"""
path = IDVerificationService.get_verify_location()
expected_path = '{}/id-verification'.format(settings.ACCOUNT_MICROFRONTEND_URL)
self.assertEqual(path, expected_path)
assert path == expected_path
def test_get_verify_location_from_course_id(self):
"""
@@ -131,7 +131,7 @@ class TestIDVerificationService(ModuleStoreTestCase):
course = CourseFactory.create(org='Robot', number='999', display_name='Test Course')
path = IDVerificationService.get_verify_location(course.id)
expected_path = '{}/id-verification'.format(settings.ACCOUNT_MICROFRONTEND_URL)
self.assertEqual(path, expected_path + '?course_id=Robot/999/Test_Course')
assert path == (expected_path + '?course_id=Robot/999/Test_Course')
def test_get_verify_location_from_string(self):
"""
@@ -139,7 +139,7 @@ class TestIDVerificationService(ModuleStoreTestCase):
"""
path = IDVerificationService.get_verify_location('course-v1:edX+DemoX+Demo_Course')
expected_path = '{}/id-verification'.format(settings.ACCOUNT_MICROFRONTEND_URL)
self.assertEqual(path, expected_path + '?course_id=course-v1%3AedX%2BDemoX%2BDemo_Course')
assert path == (expected_path + '?course_id=course-v1%3AedX%2BDemoX%2BDemo_Course')
@patch.dict(settings.VERIFY_STUDENT, FAKE_SETTINGS)

View File

@@ -31,7 +31,7 @@ class VerificationDeadlineSignalTest(ModuleStoreTestCase):
""" Verify the signal sets deadline to course end when no deadline exists."""
_listen_for_course_publish('store', self.course.id)
self.assertEqual(VerificationDeadline.deadline_for_course(self.course.id), self.course.end)
assert VerificationDeadline.deadline_for_course(self.course.id) == self.course.end
def test_deadline(self):
""" Verify deadline is set to course end date by signal when changed. """
@@ -39,7 +39,7 @@ class VerificationDeadlineSignalTest(ModuleStoreTestCase):
VerificationDeadline.set_deadline(self.course.id, deadline)
_listen_for_course_publish('store', self.course.id)
self.assertEqual(VerificationDeadline.deadline_for_course(self.course.id), self.course.end)
assert VerificationDeadline.deadline_for_course(self.course.id) == self.course.end
def test_deadline_explicit(self):
""" Verify deadline is unchanged by signal when explicitly set. """
@@ -49,8 +49,8 @@ class VerificationDeadlineSignalTest(ModuleStoreTestCase):
_listen_for_course_publish('store', self.course.id)
actual_deadline = VerificationDeadline.deadline_for_course(self.course.id)
self.assertNotEqual(actual_deadline, self.course.end)
self.assertEqual(actual_deadline, deadline)
assert actual_deadline != self.course.end
assert actual_deadline == deadline
class RetirementSignalTest(ModuleStoreTestCase):
@@ -83,7 +83,7 @@ class RetirementSignalTest(ModuleStoreTestCase):
# All values for this user should now be empty string
for field in ('name', 'face_image_url', 'photo_id_image_url', 'photo_id_key'):
self.assertEqual('', getattr(ver_obj, field))
assert '' == getattr(ver_obj, field)
def test_retire_success_no_entries(self):
user = UserFactory()
@@ -101,4 +101,4 @@ class RetirementSignalTest(ModuleStoreTestCase):
# All values for this user should now be empty string
for field in ('name', 'face_image_url', 'photo_id_image_url', 'photo_id_key'):
self.assertEqual('', getattr(ver_obj, field))
assert '' == getattr(ver_obj, field)

View File

@@ -42,12 +42,12 @@ class TestVerifyStudentUtils(unittest.TestCase):
# No attempts in the query set, so should return None
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(now, query)
self.assertIs(result, None)
assert result is None
# Should also return None if no deadline specified
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(None, query)
self.assertIs(result, None)
assert result is None
# Make an attempt
attempt = SoftwareSecurePhotoVerification.objects.create(user=user)
@@ -56,25 +56,25 @@ class TestVerifyStudentUtils(unittest.TestCase):
before = attempt.created_at - timedelta(seconds=1)
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(before, query)
self.assertIs(result, None)
assert result is None
# Immediately after the created date, should get the attempt
after_created = attempt.created_at + timedelta(seconds=1)
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(after_created, query)
self.assertEqual(result, attempt)
assert result == attempt
# If no deadline specified, should return first available
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(None, query)
self.assertEqual(result, attempt)
assert result == attempt
# Immediately before the expiration date, should get the attempt
expiration = attempt.expiration_datetime + timedelta(days=settings.VERIFY_STUDENT["DAYS_GOOD_FOR"])
before_expiration = expiration - timedelta(seconds=1)
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(before_expiration, query)
self.assertEqual(result, attempt)
assert result == attempt
# Immediately after the expiration date, should not get the attempt
attempt.expiration_date = now - timedelta(seconds=1)
@@ -82,7 +82,7 @@ class TestVerifyStudentUtils(unittest.TestCase):
after = now + timedelta(days=1)
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(after, query)
self.assertIs(result, None)
assert result is None
# Create a second attempt in the same window
second_attempt = SoftwareSecurePhotoVerification.objects.create(user=user)
@@ -91,7 +91,7 @@ class TestVerifyStudentUtils(unittest.TestCase):
deadline = second_attempt.created_at + timedelta(days=1)
query = SoftwareSecurePhotoVerification.objects.filter(user=user)
result = verification_for_datetime(deadline, query)
self.assertEqual(result, second_attempt)
assert result == second_attempt
@ddt.data(
(False, False, False, None, None),
@@ -141,13 +141,13 @@ class TestVerifyStudentUtils(unittest.TestCase):
)
if not expected_verification:
self.assertEqual(most_recent, None)
assert most_recent is None
elif expected_verification == 'photo':
self.assertEqual(most_recent, photo_verification)
assert most_recent == photo_verification
elif expected_verification == 'sso':
self.assertEqual(most_recent, sso_verification)
assert most_recent == sso_verification
else:
self.assertEqual(most_recent, manual_verification)
assert most_recent == manual_verification
@mock.patch('lms.djangoapps.verify_student.utils.log')
@mock.patch(
@@ -165,4 +165,4 @@ class TestVerifyStudentUtils(unittest.TestCase):
user.username,
'error'
)
self.assertTrue(attempt.status, SoftwareSecurePhotoVerification.STATUS.must_retry)
assert attempt.status, SoftwareSecurePhotoVerification.STATUS.must_retry

View File

@@ -154,7 +154,7 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
super(TestPayAndVerifyView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD)
result = self.client.login(username=self.USERNAME, password=self.PASSWORD)
self.assertTrue(result, msg="Could not log in")
assert result, 'Could not log in'
@ddt.data(
("verified", "verify_student_start_flow"),
@@ -688,7 +688,7 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
# Expect that the expiration date is set
response = self._get_page(payment_flow, course.id)
data = self._get_page_data(response)
self.assertEqual(data['verification_deadline'], six.text_type(deadline))
assert data['verification_deadline'] == six.text_type(deadline)
def test_course_mode_expired(self):
deadline = now() + timedelta(days=-360)
@@ -748,17 +748,17 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
self.assertNotContains(response, "Verification is no longer available")
data = self._get_page_data(response)
self.assertEqual(data['message_key'], PayAndVerifyView.VERIFY_NOW_MSG)
assert data['message_key'] == PayAndVerifyView.VERIFY_NOW_MSG
# Check that the mode selected is expired verified mode not the credit mode
# because the direct enrollment to the credit mode is not allowed.
self.assertEqual(data['course_mode_slug'], "verified")
assert data['course_mode_slug'] == 'verified'
# Check that the verification deadline (rather than the upgrade deadline) is displayed
if verification_deadline is not None:
self.assertEqual(data["verification_deadline"], six.text_type(verification_deadline))
assert data['verification_deadline'] == six.text_type(verification_deadline)
else:
self.assertEqual(data["verification_deadline"], "")
assert data['verification_deadline'] == ''
def test_course_mode_not_expired_verification_deadline_passed(self):
course = self._create_course("verified")
@@ -902,72 +902,64 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
_mock_payment_processors()
response = self.client.get(url)
self.assertEqual(response.status_code, expected_status_code)
assert response.status_code == expected_status_code
if assert_headers:
# ensure the mock api call was made. NOTE: the following line
# approximates the check - if the headers were empty it means
# there was no last request.
self.assertNotEqual(httpretty.last_request().headers, {})
assert httpretty.last_request().headers != {}
return response
def _assert_displayed_mode(self, response, expected_mode):
"""Check whether a course mode is displayed. """
response_dict = self._get_page_data(response)
self.assertEqual(response_dict['course_mode_slug'], expected_mode)
assert response_dict['course_mode_slug'] == expected_mode
def _assert_steps_displayed(self, response, expected_steps, expected_current_step):
"""Check whether steps in the flow are displayed to the user. """
response_dict = self._get_page_data(response)
self.assertEqual(response_dict['current_step'], expected_current_step)
self.assertEqual(expected_steps, [
step['name'] for step in
response_dict['display_steps']
])
assert response_dict['current_step'] == expected_current_step
assert expected_steps == [step['name'] for step in response_dict['display_steps']]
def _assert_messaging(self, response, expected_message):
"""Check the messaging on the page. """
response_dict = self._get_page_data(response)
self.assertEqual(response_dict['message_key'], expected_message)
assert response_dict['message_key'] == expected_message
def _assert_requirements_displayed(self, response, requirements):
"""Check that requirements are displayed on the page. """
response_dict = self._get_page_data(response)
for req, displayed in six.iteritems(response_dict['requirements']):
if req in requirements:
self.assertTrue(displayed, msg=u"Expected '{req}' requirement to be displayed".format(req=req))
assert displayed, "Expected '{req}' requirement to be displayed".format(req=req)
else:
self.assertFalse(displayed, msg=u"Expected '{req}' requirement to be hidden".format(req=req))
assert not displayed, "Expected '{req}' requirement to be displayed".format(req=req)
def _assert_course_details(self, response, course_key, display_name, url):
"""Check the course information on the page. """
response_dict = self._get_page_data(response)
self.assertEqual(response_dict['course_key'], course_key)
self.assertEqual(response_dict['course_name'], display_name)
self.assertEqual(response_dict['courseware_url'], url)
assert response_dict['course_key'] == course_key
assert response_dict['course_name'] == display_name
assert response_dict['courseware_url'] == url
def _assert_user_details(self, response, full_name):
"""Check the user detail information on the page. """
response_dict = self._get_page_data(response)
self.assertEqual(response_dict['full_name'], full_name)
assert response_dict['full_name'] == full_name
def _assert_contribution_amount(self, response, expected_amount):
"""Check the pre-filled contribution amount. """
response_dict = self._get_page_data(response)
self.assertEqual(response_dict['contribution_amount'], expected_amount)
assert response_dict['contribution_amount'] == expected_amount
def _get_page_data(self, response):
"""Retrieve the data attributes rendered on the page. """
soup = BeautifulSoup(markup=response.content, features="lxml")
pay_and_verify_div = soup.find(id="pay-and-verify-container")
self.assertIsNot(
pay_and_verify_div, None,
msg=(
"Could not load pay and verify flow data. "
"Maybe this isn't the pay and verify page?"
)
)
assert pay_and_verify_div is not None,\
"Could not load pay and verify flow data. Maybe this isn't the pay and verify page?"
return {
'full_name': pay_and_verify_div['data-full-name'],
@@ -986,7 +978,7 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
def _assert_upgrade_session_flag(self, is_upgrade):
"""Check that the session flag for attempting an upgrade is set. """
self.assertEqual(self.client.session.get('attempting_upgrade'), is_upgrade)
assert self.client.session.get('attempting_upgrade') == is_upgrade
def _assert_redirects_to_dashboard(self, response):
"""Check that the page redirects to the student dashboard. """
@@ -1026,7 +1018,7 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
self._enroll(course.id)
response_dict = self._get_page_data(self._get_page(payment_flow, course.id))
self.assertEqual(response_dict['course_name'], mode_display_name)
assert response_dict['course_name'] == mode_display_name
@ddt.data("verify_student_start_flow", "verify_student_begin_flow")
def test_processors_api(self, payment_flow):
@@ -1042,7 +1034,7 @@ class TestPayAndVerifyView(UrlResetMixin, ModuleStoreTestCase, XssTestMixin, Tes
# make the server request
response = self._get_page(payment_flow, course.id, assert_headers=True)
self.assertEqual(response.status_code, 200)
assert response.status_code == 200
class CheckoutTestMixin(object):
@@ -1084,20 +1076,20 @@ class CheckoutTestMixin(object):
"""
post_params.setdefault('processor', '')
response = self.client.post(reverse('verify_student_create_order'), post_params)
self.assertEqual(response.status_code, expected_status_code)
assert response.status_code == expected_status_code
if expected_status_code == 200:
# ensure we called checkout at all
self.assertTrue(patched_create_order.called)
assert patched_create_order.called
# ensure checkout args were correct
args = self._get_checkout_args(patched_create_order)
self.assertEqual(args['user'], self.user)
self.assertEqual(args['course_key'], expected_course_key)
self.assertEqual(args['course_mode'].slug, expected_mode_slug)
assert args['user'] == self.user
assert args['course_key'] == expected_course_key
assert args['course_mode'].slug == expected_mode_slug
# ensure response data was correct
data = json.loads(response.content.decode('utf-8'))
self.assertEqual(set(data.keys()), PAYMENT_DATA_KEYS)
assert set(data.keys()) == PAYMENT_DATA_KEYS
else:
self.assertFalse(patched_create_order.called)
assert not patched_create_order.called
def test_create_order(self, patched_create_order):
# Create an order
@@ -1159,16 +1151,16 @@ class CheckoutTestMixin(object):
# there is no 'processor' parameter in the post payload, so the response should only contain payment form data.
params = {'course_id': six.text_type(self.course.id), 'contribution': 100}
response = self.client.post(reverse('verify_student_create_order'), params)
self.assertEqual(response.status_code, 200)
self.assertTrue(patched_create_order.called)
assert response.status_code == 200
assert patched_create_order.called
# ensure checkout args were correct
args = self._get_checkout_args(patched_create_order)
self.assertEqual(args['user'], self.user)
self.assertEqual(args['course_key'], self.course.id)
self.assertEqual(args['course_mode'].slug, 'verified')
assert args['user'] == self.user
assert args['course_key'] == self.course.id
assert args['course_mode'].slug == 'verified'
# ensure response data was correct
data = json.loads(response.content.decode('utf-8'))
self.assertEqual(data, {'foo': 'bar'})
assert data == {'foo': 'bar'}
@override_settings(ECOMMERCE_API_URL=TEST_API_URL)
@@ -1223,16 +1215,13 @@ class TestCheckoutWithEcommerceService(ModuleStoreTestCase):
)
# Verify that an audit message was logged
self.assertTrue(mock_audit_log.called)
assert mock_audit_log.called
# Check the api call
self.assertEqual(json.loads(httpretty.last_request().body.decode('utf-8')), {
'products': [{'sku': 'test-sku'}],
'checkout': True,
'payment_processor_name': 'test-processor',
})
assert json.loads(httpretty.last_request().body.decode('utf-8')) ==\
{'products': [{'sku': 'test-sku'}], 'checkout': True, 'payment_processor_name': 'test-processor'}
# Check the response
self.assertEqual(actual_payment_data, expected_payment_data)
assert actual_payment_data == expected_payment_data
@ddt.ddt
@@ -1250,7 +1239,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
super(TestSubmitPhotosForVerification, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD)
result = self.client.login(username=self.USERNAME, password=self.PASSWORD)
self.assertTrue(result, msg="Could not log in")
assert result, 'Could not log in'
def test_submit_photos(self):
# Submit the photos
@@ -1261,7 +1250,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
# Verify that the attempt is created in the database
attempt = SoftwareSecurePhotoVerification.objects.get(user=self.user)
self.assertEqual(attempt.status, "submitted")
assert attempt.status == 'submitted'
# Verify that the user's name wasn't changed
self._assert_user_name(self.user.profile.name)
@@ -1328,7 +1317,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
reverification_data = self._get_post_data()
# Verify that the initial attempt sent the same ID photo as the reverification attempt
self.assertEqual(initial_data["PhotoIDKey"], reverification_data["PhotoIDKey"])
assert initial_data['PhotoIDKey'] == reverification_data['PhotoIDKey']
# Submit a new face photo and photo id for verification
self._submit_photos(
@@ -1338,7 +1327,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
two_photo_reverification_data = self._get_post_data()
# Verify that the initial attempt sent a new ID photo for the reverification attempt
self.assertNotEqual(initial_data["PhotoIDKey"], two_photo_reverification_data["PhotoIDKey"])
assert initial_data['PhotoIDKey'] != two_photo_reverification_data['PhotoIDKey']
@ddt.data('face_image', 'photo_id_image')
def test_invalid_image_data(self, invalid_param):
@@ -1348,7 +1337,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
}
params[invalid_param] = ""
response = self._submit_photos(expected_status_code=400, **params)
self.assertEqual(response.content.decode('utf-8'), "Image data is not valid.")
assert response.content.decode('utf-8') == 'Image data is not valid.'
def test_invalid_name(self):
response = self._submit_photos(
@@ -1357,7 +1346,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
full_name="",
expected_status_code=400
)
self.assertEqual(response.content.decode('utf-8'), "Name must be at least 1 character long.")
assert response.content.decode('utf-8') == 'Name must be at least 1 character long.'
def test_missing_required_param(self):
# Missing face image parameter
@@ -1365,16 +1354,14 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
'photo_id_image': self.IMAGE_DATA
}
response = self._submit_photos(expected_status_code=400, **params)
self.assertEqual(response.content.decode('utf-8'), "Missing required parameter face_image")
assert response.content.decode('utf-8') == 'Missing required parameter face_image'
def test_no_photo_id_and_no_initial_verification(self):
# Submit face image data, but not photo ID data.
# Since the user doesn't have an initial verification attempt, this should fail
response = self._submit_photos(expected_status_code=400, face_image=self.IMAGE_DATA)
self.assertEqual(
response.content.decode('utf-8'),
"Photo ID image is required if the user does not have an initial verification attempt."
)
assert response.content.decode('utf-8') ==\
'Photo ID image is required if the user does not have an initial verification attempt.'
# Create the initial verification attempt with some dummy
# value set for field 'photo_id_key'
@@ -1417,7 +1404,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
with self.immediate_on_commit():
response = self.client.post(url, params)
self.assertEqual(response.status_code, expected_status_code)
assert response.status_code == expected_status_code
return response
@@ -1427,11 +1414,11 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
"""
if expect_email:
# Verify that photo submission confirmation email was sent
self.assertEqual(len(mail.outbox), 1)
self.assertEqual('Thank you for submitting your photos!', mail.outbox[0].subject)
assert len(mail.outbox) == 1
assert 'Thank you for submitting your photos!' == mail.outbox[0].subject
else:
# Verify that photo submission confirmation email was not sent
self.assertEqual(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def _assert_user_name(self, full_name):
"""Check the user's name.
@@ -1446,7 +1433,7 @@ class TestSubmitPhotosForVerification(MockS3BotoMixin, TestVerificationBase):
request = RequestFactory().get('/url')
request.user = self.user
account_settings = get_account_settings(request)[0]
self.assertEqual(account_settings['name'], full_name)
assert account_settings['name'] == full_name
def _get_post_data(self):
"""Retrieve POST data from the last request. """
@@ -1481,18 +1468,18 @@ class TestPhotoVerificationResultsCallback(ModuleStoreTestCase, TestVerification
def _assert_verification_approved_email(self, expiration_date):
"""Check that a verification approved email was sent."""
self.assertEqual(len(mail.outbox), 1)
assert len(mail.outbox) == 1
email = mail.outbox[0]
self.assertEqual(email.subject, 'Your édX ID verification was approved!')
self.assertIn('Your édX ID verification photos have been approved', email.body)
self.assertIn(expiration_date.strftime("%m/%d/%Y"), email.body)
assert email.subject == 'Your édX ID verification was approved!'
assert 'Your édX ID verification photos have been approved' in email.body
assert expiration_date.strftime("%m/%d/%Y") in email.body
def _assert_verification_denied_email(self):
"""Check that a verification approved email was sent."""
self.assertEqual(len(mail.outbox), 1)
assert len(mail.outbox) == 1
email = mail.outbox[0]
self.assertEqual(email.subject, 'Your édX Verification Has Been Denied')
self.assertIn('The photos you submitted for ID verification were not accepted', email.body)
assert email.subject == 'Your édX Verification Has Been Denied'
assert 'The photos you submitted for ID verification were not accepted' in email.body
def test_invalid_json(self):
"""
@@ -1604,10 +1591,10 @@ class TestPhotoVerificationResultsCallback(ModuleStoreTestCase, TestVerification
)
attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=self.receipt_id)
old_verification = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk)
self.assertEqual(attempt.status, u'approved')
self.assertEqual(attempt.expiration_datetime.date(), expiration_datetime.date())
self.assertIsNone(old_verification.expiry_email_date)
self.assertEqual(response.content.decode('utf-8'), 'OK!')
assert attempt.status == u'approved'
assert attempt.expiration_datetime.date() == expiration_datetime.date()
assert old_verification.expiry_email_date is None
assert response.content.decode('utf-8') == 'OK!'
self._assert_verification_approved_email(expiration_datetime.date())
@patch(
@@ -1639,9 +1626,9 @@ class TestPhotoVerificationResultsCallback(ModuleStoreTestCase, TestVerification
)
attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=self.receipt_id)
self.assertEqual(attempt.status, u'approved')
self.assertEqual(attempt.expiration_datetime.date(), expiration_datetime.date())
self.assertEqual(response.content.decode('utf-8'), 'OK!')
assert attempt.status == u'approved'
assert attempt.expiration_datetime.date() == expiration_datetime.date()
assert response.content.decode('utf-8') == 'OK!'
self._assert_verification_approved_email(expiration_datetime.date())
@patch(
@@ -1669,10 +1656,10 @@ class TestPhotoVerificationResultsCallback(ModuleStoreTestCase, TestVerification
HTTP_DATE='testdate'
)
attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=self.receipt_id)
self.assertEqual(attempt.status, u'denied')
self.assertEqual(attempt.error_code, u'Your photo doesn\'t meet standards.')
self.assertEqual(attempt.error_msg, u'[{"photoIdReasons": ["Not provided"]}]')
self.assertEqual(response.content.decode('utf-8'), 'OK!')
assert attempt.status == u'denied'
assert attempt.error_code == u"Your photo doesn't meet standards."
assert attempt.error_msg == u'[{"photoIdReasons": ["Not provided"]}]'
assert response.content.decode('utf-8') == 'OK!'
self._assert_verification_denied_email()
@patch(
@@ -1696,10 +1683,10 @@ class TestPhotoVerificationResultsCallback(ModuleStoreTestCase, TestVerification
HTTP_DATE='testdate'
)
attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=self.receipt_id)
self.assertEqual(attempt.status, u'must_retry')
self.assertEqual(attempt.error_code, u'You must retry the verification.')
self.assertEqual(attempt.error_msg, u'"Memory overflow"')
self.assertEqual(response.content.decode('utf-8'), 'OK!')
assert attempt.status == u'must_retry'
assert attempt.error_code == u'You must retry the verification.'
assert attempt.error_msg == u'"Memory overflow"'
assert response.content.decode('utf-8') == 'OK!'
@patch(
'lms.djangoapps.verify_student.ssencrypt.has_valid_signature',
@@ -1741,7 +1728,7 @@ class TestReverifyView(TestVerificationBase):
super(TestReverifyView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD)
success = self.client.login(username=self.USERNAME, password=self.PASSWORD)
self.assertTrue(success, msg="Could not log in")
assert success, 'Could not log in'
def test_reverify_view_can_do_initial_verification(self):
"""
@@ -1840,7 +1827,7 @@ class TestPhotoURLView(TestVerificationBase):
self.user = AdminFactory()
login_success = self.client.login(username=self.user.username, password='test')
self.assertTrue(login_success)
assert login_success
self.attempt = SoftwareSecurePhotoVerification(
status="submitted",
user=self.user
@@ -1851,35 +1838,26 @@ class TestPhotoURLView(TestVerificationBase):
def test_photo_url_view_returns_data(self):
url = reverse('verification_photo_urls', kwargs={'receipt_id': six.text_type(self.receipt_id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["EdX-ID"], self.receipt_id)
self.assertEqual(
response.data["PhotoID"],
"https://{bucket}/photo_id/{receipt_id}".format(
bucket=settings.AWS_S3_CUSTOM_DOMAIN,
receipt_id=self.receipt_id
)
)
self.assertEqual(
response.data["UserPhoto"],
"https://{bucket}/face/{receipt_id}".format(
bucket=settings.AWS_S3_CUSTOM_DOMAIN,
receipt_id=self.receipt_id
)
)
assert response.status_code == 200
assert response.data['EdX-ID'] == self.receipt_id
assert response.data['PhotoID'] == 'https://{bucket}/photo_id/{receipt_id}'\
.format(bucket=settings.AWS_S3_CUSTOM_DOMAIN, receipt_id=self.receipt_id)
assert response.data['UserPhoto'] == 'https://{bucket}/face/{receipt_id}'\
.format(bucket=settings.AWS_S3_CUSTOM_DOMAIN, receipt_id=self.receipt_id)
def test_photo_url_view_returns_404_if_invalid_receipt_id(self):
url = reverse('verification_photo_urls', kwargs={'receipt_id': six.text_type('00000000-0000-0000-0000-000000000000')}) # lint-amnesty, pylint: disable=line-too-long
url = reverse('verification_photo_urls',
kwargs={'receipt_id': six.text_type('00000000-0000-0000-0000-000000000000')})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
assert response.status_code == 404
def test_403_for_non_staff(self):
self.user = UserFactory()
login_success = self.client.login(username=self.user.username, password='test')
self.assertTrue(login_success)
assert login_success
url = reverse('verification_photo_urls', kwargs={'receipt_id': six.text_type(self.receipt_id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
@override_settings(
@@ -1915,7 +1893,7 @@ class TestDecodeImageViews(MockS3BotoMixin, TestVerificationBase):
super().setUp()
self.user = AdminFactory()
login_success = self.client.login(username=self.user.username, password='test')
self.assertTrue(login_success)
assert login_success
def _mock_submit_images(self):
"""
@@ -1969,14 +1947,14 @@ class TestDecodeImageViews(MockS3BotoMixin, TestVerificationBase):
#mock downloading and decrypting images
response = self._decode_image(receipt_id, img_type)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, base64.b64decode(self.IMAGE_DATA.split(",")[1]))
assert response.status_code == 200
assert response.content == base64.b64decode(self.IMAGE_DATA.split(',')[1])
@ddt.data("face", "photo_id")
def test_403_for_non_staff(self, img_type):
self.user = UserFactory()
login_success = self.client.login(username=self.user.username, password='test')
self.assertTrue(login_success)
assert login_success
self._mock_submit_images()
attempt = SoftwareSecurePhotoVerification.objects.get(user=self.user)
@@ -1984,7 +1962,7 @@ class TestDecodeImageViews(MockS3BotoMixin, TestVerificationBase):
# mock downloading and decrypting images
response = self._decode_image(receipt_id, img_type)
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
@override_settings(
VERIFY_STUDENT={
@@ -2010,12 +1988,12 @@ class TestDecodeImageViews(MockS3BotoMixin, TestVerificationBase):
# mock downloading and decrypting images
response = self._decode_image(receipt_id, img_type)
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
@ddt.data("face", "photo_id")
def test_404_if_invalid_receipt_id(self, img_type):
response = self._decode_image('00000000-0000-0000-0000-000000000000', img_type)
self.assertEqual(response.status_code, 404)
assert response.status_code == 404
@ddt.data("face", "photo_id")
@patch.object(SoftwareSecurePhotoVerification, '_get_image_from_storage')
@@ -2031,4 +2009,4 @@ class TestDecodeImageViews(MockS3BotoMixin, TestVerificationBase):
# mock downloading and decrypting images
response = self._decode_image(receipt_id, img_type)
self.assertEqual(response.status_code, 404)
assert response.status_code == 404