Black formatting

This commit is contained in:
zandercymatics 2023-08-17 11:41:07 -06:00
parent 080a70e613
commit 40b5d7ec5c
No known key found for this signature in database
GPG key ID: FF4636ABEC9682B7
4 changed files with 82 additions and 113 deletions

View file

@ -5,6 +5,7 @@ from django.contrib.contenttypes.models import ContentType
from django.http.response import HttpResponseRedirect from django.http.response import HttpResponseRedirect
from django.urls import reverse from django.urls import reverse
from registrar.models.utility.admin_form_order_helper import AdminFormOrderHelper from registrar.models.utility.admin_form_order_helper import AdminFormOrderHelper
# Split up for the linter # Split up for the linter
from registrar.models.utility.admin_form_order_helper import SortingDict from registrar.models.utility.admin_form_order_helper import SortingDict
from . import models from . import models
@ -17,13 +18,10 @@ foreignkey_orderby_dict: list[SortingDict] = [
# Handles fields that are sorted by 'first_name / last_name # Handles fields that are sorted by 'first_name / last_name
SortingDict( SortingDict(
["submitter", "authorizing_official", "investigator", "creator", "user"], ["submitter", "authorizing_official", "investigator", "creator", "user"],
['first_name', 'last_name'] ["first_name", "last_name"],
), ),
# Handles fields that are sorted by 'name' # Handles fields that are sorted by 'name'
SortingDict( SortingDict(["domain", "requested_domain"], ["name"]),
["domain", "requested_domain"],
["name"]
)
] ]
@ -184,6 +182,7 @@ class DomainAdmin(ListHeaderAdmin):
class ContactAdmin(ListHeaderAdmin): class ContactAdmin(ListHeaderAdmin):
"""Custom contact admin class to add search.""" """Custom contact admin class to add search."""
search_fields = ["email", "first_name", "last_name"] search_fields = ["email", "first_name", "last_name"]
search_help_text = "Search by firstname, lastname or email." search_help_text = "Search by firstname, lastname or email."

View file

@ -7,6 +7,7 @@ logger = logging.getLogger(__name__)
class SortingDict: class SortingDict:
"""Stores a sorting dictionary object""" """Stores a sorting dictionary object"""
_sorting_dict: Dict[type, type] = {} _sorting_dict: Dict[type, type] = {}
# model_list can be will be called multiple times. # model_list can be will be called multiple times.
@ -24,7 +25,7 @@ class SortingDict:
def __init__(self, model_list, sort_list): def __init__(self, model_list, sort_list):
self._sorting_dict = { self._sorting_dict = {
"dropDownSelected": self.convert_list_to_dict(model_list), "dropDownSelected": self.convert_list_to_dict(model_list),
"sortBy": sort_list "sortBy": sort_list,
} }
def get_dict(self): def get_dict(self):
@ -36,7 +37,7 @@ class SortingDict:
return self._sorting_dict return self._sorting_dict
class AdminFormOrderHelper(): class AdminFormOrderHelper:
"""A helper class to order a dropdown field in Django Admin, """A helper class to order a dropdown field in Django Admin,
takes the fields you want to order by as an array""" takes the fields you want to order by as an array"""
@ -46,7 +47,7 @@ class AdminFormOrderHelper():
def __init__(self, sort: list[SortingDict]): def __init__(self, sort: list[SortingDict]):
self._sorting_list = sort self._sorting_list = sort
def get_ordered_form_field(self, form_field, db_field) -> (ModelChoiceField | None): def get_ordered_form_field(self, form_field, db_field) -> ModelChoiceField | None:
"""Orders the queryset for a ModelChoiceField """Orders the queryset for a ModelChoiceField
based on the order_by_dict dictionary""" based on the order_by_dict dictionary"""
_order_by_list = [] _order_by_list = []

View file

@ -11,6 +11,7 @@ from django.conf import settings
from django.contrib.auth import get_user_model, login from django.contrib.auth import get_user_model, login
from registrar.models import Contact, DraftDomain, Website, DomainApplication from registrar.models import Contact, DraftDomain, Website, DomainApplication
# For the linter # For the linter
from registrar.models import DomainInvitation, User, DomainInformation, Domain from registrar.models import DomainInvitation, User, DomainInformation, Domain
@ -118,7 +119,7 @@ class AuditedAdminMockData:
user = User.objects.get_or_create( user = User.objects.get_or_create(
first_name="{} First:{}".format(item_name, shorthand), first_name="{} First:{}".format(item_name, shorthand),
last_name="{} Last:{}".format(item_name, shorthand), last_name="{} Last:{}".format(item_name, shorthand),
username="{} username:{}".format(item_name, shorthand) username="{} username:{}".format(item_name, shorthand),
)[0] )[0]
return user return user
@ -129,7 +130,7 @@ class AuditedAdminMockData:
last_name="{} Last:{}".format(item_name, shorthand), last_name="{} Last:{}".format(item_name, shorthand),
title="{} title:{}".format(item_name, shorthand), title="{} title:{}".format(item_name, shorthand),
email="{}testy@town.com".format(item_name), email="{}testy@town.com".format(item_name),
phone="(555) 555 5555" phone="(555) 555 5555",
)[0] )[0]
return contact return contact
@ -143,9 +144,9 @@ class AuditedAdminMockData:
def dummy_alt(self, item_name): def dummy_alt(self, item_name):
"""Creates a dummy website object for alternates""" """Creates a dummy website object for alternates"""
return Website.objects.get_or_create( return Website.objects.get_or_create(website="cityalt{}.gov".format(item_name))[
website="cityalt{}.gov".format(item_name) 0
)[0] ]
def dummy_current(self, item_name): def dummy_current(self, item_name):
"""Creates a dummy website object for current""" """Creates a dummy website object for current"""
@ -156,7 +157,7 @@ class AuditedAdminMockData:
item_name, item_name,
org_type="federal", org_type="federal",
federal_type="executive", federal_type="executive",
purpose="Purpose of the site" purpose="Purpose of the site",
): ):
"""Generates a generic argument list for most domains""" """Generates a generic argument list for most domains"""
common_args = dict( common_args = dict(
@ -169,11 +170,11 @@ class AuditedAdminMockData:
is_policy_acknowledged=True, is_policy_acknowledged=True,
state_territory="NY", state_territory="NY",
zipcode="10002", zipcode="10002",
type_of_work='e-Government', type_of_work="e-Government",
anything_else="There is more", anything_else="There is more",
authorizing_official=self.dummy_contact(item_name, 'authorizing_official'), authorizing_official=self.dummy_contact(item_name, "authorizing_official"),
submitter=self.dummy_contact(item_name, 'submitter'), submitter=self.dummy_contact(item_name, "submitter"),
creator=self.dummy_user(item_name, 'creator'), creator=self.dummy_user(item_name, "creator"),
) )
return common_args return common_args
@ -185,14 +186,11 @@ class AuditedAdminMockData:
status, status,
org_type="federal", org_type="federal",
federal_type="executive", federal_type="executive",
purpose="Purpose of the site" purpose="Purpose of the site",
): ):
"""Returns kwargs for different domain object types""" """Returns kwargs for different domain object types"""
common_args = self.get_common_domain_arg_dictionary( common_args = self.get_common_domain_arg_dictionary(
item_name, item_name, org_type, federal_type, purpose
org_type,
federal_type,
purpose
) )
full_arg_list = None full_arg_list = None
match domain_type: match domain_type:
@ -200,7 +198,7 @@ class AuditedAdminMockData:
full_arg_list = dict( full_arg_list = dict(
**common_args, **common_args,
requested_domain=self.dummy_draft_domain(item_name), requested_domain=self.dummy_draft_domain(item_name),
investigator=self.dummy_user(item_name, 'investigator'), investigator=self.dummy_user(item_name, "investigator"),
status=status, status=status,
) )
case self.INFORMATION: case self.INFORMATION:
@ -208,26 +206,22 @@ class AuditedAdminMockData:
full_arg_list = dict( full_arg_list = dict(
**common_args, **common_args,
domain=self.dummy_domain(item_name), domain=self.dummy_domain(item_name),
domain_application=domain_app domain_application=domain_app,
) )
case self.INVITATION: case self.INVITATION:
full_arg_list = dict( full_arg_list = dict(
email="test_mail@mail.com", email="test_mail@mail.com",
domain=self.dummy_domain(item_name), domain=self.dummy_domain(item_name),
status=DomainInvitation.INVITED status=DomainInvitation.INVITED,
) )
return full_arg_list return full_arg_list
def create_full_dummy_domain_application( def create_full_dummy_domain_application(
self, self, object_name, status=DomainApplication.STARTED
object_name,
status=DomainApplication.STARTED
): ):
"""Creates a dummy domain application object""" """Creates a dummy domain application object"""
domain_application_kwargs = self.dummy_kwarg_boilerplate( domain_application_kwargs = self.dummy_kwarg_boilerplate(
self.APPLICATION, self.APPLICATION, object_name, status
object_name,
status
) )
application = DomainApplication.objects.get_or_create( application = DomainApplication.objects.get_or_create(
**domain_application_kwargs **domain_application_kwargs
@ -235,15 +229,11 @@ class AuditedAdminMockData:
return application return application
def create_full_dummy_domain_information( def create_full_dummy_domain_information(
self, self, object_name, status=DomainApplication.STARTED
object_name,
status=DomainApplication.STARTED
): ):
"""Creates a dummy domain information object""" """Creates a dummy domain information object"""
domain_application_kwargs = self.dummy_kwarg_boilerplate( domain_application_kwargs = self.dummy_kwarg_boilerplate(
self.INFORMATION, self.INFORMATION, object_name, status
object_name,
status
) )
application = DomainInformation.objects.get_or_create( application = DomainInformation.objects.get_or_create(
**domain_application_kwargs **domain_application_kwargs
@ -251,15 +241,11 @@ class AuditedAdminMockData:
return application return application
def create_full_dummy_domain_invitation( def create_full_dummy_domain_invitation(
self, self, object_name, status=DomainApplication.STARTED
object_name,
status=DomainApplication.STARTED
): ):
"""Creates a dummy domain invitation object""" """Creates a dummy domain invitation object"""
domain_application_kwargs = self.dummy_kwarg_boilerplate( domain_application_kwargs = self.dummy_kwarg_boilerplate(
self.INVITATION, self.INVITATION, object_name, status
object_name,
status
) )
application = DomainInvitation.objects.get_or_create( application = DomainInvitation.objects.get_or_create(
**domain_application_kwargs **domain_application_kwargs
@ -274,7 +260,7 @@ class AuditedAdminMockData:
has_other_contacts=True, has_other_contacts=True,
has_current_website=True, has_current_website=True,
has_alternative_gov_domain=True, has_alternative_gov_domain=True,
status=DomainApplication.STARTED status=DomainApplication.STARTED,
): ):
"""A helper to create a dummy domain application object""" """A helper to create a dummy domain application object"""
application = None application = None
@ -295,7 +281,7 @@ class AuditedAdminMockData:
raise ValueError("Invalid domain_type, must conform to given constants") raise ValueError("Invalid domain_type, must conform to given constants")
if has_other_contacts and domain_type != self.INVITATION: if has_other_contacts and domain_type != self.INVITATION:
other = self.dummy_contact(object_name, 'other') other = self.dummy_contact(object_name, "other")
application.other_contacts.add(other) application.other_contacts.add(other)
if has_current_website and domain_type == self.APPLICATION: if has_current_website and domain_type == self.APPLICATION:
current = self.dummy_current(object_name) current = self.dummy_current(object_name)
@ -410,7 +396,7 @@ def completed_application(
def multiple_unalphabetical_domain_objects( def multiple_unalphabetical_domain_objects(
domain_type=AuditedAdminMockData.APPLICATION domain_type=AuditedAdminMockData.APPLICATION,
): ):
"""Returns a list of generic domain objects for testing purposes""" """Returns a list of generic domain objects for testing purposes"""
applications = [] applications = []

View file

@ -1,12 +1,14 @@
from django.test import TestCase, RequestFactory, Client from django.test import TestCase, RequestFactory, Client
from django.contrib.admin.sites import AdminSite from django.contrib.admin.sites import AdminSite
from registrar.admin import DomainApplicationAdmin, ListHeaderAdmin from registrar.admin import DomainApplicationAdmin, ListHeaderAdmin
# Need to split these up due to the linter # Need to split these up due to the linter
from registrar.admin import MyUserAdmin, AuditedAdmin from registrar.admin import MyUserAdmin, AuditedAdmin
from registrar.models import DomainApplication, DomainInformation, User from registrar.models import DomainApplication, DomainInformation, User
from registrar.models.contact import Contact from registrar.models.contact import Contact
from registrar.models.domain_invitation import DomainInvitation from registrar.models.domain_invitation import DomainInvitation
from .common import completed_application, mock_user, create_superuser, create_user from .common import completed_application, mock_user, create_superuser, create_user
# Need to split these up due to the linter # Need to split these up due to the linter
from .common import multiple_unalphabetical_domain_objects from .common import multiple_unalphabetical_domain_objects
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
@ -385,11 +387,7 @@ class AuditedAdminTest(TestCase):
self.client = Client(HTTP_HOST="localhost:8080") self.client = Client(HTTP_HOST="localhost:8080")
def order_by_desired_field_helper( def order_by_desired_field_helper(
self, self, obj_to_sort: AuditedAdmin, request, field_name, *obj_names
obj_to_sort: AuditedAdmin,
request,
field_name,
*obj_names
): ):
formatted_sort_fields = [] formatted_sort_fields = []
for obj in obj_names: for obj in obj_names:
@ -397,9 +395,9 @@ class AuditedAdminTest(TestCase):
# Not really a fan of how this looks, but as the linter demands... # Not really a fan of how this looks, but as the linter demands...
ordered_list = list( ordered_list = list(
obj_to_sort.get_queryset(request).order_by( obj_to_sort.get_queryset(request)
*formatted_sort_fields).values_list( .order_by(*formatted_sort_fields)
*formatted_sort_fields) .values_list(*formatted_sort_fields)
) )
return ordered_list return ordered_list
@ -428,14 +426,9 @@ class AuditedAdminTest(TestCase):
# but both fields are of a fixed length. # but both fields are of a fixed length.
# For test case purposes, this should be performant. # For test case purposes, this should be performant.
for field in tested_fields: for field in tested_fields:
# We want both of these to be lists, as it is richer test wise. # We want both of these to be lists, as it is richer test wise.
desired_order = self.order_by_desired_field_helper( desired_order = self.order_by_desired_field_helper(
model_admin, model_admin, request, field.name, "first_name", "last_name"
request,
field.name,
"first_name",
"last_name"
) )
current_sort_order: Contact = list( current_sort_order: Contact = list(
model_admin.formfield_for_foreignkey(field, request).queryset model_admin.formfield_for_foreignkey(field, request).queryset
@ -451,14 +444,14 @@ class AuditedAdminTest(TestCase):
first = contact.first_name first = contact.first_name
last = contact.last_name last = contact.last_name
name_tuple = self.coerced_fk_field_helper(first, last, field.name, ':') name_tuple = self.coerced_fk_field_helper(first, last, field.name, ":")
if name_tuple: if name_tuple:
current_sort_order_coerced_type.append((first, last)) current_sort_order_coerced_type.append((first, last))
self.assertEqual( self.assertEqual(
desired_order, desired_order,
current_sort_order_coerced_type, current_sort_order_coerced_type,
"{} is not ordered alphabetically".format(field.name) "{} is not ordered alphabetically".format(field.name),
) )
def test_alphabetically_sorted_fk_fields_domain_information(self): def test_alphabetically_sorted_fk_fields_domain_information(self):
@ -466,7 +459,7 @@ class AuditedAdminTest(TestCase):
DomainInformation.authorizing_official.field, DomainInformation.authorizing_official.field,
DomainInformation.submitter.field, DomainInformation.submitter.field,
DomainInformation.domain.field, DomainInformation.domain.field,
DomainInformation.creator.field DomainInformation.creator.field,
] ]
# Creates multiple domain applications - review status does not matter # Creates multiple domain applications - review status does not matter
@ -484,18 +477,15 @@ class AuditedAdminTest(TestCase):
# but both fields are of a fixed length. # but both fields are of a fixed length.
# For test case purposes, this should be performant. # For test case purposes, this should be performant.
for field in tested_fields: for field in tested_fields:
isNamefield: bool = (field == DomainInformation.domain.field) isNamefield: bool = field == DomainInformation.domain.field
if (isNamefield): if isNamefield:
sorted_fields = ["name"] sorted_fields = ["name"]
else: else:
sorted_fields = ["first_name", "last_name"] sorted_fields = ["first_name", "last_name"]
# We want both of these to be lists, as it is richer test wise. # We want both of these to be lists, as it is richer test wise.
desired_order = self.order_by_desired_field_helper( desired_order = self.order_by_desired_field_helper(
model_admin, model_admin, request, field.name, *sorted_fields
request,
field.name,
*sorted_fields
) )
current_sort_order = list( current_sort_order = list(
model_admin.formfield_for_foreignkey(field, request).queryset model_admin.formfield_for_foreignkey(field, request).queryset
@ -515,14 +505,14 @@ class AuditedAdminTest(TestCase):
first = contact.name first = contact.name
last = None last = None
name_tuple = self.coerced_fk_field_helper(first, last, field.name, ':') name_tuple = self.coerced_fk_field_helper(first, last, field.name, ":")
if name_tuple is not None: if name_tuple is not None:
current_sort_order_coerced_type.append(name_tuple) current_sort_order_coerced_type.append(name_tuple)
self.assertEqual( self.assertEqual(
desired_order, desired_order,
current_sort_order_coerced_type, current_sort_order_coerced_type,
"{} is not ordered alphabetically".format(field.name) "{} is not ordered alphabetically".format(field.name),
) )
def test_alphabetically_sorted_fk_fields_domain_invitation(self): def test_alphabetically_sorted_fk_fields_domain_invitation(self):
@ -547,10 +537,7 @@ class AuditedAdminTest(TestCase):
# We want both of these to be lists, as it is richer test wise. # We want both of these to be lists, as it is richer test wise.
desired_order = self.order_by_desired_field_helper( desired_order = self.order_by_desired_field_helper(
model_admin, model_admin, request, field.name, *sorted_fields
request,
field.name,
*sorted_fields
) )
current_sort_order = list( current_sort_order = list(
model_admin.formfield_for_foreignkey(field, request).queryset model_admin.formfield_for_foreignkey(field, request).queryset
@ -566,33 +553,29 @@ class AuditedAdminTest(TestCase):
first = contact.name first = contact.name
last = None last = None
name_tuple = self.coerced_fk_field_helper(first, last, field.name, ':') name_tuple = self.coerced_fk_field_helper(first, last, field.name, ":")
if name_tuple is not None: if name_tuple is not None:
current_sort_order_coerced_type.append(name_tuple) current_sort_order_coerced_type.append(name_tuple)
self.assertEqual( self.assertEqual(
desired_order, desired_order,
current_sort_order_coerced_type, current_sort_order_coerced_type,
"{} is not ordered alphabetically".format(field.name) "{} is not ordered alphabetically".format(field.name),
) )
def coerced_fk_field_helper( def coerced_fk_field_helper(
self, self, first_name, last_name, field_name, queryset_shorthand
first_name,
last_name,
field_name,
queryset_shorthand
): ):
"""Handles edge cases for test cases""" """Handles edge cases for test cases"""
if first_name is None: if first_name is None:
raise ValueError('Invalid value for first_name, must be defined') raise ValueError("Invalid value for first_name, must be defined")
returned_tuple = (first_name, last_name) returned_tuple = (first_name, last_name)
# Handles edge case for names - structured strangely # Handles edge case for names - structured strangely
if last_name is None: if last_name is None:
return (first_name,) return (first_name,)
if (first_name.split(queryset_shorthand)[1] == field_name): if first_name.split(queryset_shorthand)[1] == field_name:
return returned_tuple return returned_tuple
else: else:
return None return None