diff --git a/openedx/core/djangoapps/user_api/accounts/api.py b/openedx/core/djangoapps/user_api/accounts/api.py index 206af58fdf..4789241a5b 100644 --- a/openedx/core/djangoapps/user_api/accounts/api.py +++ b/openedx/core/djangoapps/user_api/accounts/api.py @@ -114,8 +114,9 @@ def update_account_settings(requesting_user, update, username=None): # If user has requested to change email, we must call the multi-step process to handle this. # It is not handled by the serializer (which considers email to be read-only). - new_email = None + changing_email = False if "email" in update: + changing_email = True new_email = update["email"] del update["email"] @@ -148,7 +149,7 @@ def update_account_settings(requesting_user, update, username=None): field_errors = _add_serializer_errors(update, serializer, field_errors) # If the user asked to change email, validate it. - if new_email: + if changing_email: try: validate_new_email(existing_user, new_email) except ValueError as err: @@ -186,7 +187,7 @@ def update_account_settings(requesting_user, update, username=None): ) # And try to send the email change request if necessary. - if new_email: + if changing_email: try: do_email_change_request(existing_user, new_email) except ValueError as err: diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_views.py b/openedx/core/djangoapps/user_api/accounts/tests/test_views.py index 918eb6529e..de518b8b49 100644 --- a/openedx/core/djangoapps/user_api/accounts/tests/test_views.py +++ b/openedx/core/djangoapps/user_api/accounts/tests/test_views.py @@ -438,8 +438,20 @@ class TestAccountAPI(UserAPITestCase): get_response = self.send_get(client) self.assertEqual(new_email, get_response.data["email"]) - # Finally, try changing to an invalid email just to make sure error messages are appropriately returned. - error_response = self.send_patch(client, {"email": "not_an_email"}, expected_status=400) + @ddt.data( + ("not_an_email",), + ("",), + (None,), + ) + @ddt.unpack + def test_patch_invalid_email(self, bad_email): + """ + Test a few error cases for email validation (full test coverage lives with do_email_change_request). + """ + client = self.login_client("client", "user") + + # Try changing to an invalid email to make sure error messages are appropriately returned. + error_response = self.send_patch(client, {"email": bad_email}, expected_status=400) field_errors = error_response.data["field_errors"] self.assertEqual( "Error thrown from validate_new_email: 'Valid e-mail address required.'",