made some updates to test adding less_noise decorator and fixing federalagency object handling

This commit is contained in:
David Kennedy 2024-07-19 10:32:17 -04:00
parent 65fbedab89
commit 8fbded1c0a
No known key found for this signature in database
GPG key ID: 6528A5386E66B96B
6 changed files with 272 additions and 271 deletions

View file

@ -3,6 +3,7 @@ from dateutil.tz import tzlocal # type: ignore
from unittest.mock import MagicMock, patch
from pathlib import Path
from django.test import TestCase
from api.tests.common import less_console_noise_decorator
from gevent.exceptions import ConcurrentObjectUseError
from epplibwrapper.client import EPPLibWrapper
from epplibwrapper.errors import RegistryError, LoginError
@ -24,15 +25,15 @@ logger = logging.getLogger(__name__)
class TestClient(TestCase):
"""Test the EPPlibwrapper client"""
@less_console_noise_decorator
def fake_result(self, code, msg):
"""Helper function to create a fake Result object"""
with less_console_noise():
return Result(code=code, msg=msg, res_data=[], cl_tr_id="cl_tr_id", sv_tr_id="sv_tr_id")
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_initialize_client_success(self, mock_client):
"""Test when the initialize_client is successful"""
with less_console_noise():
# Mock the Client instance and its methods
mock_connect = MagicMock()
# Create a mock Result instance
@ -54,10 +55,10 @@ class TestClient(TestCase):
# Assert that _client is not None after initialization
self.assertIsNotNone(wrapper._client)
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_initialize_client_transport_error(self, mock_client):
"""Test when the send(login) step of initialize_client raises a TransportError."""
with less_console_noise():
# Mock the Client instance and its methods
mock_connect = MagicMock()
mock_send = MagicMock(side_effect=TransportError("Transport error"))
@ -73,10 +74,10 @@ class TestClient(TestCase):
# the raised exception
wrapper._initialize_client()
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_initialize_client_login_error(self, mock_client):
"""Test when the send(login) step of initialize_client returns (2400) comamnd failed code."""
with less_console_noise():
# Mock the Client instance and its methods
mock_connect = MagicMock()
# Create a mock Result instance
@ -99,10 +100,10 @@ class TestClient(TestCase):
# the raised exception
wrapper._initialize_client()
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_initialize_client_unknown_exception(self, mock_client):
"""Test when the send(login) step of initialize_client raises an unexpected Exception."""
with less_console_noise():
# Mock the Client instance and its methods
mock_connect = MagicMock()
mock_send = MagicMock(side_effect=Exception("Unknown exception"))
@ -118,6 +119,7 @@ class TestClient(TestCase):
# the raised exception
wrapper._initialize_client()
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_initialize_client_fails_recovers_with_send_command(self, mock_client):
"""Test when the initialize_client fails on the connect() step. And then a subsequent
@ -127,7 +129,6 @@ class TestClient(TestCase):
Initialization step fails at app init
Send command fails (with 2400 code) prompting retry
Client closes and re-initializes, and command is sent successfully"""
with less_console_noise():
# Mock the Client instance and its methods
# close() should return successfully
mock_close = MagicMock()
@ -177,6 +178,7 @@ class TestClient(TestCase):
# passed send(login), passed send("InfoDomainCommand")
self.assertEquals(mock_send.call_count, 4)
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_send_command_failed_retries_and_fails_again(self, mock_client):
"""Test when the send("InfoDomainCommand) call fails with a 2400, prompting a retry
@ -186,7 +188,6 @@ class TestClient(TestCase):
Initialization succeeds
Send command fails (with 2400 code) prompting retry
Client closes and re-initializes, and command fails again with 2400"""
with less_console_noise():
# Mock the Client instance and its methods
# connect() and close() should succeed throughout
mock_connect = MagicMock()
@ -222,6 +223,7 @@ class TestClient(TestCase):
# send(login), send(command)
self.assertEquals(mock_send.call_count, 5)
@less_console_noise_decorator
@patch("epplibwrapper.client.Client")
def test_send_command_failure_prompts_successful_retry(self, mock_client):
"""Test when the send("InfoDomainCommand) call fails with a 2400, prompting a retry
@ -230,7 +232,6 @@ class TestClient(TestCase):
Initialization succeeds
Send command fails (with 2400 code) prompting retry
Client closes and re-initializes, and command succeeds"""
with less_console_noise():
# Mock the Client instance and its methods
# connect() and close() should succeed throughout
mock_connect = MagicMock()
@ -264,12 +265,12 @@ class TestClient(TestCase):
# send() is called 5 times: send(login), send(command) fail, send(logout), send(login), send(command)
self.assertEquals(mock_send.call_count, 5)
@less_console_noise_decorator
def fake_failure_send_concurrent_threads(self, command=None, cleaned=None):
"""
Raises a ConcurrentObjectUseError, which gevent throws when accessing
the same thread from two different locations.
"""
with less_console_noise():
# This error is thrown when two threads are being used concurrently
raise ConcurrentObjectUseError("This socket is already used by another greenlet")
@ -279,11 +280,11 @@ class TestClient(TestCase):
"""
pass # noqa
@less_console_noise_decorator
def fake_success_send(self, command=None, cleaned=None):
"""
Simulates receiving a success response from EPP.
"""
with less_console_noise():
mock = MagicMock(
code=1000,
msg="Command completed successfully",
@ -295,18 +296,18 @@ class TestClient(TestCase):
)
return mock
@less_console_noise_decorator
def fake_info_domain_received(self, command=None, cleaned=None):
"""
Simulates receiving a response by reading from a predefined XML file.
"""
with less_console_noise():
location = Path(__file__).parent / "utility" / "infoDomain.xml"
xml = (location).read_bytes()
return xml
@less_console_noise_decorator
def get_fake_epp_result(self):
"""Mimics a return from EPP by returning a dictionary in the same format"""
with less_console_noise():
result = {
"cl_tr_id": None,
"code": 1000,
@ -343,6 +344,7 @@ class TestClient(TestCase):
}
return result
@less_console_noise_decorator
def test_send_command_close_failure_recovers(self):
"""
Validates the resilience of the connection handling mechanism
@ -355,7 +357,6 @@ class TestClient(TestCase):
- Subsequently, the client re-initializes the connection.
- A retry of the command execution post-reinitialization succeeds.
"""
with less_console_noise():
expected_result = self.get_fake_epp_result()
wrapper = None
# Trigger a retry

View file

@ -793,7 +793,8 @@ class MockDb(TestCase):
User.objects.all().delete()
UserDomainRole.objects.all().delete()
DomainInvitation.objects.all().delete()
FederalAgency.objects.all().delete()
cls.federal_agency_1.delete()
cls.federal_agency_2.delete()
class MockDbForSharedTests(MockDb):

View file

@ -1909,10 +1909,6 @@ class TestFederalAgency(TestCase):
def setUp(self):
self.client = Client(HTTP_HOST="localhost:8080")
def tearDown(self):
super().tearDown()
FederalAgency.objects.all().delete()
@classmethod
def tearDownClass(cls):
super().tearDownClass()

View file

@ -1184,7 +1184,10 @@ class TestTransferFederalAgencyType(TestCase):
User.objects.all().delete()
Contact.objects.all().delete()
Website.objects.all().delete()
FederalAgency.objects.all().delete()
self.amtrak.delete()
self.legislative_branch.delete()
self.library_of_congress.delete()
self.gov_admin.delete()
def run_transfer_federal_agency_type(self):
"""

View file

@ -252,6 +252,7 @@ class ExportDataTest(MockDbForIndividualTests, MockEppLib):
# spaces and leading/trailing whitespace
csv_content = csv_content.replace(",,", "").replace(",", "").replace(" ", "").replace("\r\n", "\n").strip()
expected_content = expected_content.replace(",,", "").replace(",", "").replace(" ", "").strip()
self.maxDiff = None
self.assertEqual(csv_content, expected_content)
@less_console_noise_decorator
@ -432,6 +433,7 @@ class ExportDataTest(MockDbForIndividualTests, MockEppLib):
# spaces and leading/trailing whitespace
csv_content = csv_content.replace(",,", "").replace(",", "").replace(" ", "").replace("\r\n", "\n").strip()
expected_content = expected_content.replace(",,", "").replace(",", "").replace(" ", "").strip()
self.maxDiff = None
self.assertEqual(csv_content, expected_content)
@less_console_noise_decorator

View file

@ -43,7 +43,6 @@ class TestProcessedMigrations(TestCase):
DomainInformation.objects.all().delete()
DomainInvitation.objects.all().delete()
TransitionDomain.objects.all().delete()
FederalAgency.objects.all().delete()
# Delete users
User.objects.all().delete()
@ -185,6 +184,7 @@ class TestOrganizationMigration(TestCase):
"""Defines the file name of migration_json and the folder its contained in"""
self.test_data_file_location = "registrar/tests/data"
self.migration_json_filename = "test_migrationFilepaths.json"
self.federal_agency, _ = FederalAgency.objects.get_or_create(agency="Department of Commerce")
def tearDown(self):
"""Deletes all DB objects related to migrations"""
@ -197,6 +197,7 @@ class TestOrganizationMigration(TestCase):
# Delete users
User.objects.all().delete()
UserDomainRole.objects.all().delete()
self.federal_agency.delete()
def run_load_domains(self):
"""
@ -331,7 +332,6 @@ class TestOrganizationMigration(TestCase):
# Lets test the first one
transition = transition_domains.first()
federal_agency, _ = FederalAgency.objects.get_or_create(agency="Department of Commerce")
expected_transition_domain = TransitionDomain(
username="alexandra.bobbitt5@test.com",
domain_name="fakewebsite2.gov",
@ -340,7 +340,7 @@ class TestOrganizationMigration(TestCase):
generic_org_type="Federal",
organization_name="Fanoodle",
federal_type="Executive",
federal_agency=federal_agency,
federal_agency=self.federal_agency,
epp_creation_date=datetime.date(2004, 5, 7),
epp_expiration_date=datetime.date(2023, 9, 30),
first_name="Seline",
@ -395,7 +395,6 @@ class TestOrganizationMigration(TestCase):
# == Third, test that we've loaded data as we expect == #
_domain = Domain.objects.filter(name="fakewebsite2.gov").get()
domain_information = DomainInformation.objects.filter(domain=_domain).get()
federal_agency, _ = FederalAgency.objects.get_or_create(agency="Department of Commerce")
expected_creator = User.objects.filter(username="System").get()
expected_so = Contact.objects.filter(
@ -404,7 +403,7 @@ class TestOrganizationMigration(TestCase):
expected_domain_information = DomainInformation(
creator=expected_creator,
generic_org_type="federal",
federal_agency=federal_agency,
federal_agency=self.federal_agency,
federal_type="executive",
organization_name="Fanoodle",
address_line1="93001 Arizona Drive",
@ -451,7 +450,6 @@ class TestOrganizationMigration(TestCase):
# == Fourth, test that no data is overwritten as we expect == #
_domain = Domain.objects.filter(name="fakewebsite2.gov").get()
domain_information = DomainInformation.objects.filter(domain=_domain).get()
federal_agency, _ = FederalAgency.objects.get_or_create(agency="Department of Commerce")
expected_creator = User.objects.filter(username="System").get()
expected_so = Contact.objects.filter(
@ -460,7 +458,7 @@ class TestOrganizationMigration(TestCase):
expected_domain_information = DomainInformation(
creator=expected_creator,
generic_org_type="federal",
federal_agency=federal_agency,
federal_agency=self.federal_agency,
federal_type="executive",
organization_name="Fanoodle",
address_line1="93001 Galactic Way",