Clean up common mock class and how it's inherited

This commit is contained in:
Rachid Mrad 2024-03-05 14:28:12 -05:00
parent 266f6fedfd
commit 091e4c900e
No known key found for this signature in database
4 changed files with 251 additions and 338 deletions

View file

@ -13,6 +13,8 @@ from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model, login from django.contrib.auth import get_user_model, login
from django.utils.timezone import make_aware from django.utils.timezone import make_aware
from datetime import date, datetime, timedelta
from django.utils import timezone
from registrar.models import ( from registrar.models import (
Contact, Contact,
@ -35,6 +37,7 @@ from epplibwrapper import (
ErrorCode, ErrorCode,
responses, responses,
) )
from registrar.models.user_domain_role import UserDomainRole
from registrar.models.utility.contact_error import ContactError, ContactErrorCodes from registrar.models.utility.contact_error import ContactError, ContactErrorCodes
@ -470,6 +473,176 @@ class AuditedAdminMockData:
application.alternative_domains.add(alt) application.alternative_domains.add(alt)
return application return application
class MockDb(TestCase):
"""Hardcoded mocks make test case assertions sraightforward."""
def setUp(self):
super().setUp()
username = "test_user"
first_name = "First"
last_name = "Last"
email = "info@example.com"
self.user = get_user_model().objects.create(
username=username, first_name=first_name, last_name=last_name, email=email
)
# Create a time-aware current date
current_datetime = timezone.now()
# Extract the date part
current_date = current_datetime.date()
# Create start and end dates using timedelta
self.end_date = current_date + timedelta(days=2)
self.start_date = current_date - timedelta(days=2)
self.domain_1, _ = Domain.objects.get_or_create(
name="cdomain1.gov", state=Domain.State.READY, first_ready=timezone.now()
)
self.domain_2, _ = Domain.objects.get_or_create(name="adomain2.gov", state=Domain.State.DNS_NEEDED)
self.domain_3, _ = Domain.objects.get_or_create(name="ddomain3.gov", state=Domain.State.ON_HOLD)
self.domain_4, _ = Domain.objects.get_or_create(name="bdomain4.gov", state=Domain.State.UNKNOWN)
self.domain_4, _ = Domain.objects.get_or_create(name="bdomain4.gov", state=Domain.State.UNKNOWN)
self.domain_5, _ = Domain.objects.get_or_create(
name="bdomain5.gov", state=Domain.State.DELETED, deleted=timezone.make_aware(datetime(2023, 11, 1))
)
self.domain_6, _ = Domain.objects.get_or_create(
name="bdomain6.gov", state=Domain.State.DELETED, deleted=timezone.make_aware(datetime(1980, 10, 16))
)
self.domain_7, _ = Domain.objects.get_or_create(
name="xdomain7.gov", state=Domain.State.DELETED, deleted=timezone.now()
)
self.domain_8, _ = Domain.objects.get_or_create(
name="sdomain8.gov", state=Domain.State.DELETED, deleted=timezone.now()
)
# We use timezone.make_aware to sync to server time a datetime object with the current date (using date.today())
# and a specific time (using datetime.min.time()).
# Deleted yesterday
self.domain_9, _ = Domain.objects.get_or_create(
name="zdomain9.gov",
state=Domain.State.DELETED,
deleted=timezone.make_aware(datetime.combine(date.today() - timedelta(days=1), datetime.min.time())),
)
# ready tomorrow
self.domain_10, _ = Domain.objects.get_or_create(
name="adomain10.gov",
state=Domain.State.READY,
first_ready=timezone.make_aware(datetime.combine(date.today() + timedelta(days=1), datetime.min.time())),
)
self.domain_information_1, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_1,
organization_type="federal",
federal_agency="World War I Centennial Commission",
federal_type="executive",
is_election_board=True
)
self.domain_information_2, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_2,
organization_type="interstate",
is_election_board=True
)
self.domain_information_3, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_3,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=True
)
self.domain_information_4, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_4,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=True
)
self.domain_information_5, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_5,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_6, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_6,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_7, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_7,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_8, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_8,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_9, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_9,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_10, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_10,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
meoward_user = get_user_model().objects.create(
username="meoward_username", first_name="first_meoward", last_name="last_meoward", email="meoward@rocks.com"
)
lebowski_user = get_user_model().objects.create(
username="big_lebowski", first_name="big", last_name="lebowski", email="big_lebowski@dude.co"
)
_, created = UserDomainRole.objects.get_or_create(
user=meoward_user, domain=self.domain_1, role=UserDomainRole.Roles.MANAGER
)
_, created = UserDomainRole.objects.get_or_create(
user=self.user, domain=self.domain_1, role=UserDomainRole.Roles.MANAGER
)
_, created = UserDomainRole.objects.get_or_create(
user=lebowski_user, domain=self.domain_1, role=UserDomainRole.Roles.MANAGER
)
_, created = UserDomainRole.objects.get_or_create(
user=meoward_user, domain=self.domain_2, role=UserDomainRole.Roles.MANAGER
)
with less_console_noise():
self.domain_request_1 = completed_application(status=DomainApplication.ApplicationStatus.STARTED, name="city1.gov")
self.domain_request_2 = completed_application(status=DomainApplication.ApplicationStatus.IN_REVIEW, name="city2.gov")
self.domain_request_3 = completed_application(status=DomainApplication.ApplicationStatus.STARTED, name="city3.gov")
self.domain_request_4 = completed_application(status=DomainApplication.ApplicationStatus.STARTED, name="city4.gov")
self.domain_request_5 = completed_application(status=DomainApplication.ApplicationStatus.APPROVED, name="city5.gov")
self.domain_request_3.submit()
self.domain_request_3.save()
self.domain_request_4.submit()
self.domain_request_4.save()
def tearDown(self):
super().tearDown()
PublicContact.objects.all().delete()
Domain.objects.all().delete()
DomainInformation.objects.all().delete()
DomainApplication.objects.all().delete()
User.objects.all().delete()
UserDomainRole.objects.all().delete()
def mock_user(): def mock_user():
@ -645,7 +818,7 @@ class MockEppLib(TestCase):
self, self,
id, id,
email, email,
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
pw="thisisnotapassword", pw="thisisnotapassword",
): ):
fake = info.InfoContactResultData( fake = info.InfoContactResultData(
@ -683,82 +856,82 @@ class MockEppLib(TestCase):
mockDataInfoDomain = fakedEppObject( mockDataInfoDomain = fakedEppObject(
"fakePw", "fakePw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)], contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)],
hosts=["fake.host.com"], hosts=["fake.host.com"],
statuses=[ statuses=[
common.Status(state="serverTransferProhibited", description="", lang="en"), common.Status(state="serverTransferProhibited", description="", lang="en"),
common.Status(state="inactive", description="", lang="en"), common.Status(state="inactive", description="", lang="en"),
], ],
ex_date=datetime.date(2023, 5, 25), ex_date=date(2023, 5, 25),
) )
mockDataInfoDomainSubdomain = fakedEppObject( mockDataInfoDomainSubdomain = fakedEppObject(
"fakePw", "fakePw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)], contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)],
hosts=["fake.meoward.gov"], hosts=["fake.meoward.gov"],
statuses=[ statuses=[
common.Status(state="serverTransferProhibited", description="", lang="en"), common.Status(state="serverTransferProhibited", description="", lang="en"),
common.Status(state="inactive", description="", lang="en"), common.Status(state="inactive", description="", lang="en"),
], ],
ex_date=datetime.date(2023, 5, 25), ex_date=date(2023, 5, 25),
) )
mockDataInfoDomainSubdomainAndIPAddress = fakedEppObject( mockDataInfoDomainSubdomainAndIPAddress = fakedEppObject(
"fakePw", "fakePw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)], contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)],
hosts=["fake.meow.gov"], hosts=["fake.meow.gov"],
statuses=[ statuses=[
common.Status(state="serverTransferProhibited", description="", lang="en"), common.Status(state="serverTransferProhibited", description="", lang="en"),
common.Status(state="inactive", description="", lang="en"), common.Status(state="inactive", description="", lang="en"),
], ],
ex_date=datetime.date(2023, 5, 25), ex_date=date(2023, 5, 25),
addrs=[common.Ip(addr="2.0.0.8")], addrs=[common.Ip(addr="2.0.0.8")],
) )
mockDataInfoDomainNotSubdomainNoIP = fakedEppObject( mockDataInfoDomainNotSubdomainNoIP = fakedEppObject(
"fakePw", "fakePw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)], contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)],
hosts=["fake.meow.com"], hosts=["fake.meow.com"],
statuses=[ statuses=[
common.Status(state="serverTransferProhibited", description="", lang="en"), common.Status(state="serverTransferProhibited", description="", lang="en"),
common.Status(state="inactive", description="", lang="en"), common.Status(state="inactive", description="", lang="en"),
], ],
ex_date=datetime.date(2023, 5, 25), ex_date=date(2023, 5, 25),
) )
mockDataInfoDomainSubdomainNoIP = fakedEppObject( mockDataInfoDomainSubdomainNoIP = fakedEppObject(
"fakePw", "fakePw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)], contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)],
hosts=["fake.subdomainwoip.gov"], hosts=["fake.subdomainwoip.gov"],
statuses=[ statuses=[
common.Status(state="serverTransferProhibited", description="", lang="en"), common.Status(state="serverTransferProhibited", description="", lang="en"),
common.Status(state="inactive", description="", lang="en"), common.Status(state="inactive", description="", lang="en"),
], ],
ex_date=datetime.date(2023, 5, 25), ex_date=date(2023, 5, 25),
) )
mockDataExtensionDomain = fakedEppObject( mockDataExtensionDomain = fakedEppObject(
"fakePw", "fakePw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)], contacts=[common.DomainContact(contact="123", type=PublicContact.ContactTypeChoices.SECURITY)],
hosts=["fake.host.com"], hosts=["fake.host.com"],
statuses=[ statuses=[
common.Status(state="serverTransferProhibited", description="", lang="en"), common.Status(state="serverTransferProhibited", description="", lang="en"),
common.Status(state="inactive", description="", lang="en"), common.Status(state="inactive", description="", lang="en"),
], ],
ex_date=datetime.date(2023, 11, 15), ex_date=date(2023, 11, 15),
) )
mockDataInfoContact = mockDataInfoDomain.dummyInfoContactResultData( mockDataInfoContact = mockDataInfoDomain.dummyInfoContactResultData(
"123", "123@mail.gov", datetime.datetime(2023, 5, 25, 19, 45, 35), "lastPw" "123", "123@mail.gov", datetime(2023, 5, 25, 19, 45, 35), "lastPw"
) )
InfoDomainWithContacts = fakedEppObject( InfoDomainWithContacts = fakedEppObject(
"fakepw", "fakepw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[ contacts=[
common.DomainContact( common.DomainContact(
contact="securityContact", contact="securityContact",
@ -783,7 +956,7 @@ class MockEppLib(TestCase):
InfoDomainWithDefaultSecurityContact = fakedEppObject( InfoDomainWithDefaultSecurityContact = fakedEppObject(
"fakepw", "fakepw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[ contacts=[
common.DomainContact( common.DomainContact(
contact="defaultSec", contact="defaultSec",
@ -798,11 +971,11 @@ class MockEppLib(TestCase):
) )
mockVerisignDataInfoContact = mockDataInfoDomain.dummyInfoContactResultData( mockVerisignDataInfoContact = mockDataInfoDomain.dummyInfoContactResultData(
"defaultVeri", "registrar@dotgov.gov", datetime.datetime(2023, 5, 25, 19, 45, 35), "lastPw" "defaultVeri", "registrar@dotgov.gov", datetime(2023, 5, 25, 19, 45, 35), "lastPw"
) )
InfoDomainWithVerisignSecurityContact = fakedEppObject( InfoDomainWithVerisignSecurityContact = fakedEppObject(
"fakepw", "fakepw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[ contacts=[
common.DomainContact( common.DomainContact(
contact="defaultVeri", contact="defaultVeri",
@ -818,7 +991,7 @@ class MockEppLib(TestCase):
InfoDomainWithDefaultTechnicalContact = fakedEppObject( InfoDomainWithDefaultTechnicalContact = fakedEppObject(
"fakepw", "fakepw",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[ contacts=[
common.DomainContact( common.DomainContact(
contact="defaultTech", contact="defaultTech",
@ -843,14 +1016,14 @@ class MockEppLib(TestCase):
infoDomainNoContact = fakedEppObject( infoDomainNoContact = fakedEppObject(
"security", "security",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[], contacts=[],
hosts=["fake.host.com"], hosts=["fake.host.com"],
) )
infoDomainThreeHosts = fakedEppObject( infoDomainThreeHosts = fakedEppObject(
"my-nameserver.gov", "my-nameserver.gov",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[], contacts=[],
hosts=[ hosts=[
"ns1.my-nameserver-1.com", "ns1.my-nameserver-1.com",
@ -861,43 +1034,43 @@ class MockEppLib(TestCase):
infoDomainNoHost = fakedEppObject( infoDomainNoHost = fakedEppObject(
"my-nameserver.gov", "my-nameserver.gov",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[], contacts=[],
hosts=[], hosts=[],
) )
infoDomainTwoHosts = fakedEppObject( infoDomainTwoHosts = fakedEppObject(
"my-nameserver.gov", "my-nameserver.gov",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[], contacts=[],
hosts=["ns1.my-nameserver-1.com", "ns1.my-nameserver-2.com"], hosts=["ns1.my-nameserver-1.com", "ns1.my-nameserver-2.com"],
) )
mockDataInfoHosts = fakedEppObject( mockDataInfoHosts = fakedEppObject(
"lastPw", "lastPw",
cr_date=make_aware(datetime.datetime(2023, 8, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 8, 25, 19, 45, 35)),
addrs=[common.Ip(addr="1.2.3.4"), common.Ip(addr="2.3.4.5")], addrs=[common.Ip(addr="1.2.3.4"), common.Ip(addr="2.3.4.5")],
) )
mockDataInfoHosts1IP = fakedEppObject( mockDataInfoHosts1IP = fakedEppObject(
"lastPw", "lastPw",
cr_date=make_aware(datetime.datetime(2023, 8, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 8, 25, 19, 45, 35)),
addrs=[common.Ip(addr="2.0.0.8")], addrs=[common.Ip(addr="2.0.0.8")],
) )
mockDataInfoHostsNotSubdomainNoIP = fakedEppObject( mockDataInfoHostsNotSubdomainNoIP = fakedEppObject(
"lastPw", "lastPw",
cr_date=make_aware(datetime.datetime(2023, 8, 26, 19, 45, 35)), cr_date=make_aware(datetime(2023, 8, 26, 19, 45, 35)),
addrs=[], addrs=[],
) )
mockDataInfoHostsSubdomainNoIP = fakedEppObject( mockDataInfoHostsSubdomainNoIP = fakedEppObject(
"lastPw", "lastPw",
cr_date=make_aware(datetime.datetime(2023, 8, 27, 19, 45, 35)), cr_date=make_aware(datetime(2023, 8, 27, 19, 45, 35)),
addrs=[], addrs=[],
) )
mockDataHostChange = fakedEppObject("lastPw", cr_date=make_aware(datetime.datetime(2023, 8, 25, 19, 45, 35))) mockDataHostChange = fakedEppObject("lastPw", cr_date=make_aware(datetime(2023, 8, 25, 19, 45, 35)))
addDsData1 = { addDsData1 = {
"keyTag": 1234, "keyTag": 1234,
"alg": 3, "alg": 3,
@ -929,7 +1102,7 @@ class MockEppLib(TestCase):
infoDomainHasIP = fakedEppObject( infoDomainHasIP = fakedEppObject(
"nameserverwithip.gov", "nameserverwithip.gov",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[ contacts=[
common.DomainContact( common.DomainContact(
contact="securityContact", contact="securityContact",
@ -954,7 +1127,7 @@ class MockEppLib(TestCase):
justNameserver = fakedEppObject( justNameserver = fakedEppObject(
"justnameserver.com", "justnameserver.com",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[ contacts=[
common.DomainContact( common.DomainContact(
contact="securityContact", contact="securityContact",
@ -977,7 +1150,7 @@ class MockEppLib(TestCase):
infoDomainCheckHostIPCombo = fakedEppObject( infoDomainCheckHostIPCombo = fakedEppObject(
"nameserversubdomain.gov", "nameserversubdomain.gov",
cr_date=make_aware(datetime.datetime(2023, 5, 25, 19, 45, 35)), cr_date=make_aware(datetime(2023, 5, 25, 19, 45, 35)),
contacts=[], contacts=[],
hosts=[ hosts=[
"ns1.nameserversubdomain.gov", "ns1.nameserversubdomain.gov",
@ -987,27 +1160,27 @@ class MockEppLib(TestCase):
mockRenewedDomainExpDate = fakedEppObject( mockRenewedDomainExpDate = fakedEppObject(
"fake.gov", "fake.gov",
ex_date=datetime.date(2023, 5, 25), ex_date=date(2023, 5, 25),
) )
mockButtonRenewedDomainExpDate = fakedEppObject( mockButtonRenewedDomainExpDate = fakedEppObject(
"fake.gov", "fake.gov",
ex_date=datetime.date(2025, 5, 25), ex_date=date(2025, 5, 25),
) )
mockDnsNeededRenewedDomainExpDate = fakedEppObject( mockDnsNeededRenewedDomainExpDate = fakedEppObject(
"fakeneeded.gov", "fakeneeded.gov",
ex_date=datetime.date(2023, 2, 15), ex_date=date(2023, 2, 15),
) )
mockMaximumRenewedDomainExpDate = fakedEppObject( mockMaximumRenewedDomainExpDate = fakedEppObject(
"fakemaximum.gov", "fakemaximum.gov",
ex_date=datetime.date(2024, 12, 31), ex_date=date(2024, 12, 31),
) )
mockRecentRenewedDomainExpDate = fakedEppObject( mockRecentRenewedDomainExpDate = fakedEppObject(
"waterbutpurple.gov", "waterbutpurple.gov",
ex_date=datetime.date(2024, 11, 15), ex_date=date(2024, 11, 15),
) )
def _mockDomainName(self, _name, _avail=False): def _mockDomainName(self, _name, _avail=False):

View file

@ -1,174 +0,0 @@
from django.test import TestCase
from django.contrib.auth import get_user_model
from api.tests.common import less_console_noise
from registrar.models.domain_application import DomainApplication
from registrar.models.domain_information import DomainInformation
from registrar.models.domain import Domain
from registrar.models.user_domain_role import UserDomainRole
from registrar.models.public_contact import PublicContact
from registrar.models.user import User
from datetime import date, datetime, timedelta
from django.utils import timezone
from registrar.tests.common import MockEppLib, completed_application
class MockDb(MockEppLib):
def setUp(self):
super().setUp()
username = "test_user"
first_name = "First"
last_name = "Last"
email = "info@example.com"
self.user = get_user_model().objects.create(
username=username, first_name=first_name, last_name=last_name, email=email
)
self.domain_1, _ = Domain.objects.get_or_create(
name="cdomain1.gov", state=Domain.State.READY, first_ready=timezone.now()
)
self.domain_2, _ = Domain.objects.get_or_create(name="adomain2.gov", state=Domain.State.DNS_NEEDED)
self.domain_3, _ = Domain.objects.get_or_create(name="ddomain3.gov", state=Domain.State.ON_HOLD)
self.domain_4, _ = Domain.objects.get_or_create(name="bdomain4.gov", state=Domain.State.UNKNOWN)
self.domain_4, _ = Domain.objects.get_or_create(name="bdomain4.gov", state=Domain.State.UNKNOWN)
self.domain_5, _ = Domain.objects.get_or_create(
name="bdomain5.gov", state=Domain.State.DELETED, deleted=timezone.make_aware(datetime(2023, 11, 1))
)
self.domain_6, _ = Domain.objects.get_or_create(
name="bdomain6.gov", state=Domain.State.DELETED, deleted=timezone.make_aware(datetime(1980, 10, 16))
)
self.domain_7, _ = Domain.objects.get_or_create(
name="xdomain7.gov", state=Domain.State.DELETED, deleted=timezone.now()
)
self.domain_8, _ = Domain.objects.get_or_create(
name="sdomain8.gov", state=Domain.State.DELETED, deleted=timezone.now()
)
# We use timezone.make_aware to sync to server time a datetime object with the current date (using date.today())
# and a specific time (using datetime.min.time()).
# Deleted yesterday
self.domain_9, _ = Domain.objects.get_or_create(
name="zdomain9.gov",
state=Domain.State.DELETED,
deleted=timezone.make_aware(datetime.combine(date.today() - timedelta(days=1), datetime.min.time())),
)
# ready tomorrow
self.domain_10, _ = Domain.objects.get_or_create(
name="adomain10.gov",
state=Domain.State.READY,
first_ready=timezone.make_aware(datetime.combine(date.today() + timedelta(days=1), datetime.min.time())),
)
self.domain_information_1, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_1,
organization_type="federal",
federal_agency="World War I Centennial Commission",
federal_type="executive",
is_election_board=True
)
self.domain_information_2, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_2,
organization_type="interstate",
is_election_board=True
)
self.domain_information_3, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_3,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=True
)
self.domain_information_4, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_4,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=True
)
self.domain_information_5, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_5,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_6, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_6,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_7, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_7,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_8, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_8,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_9, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_9,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
self.domain_information_10, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_10,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
is_election_board=False
)
meoward_user = get_user_model().objects.create(
username="meoward_username", first_name="first_meoward", last_name="last_meoward", email="meoward@rocks.com"
)
lebowski_user = get_user_model().objects.create(
username="big_lebowski", first_name="big", last_name="lebowski", email="big_lebowski@dude.co"
)
# Test for more than 1 domain manager
_, created = UserDomainRole.objects.get_or_create(
user=meoward_user, domain=self.domain_1, role=UserDomainRole.Roles.MANAGER
)
_, created = UserDomainRole.objects.get_or_create(
user=self.user, domain=self.domain_1, role=UserDomainRole.Roles.MANAGER
)
_, created = UserDomainRole.objects.get_or_create(
user=lebowski_user, domain=self.domain_1, role=UserDomainRole.Roles.MANAGER
)
# Test for just 1 domain manager
_, created = UserDomainRole.objects.get_or_create(
user=meoward_user, domain=self.domain_2, role=UserDomainRole.Roles.MANAGER
)
with less_console_noise():
self.domain_request_1 = completed_application(status=DomainApplication.ApplicationStatus.STARTED, name="city1.gov")
self.domain_request_2 = completed_application(status=DomainApplication.ApplicationStatus.IN_REVIEW, name="city2.gov")
self.domain_request_3 = completed_application(status=DomainApplication.ApplicationStatus.STARTED, name="city3.gov")
self.domain_request_4 = completed_application(status=DomainApplication.ApplicationStatus.STARTED, name="city4.gov")
self.domain_request_5 = completed_application(status=DomainApplication.ApplicationStatus.APPROVED, name="city5.gov")
self.domain_request_3.submit()
self.domain_request_3.save()
self.domain_request_4.submit()
self.domain_request_4.save()
def tearDown(self):
PublicContact.objects.all().delete()
Domain.objects.all().delete()
DomainInformation.objects.all().delete()
DomainApplication.objects.all().delete()
User.objects.all().delete()
UserDomainRole.objects.all().delete()
super().tearDown()

View file

@ -5,14 +5,9 @@ from io import StringIO
from registrar.models.domain_application import DomainApplication from registrar.models.domain_application import DomainApplication
from registrar.models.domain_information import DomainInformation from registrar.models.domain_information import DomainInformation
from registrar.models.domain import Domain from registrar.models.domain import Domain
from registrar.models.public_contact import PublicContact
from registrar.models.user import User from registrar.models.user import User
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from registrar.models.user_domain_role import UserDomainRole
from registrar.tests.data.mocks import MockDb
from registrar.utility.csv_export import ( from registrar.utility.csv_export import (
format_end_date,
format_start_date,
get_sliced_domains, get_sliced_domains,
get_sliced_requests, get_sliced_requests,
write_domains_csv, write_domains_csv,
@ -30,60 +25,17 @@ import boto3_mocking
from registrar.utility.s3_bucket import S3ClientError, S3ClientErrorCodes # type: ignore from registrar.utility.s3_bucket import S3ClientError, S3ClientErrorCodes # type: ignore
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
from django.utils import timezone from django.utils import timezone
from .common import completed_application, less_console_noise from .common import MockDb, MockEppLib, less_console_noise
class CsvReportsTest(TestCase): class CsvReportsTest(MockDb):
"""Tests to determine if we are uploading our reports correctly""" """Tests to determine if we are uploading our reports correctly"""
def setUp(self): def setUp(self):
"""Create fake domain data""" """Create fake domain data"""
super().setUp()
self.client = Client(HTTP_HOST="localhost:8080") self.client = Client(HTTP_HOST="localhost:8080")
self.factory = RequestFactory() self.factory = RequestFactory()
username = "test_user"
first_name = "First"
last_name = "Last"
email = "info@example.com"
self.user = get_user_model().objects.create(
username=username, first_name=first_name, last_name=last_name, email=email
)
self.domain_1, _ = Domain.objects.get_or_create(name="cdomain1.gov", state=Domain.State.READY)
self.domain_2, _ = Domain.objects.get_or_create(name="adomain2.gov", state=Domain.State.DNS_NEEDED)
self.domain_3, _ = Domain.objects.get_or_create(name="ddomain3.gov", state=Domain.State.ON_HOLD)
self.domain_4, _ = Domain.objects.get_or_create(name="bdomain4.gov", state=Domain.State.UNKNOWN)
self.domain_information_1, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_1,
organization_type="federal",
federal_agency="World War I Centennial Commission",
federal_type="executive",
)
self.domain_information_2, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_2,
organization_type="interstate",
)
self.domain_information_3, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_3,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
)
self.domain_information_4, _ = DomainInformation.objects.get_or_create(
creator=self.user,
domain=self.domain_4,
organization_type="federal",
federal_agency="Armed Forces Retirement Home",
)
def tearDown(self):
"""Delete all faked data"""
Domain.objects.all().delete()
DomainInformation.objects.all().delete()
User.objects.all().delete()
super().tearDown()
@boto3_mocking.patching @boto3_mocking.patching
def test_generate_federal_report(self): def test_generate_federal_report(self):
@ -94,6 +46,7 @@ class CsvReportsTest(TestCase):
expected_file_content = [ expected_file_content = [
call("Domain name,Domain type,Agency,Organization name,City,State,Security contact email\r\n"), call("Domain name,Domain type,Agency,Organization name,City,State,Security contact email\r\n"),
call("cdomain1.gov,Federal - Executive,World War I Centennial Commission,,,, \r\n"), call("cdomain1.gov,Federal - Executive,World War I Centennial Commission,,,, \r\n"),
call('adomain10.gov,Federal,Armed Forces Retirement Home,,,, \r\n'),
call("ddomain3.gov,Federal,Armed Forces Retirement Home,,,, \r\n"), call("ddomain3.gov,Federal,Armed Forces Retirement Home,,,, \r\n"),
] ]
# We don't actually want to write anything for a test case, # We don't actually want to write anything for a test case,
@ -114,6 +67,7 @@ class CsvReportsTest(TestCase):
expected_file_content = [ expected_file_content = [
call("Domain name,Domain type,Agency,Organization name,City,State,Security contact email\r\n"), call("Domain name,Domain type,Agency,Organization name,City,State,Security contact email\r\n"),
call("cdomain1.gov,Federal - Executive,World War I Centennial Commission,,,, \r\n"), call("cdomain1.gov,Federal - Executive,World War I Centennial Commission,,,, \r\n"),
call('adomain10.gov,Federal,Armed Forces Retirement Home,,,, \r\n'),
call("ddomain3.gov,Federal,Armed Forces Retirement Home,,,, \r\n"), call("ddomain3.gov,Federal,Armed Forces Retirement Home,,,, \r\n"),
call("adomain2.gov,Interstate,,,,, \r\n"), call("adomain2.gov,Interstate,,,,, \r\n"),
] ]
@ -172,6 +126,7 @@ class CsvReportsTest(TestCase):
@boto3_mocking.patching @boto3_mocking.patching
def test_load_federal_report(self): def test_load_federal_report(self):
"""Tests the get_current_federal api endpoint""" """Tests the get_current_federal api endpoint"""
with less_console_noise(): with less_console_noise():
mock_client = MagicMock() mock_client = MagicMock()
mock_client_instance = mock_client.return_value mock_client_instance = mock_client.return_value
@ -205,6 +160,7 @@ class CsvReportsTest(TestCase):
@boto3_mocking.patching @boto3_mocking.patching
def test_load_full_report(self): def test_load_full_report(self):
"""Tests the current-federal api link""" """Tests the current-federal api link"""
with less_console_noise(): with less_console_noise():
mock_client = MagicMock() mock_client = MagicMock()
mock_client_instance = mock_client.return_value mock_client_instance = mock_client.return_value
@ -237,7 +193,7 @@ class CsvReportsTest(TestCase):
self.assertEqual(expected_file_content, response.content) self.assertEqual(expected_file_content, response.content)
class ExportDataTest(MockDb): class ExportDataTest(MockDb, MockEppLib):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
@ -247,6 +203,7 @@ class ExportDataTest(MockDb):
def test_export_domains_to_writer_security_emails(self): def test_export_domains_to_writer_security_emails(self):
"""Test that export_domains_to_writer returns the """Test that export_domains_to_writer returns the
expected security email""" expected security email"""
with less_console_noise(): with less_console_noise():
# Add security email information # Add security email information
self.domain_1.name = "defaultsecurity.gov" self.domain_1.name = "defaultsecurity.gov"
@ -312,6 +269,7 @@ class ExportDataTest(MockDb):
"""Test that write_body returns the """Test that write_body returns the
existing domain, test that sort by domain name works, existing domain, test that sort by domain name works,
test that filter works""" test that filter works"""
with less_console_noise(): with less_console_noise():
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
@ -369,6 +327,7 @@ class ExportDataTest(MockDb):
def test_write_domains_body_additional(self): def test_write_domains_body_additional(self):
"""An additional test for filters and multi-column sort""" """An additional test for filters and multi-column sort"""
with less_console_noise(): with less_console_noise():
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
@ -428,15 +387,11 @@ class ExportDataTest(MockDb):
which are hard to mock. which are hard to mock.
TODO: Simplify if created_at is not needed for the report.""" TODO: Simplify if created_at is not needed for the report."""
with less_console_noise(): with less_console_noise():
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
writer = csv.writer(csv_file) writer = csv.writer(csv_file)
# We use timezone.make_aware to sync to server time a datetime object with the current date
# (using date.today()) and a specific time (using datetime.min.time()).
end_date = timezone.make_aware(datetime.combine(date.today() + timedelta(days=2), datetime.min.time()))
start_date = timezone.make_aware(datetime.combine(date.today() - timedelta(days=2), datetime.min.time()))
# Define columns, sort fields, and filter condition # Define columns, sort fields, and filter condition
columns = [ columns = [
"Domain name", "Domain name",
@ -460,15 +415,15 @@ class ExportDataTest(MockDb):
"domain__state__in": [ "domain__state__in": [
Domain.State.READY, Domain.State.READY,
], ],
"domain__first_ready__lte": end_date, "domain__first_ready__lte": self.end_date,
"domain__first_ready__gte": start_date, "domain__first_ready__gte": self.start_date,
} }
filter_conditions_for_deleted_domains = { filter_conditions_for_deleted_domains = {
"domain__state__in": [ "domain__state__in": [
Domain.State.DELETED, Domain.State.DELETED,
], ],
"domain__deleted__lte": end_date, "domain__deleted__lte": self.end_date,
"domain__deleted__gte": start_date, "domain__deleted__gte": self.start_date,
} }
# Call the export functions # Call the export functions
@ -515,13 +470,13 @@ class ExportDataTest(MockDb):
def test_export_domains_to_writer_domain_managers(self): def test_export_domains_to_writer_domain_managers(self):
"""Test that export_domains_to_writer returns the """Test that export_domains_to_writer returns the
expected domain managers""" expected domain managers."""
with less_console_noise(): with less_console_noise():
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
writer = csv.writer(csv_file) writer = csv.writer(csv_file)
# Define columns, sort fields, and filter condition # Define columns, sort fields, and filter condition
columns = [ columns = [
"Domain name", "Domain name",
"Status", "Status",
@ -572,13 +527,13 @@ class ExportDataTest(MockDb):
self.assertEqual(csv_content, expected_content) self.assertEqual(csv_content, expected_content)
def test_export_data_managed_domains_to_csv(self): def test_export_data_managed_domains_to_csv(self):
"""""" """Test get counts for domains that have domain managers for two different dates,
get list of managed domains at end_date."""
with less_console_noise(): with less_console_noise():
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
writer = csv.writer(csv_file) writer = csv.writer(csv_file)
end_date = timezone.make_aware(datetime.combine(date.today() + timedelta(days=2), datetime.min.time()))
start_date = timezone.make_aware(datetime.combine(date.today() - timedelta(days=2), datetime.min.time()))
# Define columns, sort fields, and filter condition # Define columns, sort fields, and filter condition
columns = [ columns = [
"Domain name", "Domain name",
@ -589,7 +544,7 @@ class ExportDataTest(MockDb):
] ]
filter_managed_domains_start_date = { filter_managed_domains_start_date = {
"domain__permissions__isnull": False, "domain__permissions__isnull": False,
"domain__first_ready__lte": start_date, "domain__first_ready__lte": self.start_date,
} }
managed_domains_sliced_at_start_date = get_sliced_domains(filter_managed_domains_start_date) managed_domains_sliced_at_start_date = get_sliced_domains(filter_managed_domains_start_date)
# Call the export functions # Call the export functions
@ -610,13 +565,11 @@ class ExportDataTest(MockDb):
) )
writer.writerow(managed_domains_sliced_at_start_date) writer.writerow(managed_domains_sliced_at_start_date)
writer.writerow([]) writer.writerow([])
filter_managed_domains_end_date = { filter_managed_domains_end_date = {
"domain__permissions__isnull": False, "domain__permissions__isnull": False,
"domain__first_ready__lte": end_date, "domain__first_ready__lte": self.end_date,
} }
managed_domains_sliced_at_end_date = get_sliced_domains(filter_managed_domains_end_date) managed_domains_sliced_at_end_date = get_sliced_domains(filter_managed_domains_end_date)
writer.writerow(["MANAGED DOMAINS COUNTS AT END DATE"]) writer.writerow(["MANAGED DOMAINS COUNTS AT END DATE"])
writer.writerow( writer.writerow(
[ [
@ -634,7 +587,6 @@ class ExportDataTest(MockDb):
) )
writer.writerow(managed_domains_sliced_at_end_date) writer.writerow(managed_domains_sliced_at_end_date)
writer.writerow([]) writer.writerow([])
write_domains_csv( write_domains_csv(
writer, writer,
columns, columns,
@ -647,9 +599,7 @@ class ExportDataTest(MockDb):
csv_file.seek(0) csv_file.seek(0)
# Read the content into a variable # Read the content into a variable
csv_content = csv_file.read() csv_content = csv_file.read()
self.maxDiff=None self.maxDiff=None
# We expect the READY domain names with the domain managers: Their counts, and listing at end_date. # We expect the READY domain names with the domain managers: Their counts, and listing at end_date.
expected_content = ( expected_content = (
"MANAGED DOMAINS COUNTS AT START DATE\n" "MANAGED DOMAINS COUNTS AT START DATE\n"
@ -663,20 +613,22 @@ class ExportDataTest(MockDb):
"Domain name,Domain type,Domain manager email 1,Domain manager email 2,Domain manager email 3\n" "Domain name,Domain type,Domain manager email 1,Domain manager email 2,Domain manager email 3\n"
"cdomain1.gov,Federal - Executive,meoward@rocks.com,info@example.com,big_lebowski@dude.co\n" "cdomain1.gov,Federal - Executive,meoward@rocks.com,info@example.com,big_lebowski@dude.co\n"
) )
# Normalize line endings and remove commas, # Normalize line endings and remove commas,
# 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.assertEqual(csv_content, expected_content) self.assertEqual(csv_content, expected_content)
def test_export_data_unmanaged_domains_to_csv(self): def test_export_data_unmanaged_domains_to_csv(self):
"""""" """Test get counts for domains that do not have domain managers for two different dates,
get list of unmanaged domains at end_date."""
with less_console_noise(): with less_console_noise():
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
writer = csv.writer(csv_file) writer = csv.writer(csv_file)
end_date = timezone.make_aware(datetime.combine(date.today() + timedelta(days=2), datetime.min.time()))
start_date = timezone.make_aware(datetime.combine(date.today() - timedelta(days=2), datetime.min.time()))
# Define columns, sort fields, and filter condition # Define columns, sort fields, and filter condition
columns = [ columns = [
"Domain name", "Domain name",
@ -687,7 +639,7 @@ class ExportDataTest(MockDb):
] ]
filter_unmanaged_domains_start_date = { filter_unmanaged_domains_start_date = {
"domain__permissions__isnull": True, "domain__permissions__isnull": True,
"domain__first_ready__lte": start_date, "domain__first_ready__lte": self.start_date,
} }
unmanaged_domains_sliced_at_start_date = get_sliced_domains(filter_unmanaged_domains_start_date) unmanaged_domains_sliced_at_start_date = get_sliced_domains(filter_unmanaged_domains_start_date)
# Call the export functions # Call the export functions
@ -708,13 +660,11 @@ class ExportDataTest(MockDb):
) )
writer.writerow(unmanaged_domains_sliced_at_start_date) writer.writerow(unmanaged_domains_sliced_at_start_date)
writer.writerow([]) writer.writerow([])
filter_unmanaged_domains_end_date = { filter_unmanaged_domains_end_date = {
"domain__permissions__isnull": True, "domain__permissions__isnull": True,
"domain__first_ready__lte": end_date, "domain__first_ready__lte": self.end_date,
} }
unmanaged_domains_sliced_at_end_date = get_sliced_domains(filter_unmanaged_domains_end_date) unmanaged_domains_sliced_at_end_date = get_sliced_domains(filter_unmanaged_domains_end_date)
writer.writerow(["UNMANAGED DOMAINS COUNTS AT END DATE"]) writer.writerow(["UNMANAGED DOMAINS COUNTS AT END DATE"])
writer.writerow( writer.writerow(
[ [
@ -732,7 +682,6 @@ class ExportDataTest(MockDb):
) )
writer.writerow(unmanaged_domains_sliced_at_end_date) writer.writerow(unmanaged_domains_sliced_at_end_date)
writer.writerow([]) writer.writerow([])
write_domains_csv( write_domains_csv(
writer, writer,
columns, columns,
@ -745,9 +694,7 @@ class ExportDataTest(MockDb):
csv_file.seek(0) csv_file.seek(0)
# Read the content into a variable # Read the content into a variable
csv_content = csv_file.read() csv_content = csv_file.read()
self.maxDiff=None self.maxDiff=None
# We expect the READY domain names with the domain managers: Their counts, and listing at end_date. # We expect the READY domain names with the domain managers: Their counts, and listing at end_date.
expected_content = ( expected_content = (
"UNMANAGED DOMAINS COUNTS AT START DATE\n" "UNMANAGED DOMAINS COUNTS AT START DATE\n"
@ -761,10 +708,12 @@ class ExportDataTest(MockDb):
"Domain name,Domain type\n" "Domain name,Domain type\n"
"adomain10.gov,Federal\n" "adomain10.gov,Federal\n"
) )
# Normalize line endings and remove commas, # Normalize line endings and remove commas,
# 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.assertEqual(csv_content, expected_content) self.assertEqual(csv_content, expected_content)
def test_write_requests_body_with_date_filter_pulls_requests_in_range(self): def test_write_requests_body_with_date_filter_pulls_requests_in_range(self):
@ -778,17 +727,6 @@ class ExportDataTest(MockDb):
# Create a CSV file in memory # Create a CSV file in memory
csv_file = StringIO() csv_file = StringIO()
writer = csv.writer(csv_file) writer = csv.writer(csv_file)
# We use timezone.make_aware to sync to server time a datetime object with the current date
# (using date.today()) and a specific time (using datetime.min.time()).
# Create a time-aware current date
current_datetime = timezone.now()
# Extract the date part
current_date = current_datetime.date()
# Create start and end dates using timedelta
end_date = current_date + timedelta(days=2)
start_date = current_date - timedelta(days=2)
# Define columns, sort fields, and filter condition # Define columns, sort fields, and filter condition
columns = [ columns = [
"Requested domain", "Requested domain",
@ -800,16 +738,14 @@ class ExportDataTest(MockDb):
] ]
filter_condition = { filter_condition = {
"status": DomainApplication.ApplicationStatus.SUBMITTED, "status": DomainApplication.ApplicationStatus.SUBMITTED,
"submission_date__lte": end_date, "submission_date__lte": self.end_date,
"submission_date__gte": start_date, "submission_date__gte": self.start_date,
} }
write_requests_csv(writer, columns, sort_fields, filter_condition, should_write_header=True) write_requests_csv(writer, columns, sort_fields, filter_condition, should_write_header=True)
# Reset the CSV file's position to the beginning # Reset the CSV file's position to the beginning
csv_file.seek(0) csv_file.seek(0)
# Read the content into a variable # Read the content into a variable
csv_content = csv_file.read() csv_content = csv_file.read()
# We expect READY domains first, created between today-2 and today+2, sorted by created_at then name # We expect READY domains first, created between today-2 and today+2, sorted by created_at then name
# and DELETED domains deleted between today-2 and today+2, sorted by deleted then name # and DELETED domains deleted between today-2 and today+2, sorted by deleted then name
expected_content = ( expected_content = (
@ -817,12 +753,12 @@ class ExportDataTest(MockDb):
"city3.gov,Federal - Executive,2024-03-05\n" "city3.gov,Federal - Executive,2024-03-05\n"
"city4.gov,Federal - Executive,2024-03-05\n" "city4.gov,Federal - Executive,2024-03-05\n"
) )
# Normalize line endings and remove commas, # Normalize line endings and remove commas,
# 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.assertEqual(csv_content, expected_content) self.assertEqual(csv_content, expected_content)
class HelperFunctions(MockDb): class HelperFunctions(MockDb):
@ -841,50 +777,28 @@ class HelperFunctions(MockDb):
def test_get_sliced_domains(self): def test_get_sliced_domains(self):
"""Should get fitered domains counts sliced by org type and election office.""" """Should get fitered domains counts sliced by org type and election office."""
with less_console_noise(): with less_console_noise():
# Create a time-aware current date
current_datetime = timezone.now()
# Extract the date part
current_date = current_datetime.date()
# Create start and end dates using timedelta
end_date = current_date + timedelta(days=2)
start_date = current_date - timedelta(days=2)
filter_condition = { filter_condition = {
"domain__permissions__isnull": False, "domain__permissions__isnull": False,
"domain__first_ready__lte": end_date, "domain__first_ready__lte": self.end_date,
} }
managed_domains_sliced_at_end_date = get_sliced_domains(filter_condition) managed_domains_sliced_at_end_date = get_sliced_domains(filter_condition)
expected_content = ( expected_content = (
[1, 1, 0, 0, 0, 0, 0, 0, 0, 1] [1, 1, 0, 0, 0, 0, 0, 0, 0, 1]
) )
self.assertEqual(managed_domains_sliced_at_end_date, expected_content) self.assertEqual(managed_domains_sliced_at_end_date, expected_content)
def test_get_sliced_requests(self): def test_get_sliced_requests(self):
"""Should get fitered requests counts sliced by org type and election office.""" """Should get fitered requests counts sliced by org type and election office."""
with less_console_noise(): with less_console_noise():
# Create a time-aware current date
current_datetime = timezone.now()
# Extract the date part
current_date = current_datetime.date()
# Create start and end dates using timedelta
end_date = current_date + timedelta(days=2)
start_date = current_date - timedelta(days=2)
filter_condition = { filter_condition = {
"status": DomainApplication.ApplicationStatus.SUBMITTED, "status": DomainApplication.ApplicationStatus.SUBMITTED,
"submission_date__lte": end_date, "submission_date__lte": self.end_date,
} }
submitted_requests_sliced_at_end_date = get_sliced_requests(filter_condition) submitted_requests_sliced_at_end_date = get_sliced_requests(filter_condition)
print(f'managed_domains_sliced_at_end_date {submitted_requests_sliced_at_end_date}')
expected_content = ( expected_content = (
[2, 2, 0, 0, 0, 0, 0, 0, 0, 0] [2, 2, 0, 0, 0, 0, 0, 0, 0, 0]
) )
self.assertEqual(submitted_requests_sliced_at_end_date, expected_content) self.assertEqual(submitted_requests_sliced_at_end_date, expected_content)

View file

@ -498,7 +498,7 @@ def get_sliced_requests(filter_condition):
def export_data_managed_domains_to_csv(csv_file, start_date, end_date): def export_data_managed_domains_to_csv(csv_file, start_date, end_date):
"""Get counts for domains that have domain managers for two different dates, """Get counts for domains that have domain managers for two different dates,
get list of domains at end_date.""" get list of managed domains at end_date."""
start_date_formatted = format_start_date(start_date) start_date_formatted = format_start_date(start_date)
end_date_formatted = format_end_date(end_date) end_date_formatted = format_end_date(end_date)
@ -570,7 +570,7 @@ def export_data_managed_domains_to_csv(csv_file, start_date, end_date):
def export_data_unmanaged_domains_to_csv(csv_file, start_date, end_date): def export_data_unmanaged_domains_to_csv(csv_file, start_date, end_date):
"""Get counts for domains that do not have domain managers for two different dates, """Get counts for domains that do not have domain managers for two different dates,
get list of domains at end_date.""" get list of unmanaged domains at end_date."""
start_date_formatted = format_start_date(start_date) start_date_formatted = format_start_date(start_date)
end_date_formatted = format_end_date(end_date) end_date_formatted = format_end_date(end_date)