diff --git a/accounts/models.py b/accounts/models.py index 6e1b18cfd..94016d9b3 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -727,6 +727,9 @@ def presave_user(sender, instance, **kwargs): # We use .get_or_create below to avoid having 2 OldUsername objects with the same user/username pair OldUsername.objects.get_or_create(user=instance, username=old_username) + # Also mark all sounds as index dirty because they'll need to be reindexed with the new username + Sound.objects.filter(user=instance).update(is_index_dirty=True) + # Check if email has change and, if so, remove existing EmailBounce objects associated to the user (if any) old_email = old_user_object.email if old_email != instance.email: diff --git a/accounts/tests/test_user.py b/accounts/tests/test_user.py index bb81c6957..322b6a08b 100644 --- a/accounts/tests/test_user.py +++ b/accounts/tests/test_user.py @@ -41,6 +41,7 @@ from general.tasks import DELETE_USER_DELETE_SOUNDS_ACTION_NAME, DELETE_USER_KEEP_SOUNDS_ACTION_NAME from sounds.models import License, Sound, Pack, DeletedSound, Download, PackDownload from utils.mail import transform_unique_email +from utils.test_helpers import create_user_and_sounds class UserRegistrationAndActivation(TestCase): @@ -883,6 +884,8 @@ def test_resend_activation_code_from_username(self): class ChangeUsernameTest(TestCase): + fixtures = ['licenses'] + def test_change_username_creates_old_username(self): # Create user and check no OldUsername objects exist userA = User.objects.create_user('userA', email='userA@freesound.org') @@ -972,6 +975,19 @@ def test_change_username_form_profile_page(self): self.assertEqual(userA.username, 'userANewNewName') # ...username has not changed... self.assertEqual(OldUsername.objects.filter(user=userA).count(), 2) # ...and no new OldUsername objects created + def test_change_username_mark_sounds_dirty(self): + # Thest that changing username of a user that has sounds marks her sounds as dirty + user, _, _ = create_user_and_sounds(num_sounds=3, num_packs=0) + Sound.objects.filter(user=user).update(is_index_dirty=False) + self.client.force_login(user) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['userANewNewName'], 'profile-ui_theme_preference': 'f'}) + self.assertRedirects(resp, reverse('accounts-edit')) + user.refresh_from_db() + self.assertEqual(user.username, 'userANewNewName') + self.assertEqual(OldUsername.objects.filter(user=user).count(), 1) + ss = Sound.objects.filter(user=user, is_index_dirty=True) + self.assertEqual(ss.count(), 3) + @override_settings(USERNAME_CHANGE_MAX_TIMES=2) def test_change_username_form_admin(self): User.objects.create_user('superuser', password='testpass', is_superuser=True, is_staff=True)