Skip to content

Commit

Permalink
Fix dsfr_input_class_attr triggering eaunexpected validation in DsfrB…
Browse files Browse the repository at this point in the history
…aseForm.__init__ (#190)
  • Loading branch information
christophehenry authored Dec 17, 2024
1 parent 830c563 commit 7c18a3d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
54 changes: 54 additions & 0 deletions dsfr/test/test_forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from typing import NoReturn

from django import forms
from django.test import SimpleTestCase


from dsfr.forms import DsfrBaseForm


class DsfrBaseFormTestCase(SimpleTestCase):
class TestForm(DsfrBaseForm):
book_format = forms.ChoiceField(
label="Format",
choices=(
("PAPER", "Papier"),
("NUM", "Numérique"),
),
)
book_format2 = forms.ChoiceField(
label="Format",
choices=(
("PAPER", "Papier"),
("NUM", "Numérique"),
),
widget=forms.RadioSelect,
)
user_id = forms.CharField(widget=forms.HiddenInput)

def test_init_sets_attributes(self):
form = self.TestForm(data={})
self.assertEqual(form.fields["book_format"].widget.attrs["class"], "fr-select")
self.assertEqual(
form.fields["book_format"].widget.group_class, "fr-select-group"
)
self.assertEqual(form.fields["book_format2"].widget.attrs["dsfr"], "dsfr")
self.assertEqual(
form.fields["book_format2"].widget.group_class, "fr-radio-group"
)
self.assertEqual(form.fields["user_id"].widget.attrs, {})

def test_init_dont_trigger_form_validation(self):
test_ctx = self

class AssertForm(self.TestForm):
@property
def errors(self) -> NoReturn:
test_ctx.fail("No validation expected")

# __init__ should not trigger validation
AssertForm(data={})

with self.assertRaises(self.failureException):
# is_valid should trigger validation
AssertForm(data={}).is_valid()
3 changes: 2 additions & 1 deletion dsfr/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ def dsfr_input_class_attr(bf: BoundField):
):
bf.field.widget.attrs["class"] = "fr-input"

if bf.errors:
# bf.errors triggers form validation. We need to check form._errors to prevent that
if bf.form._errors and bf.errors:
bf.field.widget.attrs.update(
{"aria-invalid": "true", "aria-describedby": f"{bf.auto_id}-desc-error"}
)
Expand Down

0 comments on commit 7c18a3d

Please sign in to comment.