File: test_field.py

package info (click to toggle)
wtforms 3.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,064 kB
  • sloc: python: 5,264; makefile: 27; sh: 17
file content (215 lines) | stat: -rw-r--r-- 5,618 bytes parent folder | download
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import pytest
from markupsafe import Markup

from tests.common import DummyPostData
from wtforms import meta
from wtforms import validators
from wtforms.fields import Field
from wtforms.fields import StringField
from wtforms.form import Form


class F(Form):
    a = StringField(default="hello", render_kw={"readonly": True, "foo": "bar"})
    b = StringField(validators=[validators.InputRequired()])


def test_unbound_field():
    unbound = F.a
    assert unbound.creation_counter != 0
    assert unbound.field_class is StringField
    assert unbound.args == ()
    assert unbound.kwargs == {
        "default": "hello",
        "render_kw": {"readonly": True, "foo": "bar"},
    }
    assert repr(unbound).startswith("<UnboundField(StringField")


def test_htmlstring():
    assert isinstance(F().a.__html__(), Markup)


def test_str_coerce():
    field = F().a
    assert isinstance(str(field), str)
    assert str(field) == str(field)


def test_unicode_coerce():
    field = F().a
    assert str(field) == field()


def test_process_formdata():
    field = F().a
    Field.process_formdata(field, [42])
    assert field.data == 42


def test_meta_attribute():
    # Can we pass in meta via _form?
    form = F()
    assert form.a.meta is form.meta

    # Can we pass in meta via _meta?
    form_meta = meta.DefaultMeta()
    field = StringField(name="Foo", _form=None, _meta=form_meta)
    assert field.meta is form_meta

    # Do we fail if both _meta and _form are None?
    with pytest.raises(TypeError):
        StringField(name="foo", _form=None)


def test_render_kw():
    form = F()
    assert (
        form.a()
        == '<input foo="bar" id="a" name="a" readonly type="text" value="hello">'
    )
    assert (
        form.a(foo="baz")
        == '<input foo="baz" id="a" name="a" readonly type="text" value="hello">'
    )
    assert form.a(foo="baz", readonly=False, other="hello") == (
        '<input foo="baz" id="a" name="a" other="hello" type="text" value="hello">'
    )


def test_render_special():
    class F(Form):
        s = StringField(render_kw={"class_": "foo"})

    assert F().s() == '<input class="foo" id="s" name="s" type="text" value="">'
    assert (
        F().s(**{"class": "bar"})
        == '<input class="bar" id="s" name="s" type="text" value="">'
    )
    assert (
        F().s(**{"class_": "bar"})
        == '<input class="bar" id="s" name="s" type="text" value="">'
    )

    class G(Form):
        s = StringField(render_kw={"class__": "foo"})

    assert G().s() == '<input class="foo" id="s" name="s" type="text" value="">'
    assert (
        G().s(**{"class__": "bar"})
        == '<input class="bar" id="s" name="s" type="text" value="">'
    )

    class H(Form):
        s = StringField(render_kw={"for_": "foo"})

    assert H().s() == '<input for="foo" id="s" name="s" type="text" value="">'
    assert (
        H().s(**{"for": "bar"})
        == '<input for="bar" id="s" name="s" type="text" value="">'
    )
    assert (
        H().s(**{"for_": "bar"})
        == '<input for="bar" id="s" name="s" type="text" value="">'
    )


def test_required_flag():
    form = F()
    assert form.b() == '<input id="b" name="b" required type="text" value="">'


def test_check_validators():
    v1 = "Not callable"
    v2 = validators.DataRequired

    with pytest.raises(
        TypeError,
        match=rf"{v1} is not a valid validator because it is not callable",
    ):
        Field(validators=[v1])

    with pytest.raises(
        TypeError,
        match=rf"{v2} is not a valid validator because "
        "it is a class, it should be an "
        "instance",
    ):
        Field(validators=[v2])


def test_custom_name():
    class F(Form):
        foo = StringField(name="bar", default="default")
        x = StringField()

    class ObjFoo:
        foo = "obj"

    class ObjBar:
        bar = "obj"

    f = F(DummyPostData(foo="data"))
    assert f.foo.data == "default"
    assert 'value="default"' in f.foo()

    f = F(DummyPostData(bar="data"))
    assert f.foo.data == "data"
    assert 'value="data"' in f.foo()

    f = F(foo="kwarg")
    assert f.foo.data == "kwarg"
    assert 'value="kwarg"' in f.foo()

    f = F(bar="kwarg")
    assert f.foo.data == "default"
    assert 'value="default"' in f.foo()

    f = F(obj=ObjFoo())
    assert f.foo.data == "obj"
    assert 'value="obj"' in f.foo()

    f = F(obj=ObjBar())
    assert f.foo.data == "default"
    assert 'value="default"' in f.foo()


class PrePostTestField(StringField):
    def pre_validate(self, form):
        if self.data == "stoponly":
            raise validators.StopValidation()
        elif self.data.startswith("stop"):
            raise validators.StopValidation("stop with message")

    def post_validate(self, form, stopped):
        if self.data == "p":
            raise validators.ValidationError("Post")
        elif stopped and self.data == "stop-post":
            raise validators.ValidationError("Post-stopped")


def _init_field(value):
    class F(Form):
        a = PrePostTestField(validators=[validators.Length(max=1, message="too long")])

    form = F(a=value)
    form.validate()
    return form.a


def test_pre_stop():
    a = _init_field("long")
    assert a.errors == ["too long"]

    stoponly = _init_field("stoponly")
    assert stoponly.errors == []

    stopmessage = _init_field("stopmessage")
    assert stopmessage.errors == ["stop with message"]


def test_post():
    a = _init_field("p")
    assert a.errors == ["Post"]
    stopped = _init_field("stop-post")
    assert stopped.errors == ["stop with message", "Post-stopped"]