1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
from wtforms import Form
from wtforms_test import FormTestCase
from tests import MultiDict
from wtforms_components import SelectField
class Dummy:
fruits = []
class TestSelectField(FormTestCase):
choices = (
("Fruits", (("apple", "Apple"), ("peach", "Peach"), ("pear", "Pear"))),
(
"Vegetables",
(
("cucumber", "Cucumber"),
("potato", "Potato"),
("tomato", "Tomato"),
),
),
)
def init_form(self, **kwargs):
class TestForm(Form):
fruit = SelectField(**kwargs)
self.form_class = TestForm
return self.form_class
def test_understands_nested_choices(self):
form_class = self.init_form(choices=self.choices)
form = form_class(MultiDict([("fruit", "invalid")]))
form.validate()
assert len(form.errors["fruit"]) == 1
def test_understands_mixing_of_choice_types(self):
choices = (
("Fruits", (("apple", "Apple"), ("peach", "Peach"), ("pear", "Pear"))),
("cucumber", "Cucumber"),
)
form_class = self.init_form(choices=choices)
form = form_class(MultiDict([("fruit", "cucumber")]))
form.validate()
assert len(form.errors) == 0
def test_understands_callables_as_choices(self):
form_class = self.init_form(choices=lambda: [])
form = form_class(MultiDict([("fruit", "invalid")]))
form.validate()
assert len(form.errors["fruit"]) == 1
def test_option_selected(self):
form_class = self.init_form(choices=self.choices)
obj = Dummy()
obj.fruit = "peach"
form = form_class(obj=obj)
assert '<option selected value="peach">Peach</option>' in str(form.fruit)
def test_nested_option_selected_by_field_default_value(self):
form_class = self.init_form(choices=self.choices, default="pear")
form = form_class()
assert '<option selected value="pear">Pear</option>' in str(form.fruit)
def test_option_selected_by_field_default_value(self):
choices = [("apple", "Apple"), ("peach", "Peach"), ("pear", "Pear")]
form_class = self.init_form(choices=choices, default="pear")
form = form_class()
assert '<option selected value="pear">Pear</option>' in str(form.fruit)
def test_callable_option_selected_by_field_default_value(self):
def choices():
return [("apple", "Apple"), ("peach", "Peach"), ("pear", "Pear")]
form_class = self.init_form(choices=choices, default="pear")
form = form_class()
assert '<option selected value="pear">Pear</option>' in str(form.fruit)
def test_data_coercion(self):
choices = (
("Fruits", ((0, "Apple"), (1, "Peach"), (2, "Pear"))),
(3, "Cucumber"),
)
form_class = self.init_form(choices=choices, coerce=int)
form = form_class(MultiDict([("fruit", "1")]))
form.validate()
assert not form.errors
|