Error handling on the post for security contact

This commit is contained in:
Rachid Mrad 2023-10-17 14:23:42 -04:00
parent 5fbe72ce5a
commit 0e5978011d
No known key found for this signature in database
GPG key ID: EF38E4CEC4A8F3CF
6 changed files with 108 additions and 7 deletions

View file

@ -45,7 +45,7 @@ except NameError:
# Attn: these imports should NOT be at the top of the file # Attn: these imports should NOT be at the top of the file
try: try:
from .client import CLIENT, commands from .client import CLIENT, commands
from .errors import RegistryError, ErrorCode from .errors import RegistryError, ErrorCode, CANNOT_CONTACT_REGISTRY, GENERIC_ERROR
from epplib.models import common, info from epplib.models import common, info
from epplib.responses import extensions from epplib.responses import extensions
from epplib import responses from epplib import responses
@ -61,4 +61,6 @@ __all__ = [
"info", "info",
"ErrorCode", "ErrorCode",
"RegistryError", "RegistryError",
"CANNOT_CONTACT_REGISTRY",
"GENERIC_ERROR",
] ]

View file

@ -1,5 +1,8 @@
from enum import IntEnum from enum import IntEnum
CANNOT_CONTACT_REGISTRY = "Update failed. Cannot contact the registry."
GENERIC_ERROR = "Value entered was wrong."
class ErrorCode(IntEnum): class ErrorCode(IntEnum):
""" """

View file

@ -701,7 +701,7 @@ class Domain(TimeStampedModel, DomainHelper):
and errorCode != ErrorCode.COMMAND_COMPLETED_SUCCESSFULLY and errorCode != ErrorCode.COMMAND_COMPLETED_SUCCESSFULLY
): ):
# TODO- ticket #433 look here for error handling # TODO- ticket #433 look here for error handling
raise Exception("Unable to add contact to registry") raise RegistryError(code=errorCode)
# contact doesn't exist on the domain yet # contact doesn't exist on the domain yet
logger.info("_set_singleton_contact()-> contact has been added to the registry") logger.info("_set_singleton_contact()-> contact has been added to the registry")

View file

@ -32,6 +32,8 @@ from epplibwrapper import (
ErrorCode, ErrorCode,
) )
from registrar.models.utility.contact_error import ContactError, ContactErrorCodes
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -794,6 +796,20 @@ class MockEppLib(TestCase):
# use this for when a contact is being updated # use this for when a contact is being updated
# sets the second send() to fail # sets the second send() to fail
raise RegistryError(code=ErrorCode.OBJECT_EXISTS) raise RegistryError(code=ErrorCode.OBJECT_EXISTS)
elif (
isinstance(_request, commands.CreateContact)
and getattr(_request, "email", None) == "test@failCreate.gov"
):
# use this for when a contact is being updated
# mocks a registry error on creation
raise RegistryError(code=None)
elif (
isinstance(_request, commands.CreateContact)
and getattr(_request, "email", None) == "test@contactError.gov"
):
# use this for when a contact is being updated
# mocks a registry error on creation
raise ContactError(code=ContactErrorCodes.CONTACT_TYPE_NONE)
elif isinstance(_request, commands.CreateHost): elif isinstance(_request, commands.CreateHost):
return MagicMock( return MagicMock(
res_data=[self.mockDataHostChange], res_data=[self.mockDataHostChange],

View file

@ -1490,6 +1490,66 @@ class TestDomainDetail(TestWithDomainPermissions, WebTest, MockEppLib):
success_page, "The security email for this domain has been updated" success_page, "The security email for this domain has been updated"
) )
def test_security_email_form_messages(self):
"""
Test against the success and error messages that are defined in the view
"""
p = "adminpass"
self.client.login(username="superuser", password=p)
form_data_registry_error = {
"security_email": "test@failCreate.gov",
}
form_data_contact_error = {
"security_email": "test@contactError.gov",
}
form_data_success = {
"security_email": "test@something.gov",
}
test_cases = [
(
"RegistryError",
form_data_registry_error,
"Update failed. Cannot contact the registry.",
),
("ContactError", form_data_contact_error, "Value entered was wrong."),
(
"RegistrySuccess",
form_data_success,
"The security email for this domain has been updated.",
),
# Add more test cases with different scenarios here
]
for test_name, data, expected_message in test_cases:
response = self.client.post(
reverse("domain-security-email", kwargs={"pk": self.domain.id}),
data=data,
follow=True,
)
# Check the response status code, content, or any other relevant assertions
self.assertEqual(response.status_code, 200)
# Check if the expected message tag is set
if test_name == "RegistryError" or test_name == "ContactError":
message_tag = "error"
elif test_name == "RegistrySuccess":
message_tag = "success"
else:
# Handle other cases if needed
message_tag = "info" # Change to the appropriate default
# Check the message tag
messages = list(response.context["messages"])
self.assertEqual(len(messages), 1)
message = messages[0]
self.assertEqual(message.tags, message_tag)
self.assertEqual(message.message, expected_message)
def test_domain_overview_blocked_for_ineligible_user(self): def test_domain_overview_blocked_for_ineligible_user(self):
"""We could easily duplicate this test for all domain management """We could easily duplicate this test for all domain management
views, but a single url test should be solid enough since all domain views, but a single url test should be solid enough since all domain

View file

@ -22,6 +22,7 @@ from registrar.models import (
UserDomainRole, UserDomainRole,
) )
from registrar.models.public_contact import PublicContact from registrar.models.public_contact import PublicContact
from registrar.models.utility.contact_error import ContactError
from ..forms import ( from ..forms import (
ContactForm, ContactForm,
@ -30,6 +31,13 @@ from ..forms import (
DomainSecurityEmailForm, DomainSecurityEmailForm,
NameserverFormset, NameserverFormset,
) )
from epplibwrapper import (
RegistryError,
CANNOT_CONTACT_REGISTRY,
GENERIC_ERROR,
)
from ..utility.email import send_templated_email, EmailSendingError from ..utility.email import send_templated_email, EmailSendingError
from .utility import DomainPermissionView, DomainInvitationPermissionDeleteView from .utility import DomainPermissionView, DomainInvitationPermissionDeleteView
@ -310,12 +318,24 @@ class DomainSecurityEmailView(DomainPermissionView, FormMixin):
# If no default is created for security_contact, # If no default is created for security_contact,
# then we cannot connect to the registry. # then we cannot connect to the registry.
if contact is None: if contact is None:
messages.error(self.request, "Update failed. Cannot contact the registry.") messages.error(self.request, CANNOT_CONTACT_REGISTRY)
return redirect(self.get_success_url()) return redirect(self.get_success_url())
contact.email = new_email contact.email = new_email
contact.save()
try:
contact.save()
except RegistryError as Err:
if Err.is_connection_error():
messages.error(self.request, CANNOT_CONTACT_REGISTRY)
logger.error(f"Registry connection error: {Err}")
else:
messages.error(self.request, GENERIC_ERROR)
logger.error(f"Registry error: {Err}")
except ContactError as Err:
messages.error(self.request, GENERIC_ERROR)
logger.error(f"Generic registry error: {Err}")
else:
messages.success( messages.success(
self.request, "The security email for this domain has been updated." self.request, "The security email for this domain has been updated."
) )