test_choicewidget.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import copy
  2. from django.forms.widgets import ChoiceWidget
  3. from .base import WidgetTest
  4. class ChoiceWidgetTest(WidgetTest):
  5. widget = ChoiceWidget
  6. @property
  7. def nested_widget(self):
  8. return self.widget(
  9. choices=(
  10. ("outer1", "Outer 1"),
  11. ('Group "1"', (("inner1", "Inner 1"), ("inner2", "Inner 2"))),
  12. )
  13. )
  14. def test_deepcopy(self):
  15. """
  16. __deepcopy__() should copy all attributes properly.
  17. """
  18. widget = self.widget()
  19. obj = copy.deepcopy(widget)
  20. self.assertIsNot(widget, obj)
  21. self.assertEqual(widget.choices, obj.choices)
  22. self.assertIsNot(widget.choices, obj.choices)
  23. self.assertEqual(widget.attrs, obj.attrs)
  24. self.assertIsNot(widget.attrs, obj.attrs)
  25. def test_options(self):
  26. options = list(
  27. self.widget(choices=self.beatles).options(
  28. "name",
  29. ["J"],
  30. attrs={"class": "super"},
  31. )
  32. )
  33. self.assertEqual(len(options), 4)
  34. self.assertEqual(options[0]["name"], "name")
  35. self.assertEqual(options[0]["value"], "J")
  36. self.assertEqual(options[0]["label"], "John")
  37. self.assertEqual(options[0]["index"], "0")
  38. self.assertIs(options[0]["selected"], True)
  39. # Template-related attributes
  40. self.assertEqual(options[1]["name"], "name")
  41. self.assertEqual(options[1]["value"], "P")
  42. self.assertEqual(options[1]["label"], "Paul")
  43. self.assertEqual(options[1]["index"], "1")
  44. self.assertIs(options[1]["selected"], False)
  45. def test_optgroups_integer_choices(self):
  46. """The option 'value' is the same type as what's in `choices`."""
  47. groups = list(
  48. self.widget(choices=[[0, "choice text"]]).optgroups("name", ["vhs"])
  49. )
  50. label, options, index = groups[0]
  51. self.assertEqual(options[0]["value"], 0)
  52. def test_renders_required_when_possible_to_select_empty_field_none(self):
  53. widget = self.widget(choices=[(None, "select please"), ("P", "Paul")])
  54. self.assertIs(widget.use_required_attribute(initial=None), True)
  55. def test_renders_required_when_possible_to_select_empty_field_list(self):
  56. widget = self.widget(choices=[["", "select please"], ["P", "Paul"]])
  57. self.assertIs(widget.use_required_attribute(initial=None), True)
  58. def test_renders_required_when_possible_to_select_empty_field_str(self):
  59. widget = self.widget(choices=[("", "select please"), ("P", "Paul")])
  60. self.assertIs(widget.use_required_attribute(initial=None), True)