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 unittest.mock import MagicMock, patch
from pathlib import Path from pathlib import Path
from django.test import TestCase from django.test import TestCase
from api.tests.common import less_console_noise_decorator
from gevent.exceptions import ConcurrentObjectUseError from gevent.exceptions import ConcurrentObjectUseError
from epplibwrapper.client import EPPLibWrapper from epplibwrapper.client import EPPLibWrapper
from epplibwrapper.errors import RegistryError, LoginError from epplibwrapper.errors import RegistryError, LoginError
@ -24,100 +25,101 @@ logger = logging.getLogger(__name__)
class TestClient(TestCase): class TestClient(TestCase):
"""Test the EPPlibwrapper client""" """Test the EPPlibwrapper client"""
@less_console_noise_decorator
def fake_result(self, code, msg): def fake_result(self, code, msg):
"""Helper function to create a fake Result object""" """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")
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") @patch("epplibwrapper.client.Client")
def test_initialize_client_success(self, mock_client): def test_initialize_client_success(self, mock_client):
"""Test when the initialize_client is successful""" """Test when the initialize_client is successful"""
with less_console_noise(): # Mock the Client instance and its methods
# Mock the Client instance and its methods mock_connect = MagicMock()
mock_connect = MagicMock() # Create a mock Result instance
# Create a mock Result instance mock_result = MagicMock(spec=Result)
mock_result = MagicMock(spec=Result) mock_result.code = 200
mock_result.code = 200 mock_result.msg = "Success"
mock_result.msg = "Success" mock_result.res_data = ["data1", "data2"]
mock_result.res_data = ["data1", "data2"] mock_result.cl_tr_id = "client_id"
mock_result.cl_tr_id = "client_id" mock_result.sv_tr_id = "server_id"
mock_result.sv_tr_id = "server_id" mock_send = MagicMock(return_value=mock_result)
mock_send = MagicMock(return_value=mock_result) mock_client.return_value.connect = mock_connect
mock_client.return_value.connect = mock_connect mock_client.return_value.send = mock_send
mock_client.return_value.send = mock_send
# Create EPPLibWrapper instance and initialize client # Create EPPLibWrapper instance and initialize client
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
# Assert that connect method is called once # Assert that connect method is called once
mock_connect.assert_called_once() mock_connect.assert_called_once()
# Assert that _client is not None after initialization # Assert that _client is not None after initialization
self.assertIsNotNone(wrapper._client) self.assertIsNotNone(wrapper._client)
@less_console_noise_decorator
@patch("epplibwrapper.client.Client") @patch("epplibwrapper.client.Client")
def test_initialize_client_transport_error(self, mock_client): def test_initialize_client_transport_error(self, mock_client):
"""Test when the send(login) step of initialize_client raises a TransportError.""" """Test when the send(login) step of initialize_client raises a TransportError."""
with less_console_noise(): # Mock the Client instance and its methods
# Mock the Client instance and its methods mock_connect = MagicMock()
mock_connect = MagicMock() mock_send = MagicMock(side_effect=TransportError("Transport error"))
mock_send = MagicMock(side_effect=TransportError("Transport error")) mock_client.return_value.connect = mock_connect
mock_client.return_value.connect = mock_connect mock_client.return_value.send = mock_send
mock_client.return_value.send = mock_send
with self.assertRaises(RegistryError): with self.assertRaises(RegistryError):
# Create EPPLibWrapper instance and initialize client # Create EPPLibWrapper instance and initialize client
# if functioning as expected, initial __init__ should except # if functioning as expected, initial __init__ should except
# and log any Exception raised # and log any Exception raised
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
# so call _initialize_client a second time directly to test # so call _initialize_client a second time directly to test
# the raised exception # the raised exception
wrapper._initialize_client() wrapper._initialize_client()
@less_console_noise_decorator
@patch("epplibwrapper.client.Client") @patch("epplibwrapper.client.Client")
def test_initialize_client_login_error(self, mock_client): def test_initialize_client_login_error(self, mock_client):
"""Test when the send(login) step of initialize_client returns (2400) comamnd failed code.""" """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 the Client instance and its methods mock_connect = MagicMock()
mock_connect = MagicMock() # Create a mock Result instance
# Create a mock Result instance mock_result = MagicMock(spec=Result)
mock_result = MagicMock(spec=Result) mock_result.code = 2400
mock_result.code = 2400 mock_result.msg = "Login failed"
mock_result.msg = "Login failed" mock_result.res_data = ["data1", "data2"]
mock_result.res_data = ["data1", "data2"] mock_result.cl_tr_id = "client_id"
mock_result.cl_tr_id = "client_id" mock_result.sv_tr_id = "server_id"
mock_result.sv_tr_id = "server_id" mock_send = MagicMock(return_value=mock_result)
mock_send = MagicMock(return_value=mock_result) mock_client.return_value.connect = mock_connect
mock_client.return_value.connect = mock_connect mock_client.return_value.send = mock_send
mock_client.return_value.send = mock_send
with self.assertRaises(LoginError): with self.assertRaises(LoginError):
# Create EPPLibWrapper instance and initialize client # Create EPPLibWrapper instance and initialize client
# if functioning as expected, initial __init__ should except # if functioning as expected, initial __init__ should except
# and log any Exception raised # and log any Exception raised
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
# so call _initialize_client a second time directly to test # so call _initialize_client a second time directly to test
# the raised exception # the raised exception
wrapper._initialize_client() wrapper._initialize_client()
@less_console_noise_decorator
@patch("epplibwrapper.client.Client") @patch("epplibwrapper.client.Client")
def test_initialize_client_unknown_exception(self, mock_client): def test_initialize_client_unknown_exception(self, mock_client):
"""Test when the send(login) step of initialize_client raises an unexpected Exception.""" """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 the Client instance and its methods mock_connect = MagicMock()
mock_connect = MagicMock() mock_send = MagicMock(side_effect=Exception("Unknown exception"))
mock_send = MagicMock(side_effect=Exception("Unknown exception")) mock_client.return_value.connect = mock_connect
mock_client.return_value.connect = mock_connect mock_client.return_value.send = mock_send
mock_client.return_value.send = mock_send
with self.assertRaises(RegistryError): with self.assertRaises(RegistryError):
# Create EPPLibWrapper instance and initialize client # Create EPPLibWrapper instance and initialize client
# if functioning as expected, initial __init__ should except # if functioning as expected, initial __init__ should except
# and log any Exception raised # and log any Exception raised
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
# so call _initialize_client a second time directly to test # so call _initialize_client a second time directly to test
# the raised exception # the raised exception
wrapper._initialize_client() wrapper._initialize_client()
@less_console_noise_decorator
@patch("epplibwrapper.client.Client") @patch("epplibwrapper.client.Client")
def test_initialize_client_fails_recovers_with_send_command(self, mock_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 """Test when the initialize_client fails on the connect() step. And then a subsequent
@ -127,56 +129,56 @@ class TestClient(TestCase):
Initialization step fails at app init Initialization step fails at app init
Send command fails (with 2400 code) prompting retry Send command fails (with 2400 code) prompting retry
Client closes and re-initializes, and command is sent successfully""" Client closes and re-initializes, and command is sent successfully"""
with less_console_noise(): # Mock the Client instance and its methods
# Mock the Client instance and its methods # close() should return successfully
# close() should return successfully mock_close = MagicMock()
mock_close = MagicMock() mock_client.return_value.close = mock_close
mock_client.return_value.close = mock_close # Create success and failure results
# Create success and failure results command_success_result = self.fake_result(1000, "Command completed successfully")
command_success_result = self.fake_result(1000, "Command completed successfully") command_failure_result = self.fake_result(2400, "Command failed")
command_failure_result = self.fake_result(2400, "Command failed") # side_effect for the connect() calls
# side_effect for the connect() calls # first connect() should raise an Exception
# first connect() should raise an Exception # subsequent connect() calls should return success
# subsequent connect() calls should return success connect_call_count = 0
connect_call_count = 0
def connect_side_effect(*args, **kwargs): def connect_side_effect(*args, **kwargs):
nonlocal connect_call_count nonlocal connect_call_count
connect_call_count += 1 connect_call_count += 1
if connect_call_count == 1: if connect_call_count == 1:
raise Exception("Connection failed") raise Exception("Connection failed")
else: else:
return command_success_result return command_success_result
mock_connect = MagicMock(side_effect=connect_side_effect) mock_connect = MagicMock(side_effect=connect_side_effect)
mock_client.return_value.connect = mock_connect mock_client.return_value.connect = mock_connect
# side_effect for the send() calls # side_effect for the send() calls
# first send will be the send("InfoDomainCommand") and should fail # first send will be the send("InfoDomainCommand") and should fail
# subsequend send() calls should return success # subsequend send() calls should return success
send_call_count = 0 send_call_count = 0
def send_side_effect(*args, **kwargs): def send_side_effect(*args, **kwargs):
nonlocal send_call_count nonlocal send_call_count
send_call_count += 1 send_call_count += 1
if send_call_count == 1: if send_call_count == 1:
return command_failure_result return command_failure_result
else: else:
return command_success_result return command_success_result
mock_send = MagicMock(side_effect=send_side_effect) mock_send = MagicMock(side_effect=send_side_effect)
mock_client.return_value.send = mock_send mock_client.return_value.send = mock_send
# Create EPPLibWrapper instance and call send command # Create EPPLibWrapper instance and call send command
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
wrapper.send("InfoDomainCommand", cleaned=True) wrapper.send("InfoDomainCommand", cleaned=True)
# two connect() calls should be made, the initial failed connect() # two connect() calls should be made, the initial failed connect()
# and the successful connect() during retry() # and the successful connect() during retry()
self.assertEquals(mock_connect.call_count, 2) self.assertEquals(mock_connect.call_count, 2)
# close() should only be called once, during retry() # close() should only be called once, during retry()
mock_close.assert_called_once() mock_close.assert_called_once()
# send called 4 times: failed send("InfoDomainCommand"), passed send(logout), # send called 4 times: failed send("InfoDomainCommand"), passed send(logout),
# passed send(login), passed send("InfoDomainCommand") # passed send(login), passed send("InfoDomainCommand")
self.assertEquals(mock_send.call_count, 4) self.assertEquals(mock_send.call_count, 4)
@less_console_noise_decorator
@patch("epplibwrapper.client.Client") @patch("epplibwrapper.client.Client")
def test_send_command_failed_retries_and_fails_again(self, mock_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 """Test when the send("InfoDomainCommand) call fails with a 2400, prompting a retry
@ -186,42 +188,42 @@ class TestClient(TestCase):
Initialization succeeds Initialization succeeds
Send command fails (with 2400 code) prompting retry Send command fails (with 2400 code) prompting retry
Client closes and re-initializes, and command fails again with 2400""" Client closes and re-initializes, and command fails again with 2400"""
with less_console_noise(): # Mock the Client instance and its methods
# Mock the Client instance and its methods # connect() and close() should succeed throughout
# connect() and close() should succeed throughout mock_connect = MagicMock()
mock_connect = MagicMock() mock_close = MagicMock()
mock_close = MagicMock() # Create a mock Result instance
# Create a mock Result instance send_command_success_result = self.fake_result(1000, "Command completed successfully")
send_command_success_result = self.fake_result(1000, "Command completed successfully") send_command_failure_result = self.fake_result(2400, "Command failed")
send_command_failure_result = self.fake_result(2400, "Command failed")
# side_effect for send command, passes for all other sends (login, logout), but # side_effect for send command, passes for all other sends (login, logout), but
# fails for send("InfoDomainCommand") # fails for send("InfoDomainCommand")
def side_effect(*args, **kwargs): def side_effect(*args, **kwargs):
if args[0] == "InfoDomainCommand": if args[0] == "InfoDomainCommand":
return send_command_failure_result return send_command_failure_result
else: else:
return send_command_success_result return send_command_success_result
mock_send = MagicMock(side_effect=side_effect) mock_send = MagicMock(side_effect=side_effect)
mock_client.return_value.connect = mock_connect mock_client.return_value.connect = mock_connect
mock_client.return_value.close = mock_close mock_client.return_value.close = mock_close
mock_client.return_value.send = mock_send mock_client.return_value.send = mock_send
with self.assertRaises(RegistryError): with self.assertRaises(RegistryError):
# Create EPPLibWrapper instance and initialize client # Create EPPLibWrapper instance and initialize client
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
# call send, which should throw a RegistryError (after retry) # call send, which should throw a RegistryError (after retry)
wrapper.send("InfoDomainCommand", cleaned=True) wrapper.send("InfoDomainCommand", cleaned=True)
# connect() should be called twice, once during initialization, second time # connect() should be called twice, once during initialization, second time
# during retry # during retry
self.assertEquals(mock_connect.call_count, 2) self.assertEquals(mock_connect.call_count, 2)
# close() is called once during retry # close() is called once during retry
mock_close.assert_called_once() mock_close.assert_called_once()
# send() is called 5 times: send(login), send(command) fails, send(logout) # send() is called 5 times: send(login), send(command) fails, send(logout)
# send(login), send(command) # send(login), send(command)
self.assertEquals(mock_send.call_count, 5) self.assertEquals(mock_send.call_count, 5)
@less_console_noise_decorator
@patch("epplibwrapper.client.Client") @patch("epplibwrapper.client.Client")
def test_send_command_failure_prompts_successful_retry(self, mock_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 """Test when the send("InfoDomainCommand) call fails with a 2400, prompting a retry
@ -230,48 +232,47 @@ class TestClient(TestCase):
Initialization succeeds Initialization succeeds
Send command fails (with 2400 code) prompting retry Send command fails (with 2400 code) prompting retry
Client closes and re-initializes, and command succeeds""" Client closes and re-initializes, and command succeeds"""
with less_console_noise(): # Mock the Client instance and its methods
# Mock the Client instance and its methods # connect() and close() should succeed throughout
# connect() and close() should succeed throughout mock_connect = MagicMock()
mock_connect = MagicMock() mock_close = MagicMock()
mock_close = MagicMock() # create success and failure result messages
# create success and failure result messages send_command_success_result = self.fake_result(1000, "Command completed successfully")
send_command_success_result = self.fake_result(1000, "Command completed successfully") send_command_failure_result = self.fake_result(2400, "Command failed")
send_command_failure_result = self.fake_result(2400, "Command failed") # side_effect for send call, initial send(login) succeeds during initialization, next send(command)
# side_effect for send call, initial send(login) succeeds during initialization, next send(command) # fails, subsequent sends (logout, login, command) all succeed
# fails, subsequent sends (logout, login, command) all succeed send_call_count = 0
send_call_count = 0
def side_effect(*args, **kwargs): def side_effect(*args, **kwargs):
nonlocal send_call_count nonlocal send_call_count
send_call_count += 1 send_call_count += 1
if send_call_count == 2: if send_call_count == 2:
return send_command_failure_result return send_command_failure_result
else: else:
return send_command_success_result return send_command_success_result
mock_send = MagicMock(side_effect=side_effect) mock_send = MagicMock(side_effect=side_effect)
mock_client.return_value.connect = mock_connect mock_client.return_value.connect = mock_connect
mock_client.return_value.close = mock_close mock_client.return_value.close = mock_close
mock_client.return_value.send = mock_send mock_client.return_value.send = mock_send
# Create EPPLibWrapper instance and initialize client # Create EPPLibWrapper instance and initialize client
wrapper = EPPLibWrapper() wrapper = EPPLibWrapper()
wrapper.send("InfoDomainCommand", cleaned=True) wrapper.send("InfoDomainCommand", cleaned=True)
# connect() is called twice, once during initialization of app, once during retry # connect() is called twice, once during initialization of app, once during retry
self.assertEquals(mock_connect.call_count, 2) self.assertEquals(mock_connect.call_count, 2)
# close() is called once, during retry # close() is called once, during retry
mock_close.assert_called_once() mock_close.assert_called_once()
# send() is called 5 times: send(login), send(command) fail, send(logout), send(login), send(command) # send() is called 5 times: send(login), send(command) fail, send(logout), send(login), send(command)
self.assertEquals(mock_send.call_count, 5) self.assertEquals(mock_send.call_count, 5)
@less_console_noise_decorator
def fake_failure_send_concurrent_threads(self, command=None, cleaned=None): def fake_failure_send_concurrent_threads(self, command=None, cleaned=None):
""" """
Raises a ConcurrentObjectUseError, which gevent throws when accessing Raises a ConcurrentObjectUseError, which gevent throws when accessing
the same thread from two different locations. the same thread from two different locations.
""" """
with less_console_noise(): # This error is thrown when two threads are being used concurrently
# This error is thrown when two threads are being used concurrently raise ConcurrentObjectUseError("This socket is already used by another greenlet")
raise ConcurrentObjectUseError("This socket is already used by another greenlet")
def do_nothing(self, command=None): def do_nothing(self, command=None):
""" """
@ -279,70 +280,71 @@ class TestClient(TestCase):
""" """
pass # noqa pass # noqa
@less_console_noise_decorator
def fake_success_send(self, command=None, cleaned=None): def fake_success_send(self, command=None, cleaned=None):
""" """
Simulates receiving a success response from EPP. Simulates receiving a success response from EPP.
""" """
with less_console_noise(): mock = MagicMock(
mock = MagicMock( code=1000,
code=1000, msg="Command completed successfully",
msg="Command completed successfully", res_data=None,
res_data=None, cl_tr_id="xkw1uo#2023-10-17T15:29:09.559376",
cl_tr_id="xkw1uo#2023-10-17T15:29:09.559376", sv_tr_id="5CcH4gxISuGkq8eqvr1UyQ==-35a",
sv_tr_id="5CcH4gxISuGkq8eqvr1UyQ==-35a", extensions=[],
extensions=[], msg_q=None,
msg_q=None, )
) return mock
return mock
@less_console_noise_decorator
def fake_info_domain_received(self, command=None, cleaned=None): def fake_info_domain_received(self, command=None, cleaned=None):
""" """
Simulates receiving a response by reading from a predefined XML file. Simulates receiving a response by reading from a predefined XML file.
""" """
with less_console_noise(): location = Path(__file__).parent / "utility" / "infoDomain.xml"
location = Path(__file__).parent / "utility" / "infoDomain.xml" xml = (location).read_bytes()
xml = (location).read_bytes() return xml
return xml
@less_console_noise_decorator
def get_fake_epp_result(self): def get_fake_epp_result(self):
"""Mimics a return from EPP by returning a dictionary in the same format""" """Mimics a return from EPP by returning a dictionary in the same format"""
with less_console_noise(): result = {
result = { "cl_tr_id": None,
"cl_tr_id": None, "code": 1000,
"code": 1000, "extensions": [],
"extensions": [], "msg": "Command completed successfully",
"msg": "Command completed successfully", "msg_q": None,
"msg_q": None, "res_data": [
"res_data": [ info.InfoDomainResultData(
info.InfoDomainResultData( roid="DF1340360-GOV",
roid="DF1340360-GOV", statuses=[
statuses=[ common.Status(
common.Status( state="serverTransferProhibited",
state="serverTransferProhibited", description=None,
description=None, lang="en",
lang="en", ),
), common.Status(state="inactive", description=None, lang="en"),
common.Status(state="inactive", description=None, lang="en"), ],
], cl_id="gov2023-ote",
cl_id="gov2023-ote", cr_id="gov2023-ote",
cr_id="gov2023-ote", cr_date=datetime.datetime(2023, 8, 15, 23, 56, 36, tzinfo=tzlocal()),
cr_date=datetime.datetime(2023, 8, 15, 23, 56, 36, tzinfo=tzlocal()), up_id="gov2023-ote",
up_id="gov2023-ote", up_date=datetime.datetime(2023, 8, 17, 2, 3, 19, tzinfo=tzlocal()),
up_date=datetime.datetime(2023, 8, 17, 2, 3, 19, tzinfo=tzlocal()), tr_date=None,
tr_date=None, name="test3.gov",
name="test3.gov", registrant="TuaWnx9hnm84GCSU",
registrant="TuaWnx9hnm84GCSU", admins=[],
admins=[], nsset=None,
nsset=None, keyset=None,
keyset=None, ex_date=datetime.date(2024, 8, 15),
ex_date=datetime.date(2024, 8, 15), auth_info=info.DomainAuthInfo(pw="2fooBAR123fooBaz"),
auth_info=info.DomainAuthInfo(pw="2fooBAR123fooBaz"), )
) ],
], "sv_tr_id": "wRRNVhKhQW2m6wsUHbo/lA==-29a",
"sv_tr_id": "wRRNVhKhQW2m6wsUHbo/lA==-29a", }
} return result
return result
@less_console_noise_decorator
def test_send_command_close_failure_recovers(self): def test_send_command_close_failure_recovers(self):
""" """
Validates the resilience of the connection handling mechanism Validates the resilience of the connection handling mechanism
@ -355,28 +357,27 @@ class TestClient(TestCase):
- Subsequently, the client re-initializes the connection. - Subsequently, the client re-initializes the connection.
- A retry of the command execution post-reinitialization succeeds. - A retry of the command execution post-reinitialization succeeds.
""" """
with less_console_noise(): expected_result = self.get_fake_epp_result()
expected_result = self.get_fake_epp_result() wrapper = None
wrapper = None # Trigger a retry
# Trigger a retry # Do nothing on connect, as we aren't testing it and want to connect while
# Do nothing on connect, as we aren't testing it and want to connect while # mimicking the rest of the client as closely as possible (which is not entirely possible with MagicMock)
# mimicking the rest of the client as closely as possible (which is not entirely possible with MagicMock) with patch.object(EPPLibWrapper, "_connect", self.do_nothing):
with patch.object(EPPLibWrapper, "_connect", self.do_nothing): with patch.object(SocketTransport, "send", self.fake_failure_send_concurrent_threads):
with patch.object(SocketTransport, "send", self.fake_failure_send_concurrent_threads): wrapper = EPPLibWrapper()
wrapper = EPPLibWrapper() tested_command = commands.InfoDomain(name="test.gov")
tested_command = commands.InfoDomain(name="test.gov") try:
try: wrapper.send(tested_command, cleaned=True)
wrapper.send(tested_command, cleaned=True) except RegistryError as err:
except RegistryError as err: expected_error = "InfoDomain failed to execute due to an unknown error."
expected_error = "InfoDomain failed to execute due to an unknown error." self.assertEqual(err.args[0], expected_error)
self.assertEqual(err.args[0], expected_error) else:
else: self.fail("Registry error was not thrown")
self.fail("Registry error was not thrown")
# After a retry, try sending again to see if the connection recovers # After a retry, try sending again to see if the connection recovers
with patch.object(EPPLibWrapper, "_connect", self.do_nothing): with patch.object(EPPLibWrapper, "_connect", self.do_nothing):
with patch.object(SocketTransport, "send", self.fake_success_send), patch.object( with patch.object(SocketTransport, "send", self.fake_success_send), patch.object(
SocketTransport, "receive", self.fake_info_domain_received SocketTransport, "receive", self.fake_info_domain_received
): ):
result = wrapper.send(tested_command, cleaned=True) result = wrapper.send(tested_command, cleaned=True)
self.assertEqual(expected_result, result.__dict__) self.assertEqual(expected_result, result.__dict__)

View file

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

View file

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

View file

@ -1184,7 +1184,10 @@ class TestTransferFederalAgencyType(TestCase):
User.objects.all().delete() User.objects.all().delete()
Contact.objects.all().delete() Contact.objects.all().delete()
Website.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): def run_transfer_federal_agency_type(self):
""" """

View file

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

View file

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