cleanup and lint

This commit is contained in:
Rachid Mrad 2024-01-09 13:17:43 -05:00
parent f2b12e01d0
commit 3895a04879
No known key found for this signature in database
GPG key ID: EF38E4CEC4A8F3CF
3 changed files with 43 additions and 44 deletions

View file

@ -17,6 +17,7 @@ from registrar.utility import errors
logger = logging.getLogger(__name__)
class RegistrarForm(forms.Form):
"""
A common set of methods and configuration.
@ -94,14 +95,14 @@ class RegistrarFormSet(forms.BaseFormSet):
Hint: Subclass should call `self._to_database(...)`.
"""
raise NotImplementedError
def test_if_more_than_one_join(self, db_obj, rel, related_name):
"""Helper for finding whether an object is joined more than once."""
# threshold is the number of related objects that are acceptable
# when determining if related objects exist. threshold is 0 for most
# relationships. if the relationship is related_name, we know that
# there is already exactly 1 acceptable relationship (the one we are
# attempting to delete), so the threshold is 1
# attempting to delete), so the threshold is 1
threshold = 1 if rel == related_name else 0
# Raise a KeyError if rel is not a defined field on the db_obj model
@ -640,7 +641,7 @@ class OtherContactsForm(RegistrarForm):
label="Email",
error_messages={
"required": ("Enter an email address in the required format, like name@example.com."),
"invalid": ("Enter an email address in the required format, like name@example.com.")
"invalid": ("Enter an email address in the required format, like name@example.com."),
},
)
phone = PhoneNumberField(
@ -659,7 +660,7 @@ class OtherContactsForm(RegistrarForm):
"""
self.form_data_marked_for_deletion = False
super().__init__(*args, **kwargs)
self.empty_permitted=False
self.empty_permitted = False
def mark_form_for_deletion(self):
self.form_data_marked_for_deletion = True
@ -668,8 +669,8 @@ class OtherContactsForm(RegistrarForm):
"""
This method overrides the default behavior for forms.
This cleans the form after field validation has already taken place.
In this override, allow for a form which is deleted by user or marked for
deletion by formset to be considered valid even though certain required fields have
In this override, allow for a form which is deleted by user or marked for
deletion by formset to be considered valid even though certain required fields have
not passed field validation
"""
if self.form_data_marked_for_deletion or self.cleaned_data.get("DELETE"):
@ -694,9 +695,9 @@ class OtherContactsForm(RegistrarForm):
class BaseOtherContactsFormSet(RegistrarFormSet):
"""
FormSet for Other Contacts
There are two conditions by which a form in the formset can be marked for deletion.
One is if the user clicks 'DELETE' button, and this is submitted in the form. The
One is if the user clicks 'DELETE' button, and this is submitted in the form. The
other is if the YesNo form, which is submitted with this formset, is set to No; in
this case, all forms in formset are marked for deletion. Both of these conditions
must co-exist.
@ -705,6 +706,7 @@ class BaseOtherContactsFormSet(RegistrarFormSet):
tested and handled; this is configured with REVERSE_JOINS, which is an array of
strings representing the relationships between contact model and other models.
"""
JOIN = "other_contacts"
REVERSE_JOINS = [
"user",
@ -718,7 +720,7 @@ class BaseOtherContactsFormSet(RegistrarFormSet):
def get_deletion_widget(self):
return forms.HiddenInput(attrs={"class": "deletion"})
def __init__(self, *args, **kwargs):
"""
Override __init__ for RegistrarFormSet.
@ -737,14 +739,14 @@ class BaseOtherContactsFormSet(RegistrarFormSet):
Implements should_delete method from BaseFormSet.
"""
return self.formset_data_marked_for_deletion or cleaned.get("DELETE", False)
def pre_create(self, db_obj, cleaned):
"""Code to run before an item in the formset is created in the database."""
# remove DELETE from cleaned
if "DELETE" in cleaned:
cleaned.pop('DELETE')
cleaned.pop("DELETE")
return cleaned
def to_database(self, obj: DomainApplication):
self._to_database(obj, self.JOIN, self.REVERSE_JOINS, self.should_delete, self.pre_update, self.pre_create)

View file

@ -6,7 +6,6 @@ from django.test import Client, TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from registrar.forms.application_wizard import OtherContactsFormSet
from .common import MockEppLib, MockSESClient, completed_application, create_user # type: ignore
from django_webtest import WebTest # type: ignore
import boto3_mocking # type: ignore
@ -1083,7 +1082,7 @@ class DomainApplicationTests(TestWithUser, WebTest):
def test_delete_other_contact(self):
"""Other contacts can be deleted after being saved to database.
This formset uses the DJANGO DELETE widget. We'll test that by setting 2 contacts on an application,
loading the form and marking one contact up for deletion."""
# Populate the database with a domain application that
@ -1148,7 +1147,7 @@ class DomainApplicationTests(TestWithUser, WebTest):
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
other_contacts_form = other_contacts_page.forms[0]
# Minimal check to ensure the form is loaded with both other contacts
self.assertEqual(other_contacts_form["other_contacts-0-first_name"].value, "Testy2")
self.assertEqual(other_contacts_form["other_contacts-1-first_name"].value, "Testy3")
@ -1159,12 +1158,12 @@ class DomainApplicationTests(TestWithUser, WebTest):
# Submit the form
other_contacts_form.submit()
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
# Verify that the first dude was deleted
application = DomainApplication.objects.get()
self.assertEqual(application.other_contacts.count(), 1)
self.assertEqual(application.other_contacts.first().first_name, "Testy3")
def test_delete_other_contact_does_not_allow_zero_contacts(self):
"""Delete Other Contact does not allow submission with zero contacts."""
# Populate the database with a domain application that
@ -1221,7 +1220,7 @@ class DomainApplicationTests(TestWithUser, WebTest):
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
other_contacts_form = other_contacts_page.forms[0]
# Minimal check to ensure the form is loaded
self.assertEqual(other_contacts_form["other_contacts-0-first_name"].value, "Testy2")
@ -1231,19 +1230,20 @@ class DomainApplicationTests(TestWithUser, WebTest):
# Submit the form
other_contacts_form.submit()
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
# Verify that the contact was not deleted
application = DomainApplication.objects.get()
self.assertEqual(application.other_contacts.count(), 1)
self.assertEqual(application.other_contacts.first().first_name, "Testy2")
@skip("Can't figure out how to make this work")
def test_delete_other_contact_sets_visible_empty_form_as_required_after_failed_submit(self):
"""When you:
1. add an empty contact,
2. delete existing contacts,
3. then submit,
3. then submit,
The forms on page reload shows all the required fields and their errors."""
# Populate the database with a domain application that
# has 1 "other contact" assigned to it
# We'll do it from scratch so we can reuse the other contact
@ -1298,58 +1298,55 @@ class DomainApplicationTests(TestWithUser, WebTest):
self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
other_contacts_form = other_contacts_page.forms[0]
# other_contacts_form["other_contacts-has_other_contacts"] = "True"
# other_contacts_form.set("other_contacts-0-first_name", "")
# other_contacts_page = other_contacts_page.forms[0].submit()
# self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
# Print the content to inspect the HTML
# print(other_contacts_page.content.decode('utf-8'))
# other_contacts_form = other_contacts_page.forms[0]
# Access the "Add another contact" button and click it
# other_contacts_page = other_contacts_page.click('#add-form', index=0)
# Minimal check to ensure the form is loaded
self.assertEqual(other_contacts_form["other_contacts-0-first_name"].value, "Testy2")
# Get the formset from the response context
formset = other_contacts_page.context['forms'][1] # Replace with the actual context variable name
formset = other_contacts_page.context["forms"][1] # Replace with the actual context variable name
# Check the initial number of forms in the formset
initial_form_count = formset.total_form_count()
print(f'initial_form_count {initial_form_count}')
print(f"initial_form_count {initial_form_count}")
# Add a new form to the formset data
formset_data = formset.management_form.initial
formset_data['TOTAL_FORMS'] = initial_form_count + 1 # Increase the total form count
formset_data["TOTAL_FORMS"] = initial_form_count + 1 # Increase the total form count
print(f"initial_form_count {formset_data['TOTAL_FORMS']}")
formset.extra = 1
other_contacts_form_0 = formset[0]
other_contacts_form_1 = formset[1]
print(other_contacts_page.content.decode('utf-8'))
print(other_contacts_page.content.decode("utf-8"))
other_contacts_form_1.set("other_contacts-1-first_name", "Rachid")
# self.assertEqual(other_contacts_form["other_contacts-1-first_name"].value, "")
# # # Submit the form
# # other_contacts_form.submit()
# # self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
# # # Verify that the first dude was deleted
# # application = DomainApplication.objects.get()
# # # self.assertEqual(application.other_contacts.count(), 1)
# # # self.assertEqual(application.other_contacts.first().first_name, "Testy3")
def test_application_about_your_organiztion_interstate(self):
"""Special districts have to answer an additional question."""

View file

@ -486,7 +486,7 @@ class YourContact(ApplicationWizard):
class OtherContacts(ApplicationWizard):
template_name = "application_other_contacts.html"
forms = [forms.OtherContactsYesNoForm, forms.OtherContactsFormSet, forms.NoOtherContactsForm]
def is_valid(self, forms: list) -> bool:
"""Overrides default behavior defined in ApplicationWizard.
Depending on value in other_contacts_yes_no_form, marks forms in
@ -500,9 +500,9 @@ class OtherContacts(ApplicationWizard):
# set all the required other_contact fields as necessary since new forms
# were added through javascript
for form in forms[1].forms:
for _, field in form.fields.items():
for field_item, field in form.fields.items():
if field.required:
field.widget.attrs['required'] = 'required'
field.widget.attrs["required"] = "required"
all_forms_valid = True
# test first for yes_no_form validity