File: test_form_helper.py

package info (click to toggle)
python-crispy-bootstrap4 2024.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 660 kB
  • sloc: python: 1,994; sh: 6; makefile: 4
file content (659 lines) | stat: -rw-r--r-- 20,258 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
import re

import django
import pytest
from crispy_forms.bootstrap import (
    AppendedText,
    FieldWithButtons,
    PrependedAppendedText,
    PrependedText,
    StrictButton,
)
from crispy_forms.helper import FormHelper, FormHelpersException
from crispy_forms.layout import Button, Hidden, Layout, Reset, Submit
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
from crispy_forms.utils import render_crispy_form
from django import forms
from django.forms.models import formset_factory
from django.middleware.csrf import _get_new_csrf_string
from django.template import Context, Template
from django.test import override_settings
from django.test.html import parse_html
from django.urls import reverse

from .forms import SampleForm, SampleForm7, SampleForm8, SampleFormWithMedia
from .utils import parse_expected, parse_form

CONVERTERS = {
    "textinput": "textinput textInput inputtext",
    "fileinput": "fileinput fileUpload",
    "passwordinput": "textinput textInput",
}


def test_inputs():
    form_helper = FormHelper()
    form_helper.add_input(Submit("my-submit", "Submit", css_class="button white"))
    form_helper.add_input(Reset("my-reset", "Reset"))
    form_helper.add_input(Hidden("my-hidden", "Hidden"))
    form_helper.add_input(Button("my-button", "Button"))

    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy form form_helper %}
    """
    )
    c = Context({"form": SampleForm(), "form_helper": form_helper})
    html = template.render(c)

    assert "button white" in html
    assert 'id="submit-id-my-submit"' in html
    assert 'id="reset-id-my-reset"' in html
    assert 'name="my-hidden"' in html
    assert 'id="button-id-my-button"' in html
    assert 'class="btn"' in html
    assert "btn btn-primary" in html
    assert "btn btn-inverse" in html
    assert len(re.findall(r"<input[^>]+> <", html)) == 9


def test_invalid_form_method():
    form_helper = FormHelper()
    with pytest.raises(FormHelpersException):
        form_helper.form_method = "superPost"


def test_form_with_helper_without_layout():
    form_helper = FormHelper()
    form_helper.form_id = "this-form-rocks"
    form_helper.form_class = "forms-that-rock"
    form_helper.form_method = "GET"
    form_helper.form_action = "simpleAction"
    form_helper.form_error_title = "ERRORS"

    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy testForm form_helper %}
    """
    )

    # now we render it, with errors
    form = SampleForm({"password1": "wargame", "password2": "god"})
    form.is_valid()
    c = Context({"testForm": form, "form_helper": form_helper})
    html = template.render(c)

    # Lets make sure everything loads right
    assert html.count("<form") == 1
    assert "forms-that-rock" in html
    assert 'method="get"' in html
    assert 'id="this-form-rocks"' in html
    assert 'action="%s"' % reverse("simpleAction") in html

    assert "ERRORS" in html
    assert "<li>Passwords dont match</li>" in html

    # now lets remove the form tag and render it again. All the True items above
    # should now be false because the form tag is removed.
    form_helper.form_tag = False
    html = template.render(c)
    assert "<form" not in html
    assert "forms-that-rock" not in html
    assert 'method="get"' not in html
    assert 'id="this-form-rocks"' not in html


@override_settings(CRISPY_CLASS_CONVERTERS=CONVERTERS)
def test_form_show_errors_non_field_errors(settings):
    form = SampleForm({"password1": "wargame", "password2": "god"})
    form.helper = FormHelper()
    form.helper.form_show_errors = True
    form.is_valid()

    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy testForm %}
    """
    )

    # First we render with errors
    c = Context({"testForm": form})
    # Ensure those errors were rendered
    if django.VERSION < (5, 0):
        expected = parse_expected(
            "bootstrap4/test_form_helper/"
            "test_form_show_errors_non_field_errors_true_lt50.html"
        )
    else:
        expected = parse_expected(
            "bootstrap4/test_form_helper/"
            "test_form_show_errors_non_field_errors_true.html"
        )
    assert parse_html(template.render(c)) == expected

    # Now we render without errors
    form.helper.form_show_errors = False
    c = Context({"testForm": form})
    # Ensure errors were not rendered
    if django.VERSION < (5, 0):
        expected = parse_expected(
            "bootstrap4/test_form_helper/"
            "test_form_show_errors_non_field_errors_false_lt50.html"
        )
    else:
        expected = parse_expected(
            "bootstrap4/test_form_helper/"
            "test_form_show_errors_non_field_errors_false.html"
        )
    assert parse_html(template.render(c)) == expected


def test_media_is_included_by_default_with_bootstrap4():
    form = SampleFormWithMedia()
    form.helper = FormHelper()
    form.helper.template_pack = "bootstrap4"
    html = render_crispy_form(form)
    assert "test.css" in html
    assert "test.js" in html


def test_media_removed_when_include_media_is_false_with_bootstrap4():
    form = SampleFormWithMedia()
    form.helper = FormHelper()
    form.helper.template_pack = "bootstrap4"
    form.helper.include_media = False
    html = render_crispy_form(form)
    assert "test.css" not in html
    assert "test.js" not in html


def test_attrs():
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.attrs = {"id": "TestIdForm", "autocomplete": "off"}
    html = render_crispy_form(form)

    assert 'autocomplete="off"' in html
    assert 'id="TestIdForm"' in html


def test_template_context():
    helper = FormHelper()
    helper.attrs = {
        "id": "test-form",
        "class": "test-forms",
        "action": "submit/test/form",
        "autocomplete": "off",
    }
    node = CrispyFormNode("form", "helper")
    context = node.get_response_dict(helper, {}, False)

    assert context["form_id"] == "test-form"
    assert context["form_attrs"]["id"] == "test-form"
    assert "test-forms" in context["form_class"]
    assert "test-forms" in context["form_attrs"]["class"]
    assert context["form_action"] == "submit/test/form"
    assert context["form_attrs"]["action"] == "submit/test/form"
    assert context["form_attrs"]["autocomplete"] == "off"


def test_template_context_using_form_attrs():
    helper = FormHelper()
    helper.form_id = "test-form"
    helper.form_class = "test-forms"
    helper.form_action = "submit/test/form"
    node = CrispyFormNode("form", "helper")
    context = node.get_response_dict(helper, {}, False)

    assert context["form_id"] == "test-form"
    assert context["form_attrs"]["id"] == "test-form"
    assert "test-forms" in context["form_class"]
    assert "test-forms" in context["form_attrs"]["class"]
    assert context["form_action"] == "submit/test/form"
    assert context["form_attrs"]["action"] == "submit/test/form"


def test_template_helper_access():
    helper = FormHelper()
    helper.form_id = "test-form"

    assert helper["form_id"] == "test-form"


def test_without_helper():
    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy form %}
    """
    )
    c = Context({"form": SampleForm()})
    html = template.render(c)

    # Lets make sure everything loads right
    assert "<form" in html
    assert 'method="post"' in html
    assert "action" not in html


def test_formset_with_helper_without_layout():
    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy testFormSet formset_helper %}
    """
    )

    form_helper = FormHelper()
    form_helper.form_id = "thisFormsetRocks"
    form_helper.form_class = "formsets-that-rock"
    form_helper.form_method = "POST"
    form_helper.form_action = "simpleAction"

    SampleFormSet = formset_factory(SampleForm, extra=3)
    testFormSet = SampleFormSet()

    c = Context(
        {
            "testFormSet": testFormSet,
            "formset_helper": form_helper,
            "csrf_token": _get_new_csrf_string(),
        }
    )
    html = template.render(c)

    assert html.count("<form") == 1
    assert html.count("csrfmiddlewaretoken") == 1

    # Check formset management form
    assert "form-TOTAL_FORMS" in html
    assert "form-INITIAL_FORMS" in html
    assert "form-MAX_NUM_FORMS" in html

    assert "formsets-that-rock" in html
    assert 'method="post"' in html
    assert 'id="thisFormsetRocks"' in html
    assert 'action="%s"' % reverse("simpleAction") in html


def test_CSRF_token_POST_form():
    form_helper = FormHelper()
    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy form form_helper %}
    """
    )

    # The middleware only initializes the CSRF token when processing a real request
    # So using RequestContext or csrf(request) here does not work.
    # Instead I set the key `csrf_token` to a CSRF token manually, which `csrf_token`
    # tag uses
    c = Context(
        {
            "form": SampleForm(),
            "form_helper": form_helper,
            "csrf_token": _get_new_csrf_string(),
        }
    )
    html = template.render(c)

    assert "csrfmiddlewaretoken" in html


def test_CSRF_token_GET_form():
    form_helper = FormHelper()
    form_helper.form_method = "GET"
    template = Template(
        """
        {% load crispy_forms_tags %}
        {% crispy form form_helper %}
    """
    )

    c = Context(
        {
            "form": SampleForm(),
            "form_helper": form_helper,
            "csrf_token": _get_new_csrf_string(),
        }
    )
    html = template.render(c)

    assert "csrfmiddlewaretoken" not in html


def test_disable_csrf():
    form = SampleForm()
    helper = FormHelper()
    helper.disable_csrf = True
    html = render_crispy_form(form, helper, {"csrf_token": _get_new_csrf_string()})
    assert "csrf" not in html


def test_render_unmentioned_fields():
    test_form = SampleForm()
    test_form.helper = FormHelper()
    test_form.helper.layout = Layout("email")
    test_form.helper.render_unmentioned_fields = True

    html = render_crispy_form(test_form)
    assert html.count("<input") == 8


def test_render_unmentioned_fields_order():
    test_form = SampleForm7()
    test_form.helper = FormHelper()
    test_form.helper.layout = Layout("email")
    test_form.helper.render_unmentioned_fields = True

    html = render_crispy_form(test_form)
    assert html.count("<input") == 4
    assert (
        # From layout
        html.index('id="div_id_email"')
        # From form.Meta.fields
        < html.index('id="div_id_password"')
        < html.index('id="div_id_password2"')
        # From fields
        < html.index('id="div_id_is_company"')
    )

    test_form = SampleForm8()
    test_form.helper = FormHelper()
    test_form.helper.layout = Layout("email")
    test_form.helper.render_unmentioned_fields = True

    html = render_crispy_form(test_form)
    assert html.count("<input") == 4
    assert (
        # From layout
        html.index('id="div_id_email"')
        # From form.Meta.fields
        < html.index('id="div_id_password2"')
        < html.index('id="div_id_password"')
        # From fields
        < html.index('id="div_id_is_company"')
    )


def test_render_hidden_fields():
    from .utils import contains_partial

    test_form = SampleForm()
    test_form.helper = FormHelper()
    test_form.helper.layout = Layout("email")
    test_form.helper.render_hidden_fields = True

    html = render_crispy_form(test_form)
    assert html.count("<input") == 1

    # Now hide a couple of fields
    for field in ("password1", "password2"):
        test_form.fields[field].widget = forms.HiddenInput()

    html = render_crispy_form(test_form)
    assert html.count("<input") == 3
    assert html.count("hidden") == 2

    assert contains_partial(html, '<input name="password1" type="hidden"/>')
    assert contains_partial(html, '<input name="password2" type="hidden"/>')


def test_render_required_fields():
    test_form = SampleForm()
    test_form.helper = FormHelper()
    test_form.helper.layout = Layout("email")
    test_form.helper.render_required_fields = True

    html = render_crispy_form(test_form)
    assert html.count("<input") == 7


def test_helper_custom_template():
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.template = "custom_form_template.html"

    html = render_crispy_form(form)
    assert "<h1>Special custom form</h1>" in html


def test_helper_custom_field_template():
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.layout = Layout("password1", "password2")
    form.helper.field_template = "custom_field_template.html"

    html = render_crispy_form(form)
    assert html.count("<h1>Special custom field</h1>") == 2


def test_helper_custom_field_template_no_layout():
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.field_template = "custom_field_template.html"

    html = render_crispy_form(form)
    for field in form.fields:
        assert html.count('id="div_id_%s"' % field) == 1
    assert html.count("<h1>Special custom field</h1>") == len(form.fields)


def test_helper_std_field_template_no_layout():
    form = SampleForm()
    form.helper = FormHelper()

    html = render_crispy_form(form)
    for field in form.fields:
        assert html.count('id="div_id_%s"' % field) == 1


@override_settings(CRISPY_CLASS_CONVERTERS=CONVERTERS)
def test_bootstrap_form_show_errors_bs4():
    form = SampleForm(
        {
            "email": "invalidemail",
            "first_name": "first_name_too_long",
            "last_name": "last_name_too_long",
            "password1": "yes",
            "password2": "yes",
        }
    )
    form.helper = FormHelper()
    form.helper.layout = Layout(
        AppendedText("email", "whatever"),
        PrependedText("first_name", "blabla"),
        PrependedAppendedText("last_name", "foo", "bar"),
        AppendedText("password1", "whatever"),
        PrependedText("password2", "blabla"),
    )
    form.is_valid()
    form.helper.form_show_errors = True
    if django.VERSION < (5, 0):
        expected = (
            "bootstrap4/test_form_helper/bootstrap_form_show_errors_bs4_true_lt50.html"
        )
    else:
        expected = (
            "bootstrap4/test_form_helper/bootstrap_form_show_errors_bs4_true.html"
        )
    assert parse_form(form) == parse_expected(expected)
    form.helper.form_show_errors = False
    if django.VERSION < (5, 0):
        expected = (
            "bootstrap4/test_form_helper/bootstrap_form_show_errors_bs4_false_lt50.html"
        )
    else:
        expected = (
            "bootstrap4/test_form_helper/bootstrap_form_show_errors_bs4_false.html"
        )
    assert parse_form(form) == parse_expected(expected)


def test_error_text_inline(settings):
    form = SampleForm({"email": "invalidemail"})
    form.helper = FormHelper()
    layout = Layout(
        AppendedText("first_name", "wat"),
        PrependedText("email", "@"),
        PrependedAppendedText("last_name", "@", "wat"),
    )
    form.helper.layout = layout
    form.is_valid()
    html = render_crispy_form(form)

    help_class = "invalid-feedback"
    help_tag_name = "div"

    matches = re.findall(
        r'<span id="error_\d_\w*" class="%s"' % help_class, html, re.MULTILINE
    )
    assert len(matches) == 3

    form = SampleForm({"email": "invalidemail"})
    form.helper = FormHelper()
    form.helper.layout = layout
    form.helper.error_text_inline = False
    html = render_crispy_form(form)

    help_class = "invalid-feedback"
    help_tag_name = "p"

    matches = re.findall(
        r'<{} id="error_\d_\w*" class="{}"'.format(help_tag_name, help_class),
        html,
        re.MULTILINE,
    )
    assert len(matches) == 3


def test_error_and_help_inline():
    form = SampleForm({"email": "invalidemail"})
    form.helper = FormHelper()
    form.helper.error_text_inline = False
    form.helper.help_text_inline = True
    form.helper.layout = Layout("email")
    form.is_valid()
    html = render_crispy_form(form)

    # Check that help goes before error, otherwise CSS won't work
    help_position = html.find('<span id="hint_id_email" class="help-inline">')
    error_position = html.find('<p id="error_1_id_email" class="invalid-feedback">')
    assert help_position < error_position

    # Viceversa
    form = SampleForm({"email": "invalidemail"})
    form.helper = FormHelper()
    form.helper.error_text_inline = True
    form.helper.help_text_inline = False
    form.helper.layout = Layout("email")
    form.is_valid()
    html = render_crispy_form(form)

    # Check that error goes before help, otherwise CSS won't work
    error_position = html.find('<span id="error_1_id_email" class="help-inline">')
    help_position = html.find('<small id="hint_id_email" class="form-text text-muted">')
    assert error_position < help_position


def test_form_show_labels():
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.layout = Layout(
        "password1",
        FieldWithButtons("password2", StrictButton("Confirm")),
        PrependedText("first_name", "Mr."),
        AppendedText("last_name", "@"),
        PrependedAppendedText("datetime_field", "on", "secs"),
    )
    form.helper.form_show_labels = False

    html = render_crispy_form(form)
    assert html.count("<label") == 0


def test_label_class_and_field_class_bs4():
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.label_class = "col-lg-2"
    form.helper.field_class = "col-lg-8"
    html = render_crispy_form(form)

    assert '<div class="form-group">' in html
    assert '<div class="col-lg-8">' in html
    assert html.count("col-lg-8") == 7
    assert "offset" not in html

    form.helper.label_class = "col-sm-3 col-md-4"
    form.helper.field_class = "col-sm-8 col-md-6"
    html = render_crispy_form(form)

    assert '<div class="form-group">' in html
    assert '<div class="col-sm-8 col-md-6">' in html
    assert html.count("col-sm-8") == 7
    assert "offset" not in html


def test_label_class_and_field_class_bs4_offset_when_horizontal():
    # Test col-XX-YY pattern
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.label_class = "col-lg-2"
    form.helper.field_class = "col-lg-8"
    form.helper.form_class = "form-horizontal"
    html = render_crispy_form(form)

    assert '<div class="form-group row">' in html
    assert '<div class="offset-lg-2 col-lg-8">' in html
    assert html.count("col-lg-8") == 7

    # Test multi col-XX-YY pattern and col-X pattern

    form.helper.label_class = "col-sm-3 col-md-4 col-5 col-lg-4"
    form.helper.field_class = "col-sm-8 col-md-6 col-7 col-lg-8"
    html = render_crispy_form(form)

    assert '<div class="form-group row">' in html
    assert (
        '<div class="offset-sm-3 offset-md-4 offset-5 offset-lg-4 col-sm-8 '
        'col-md-6 col-7 col-lg-8">' in html
    )
    assert html.count("col-sm-8") == 7
    assert html.count("col-md-6") == 7
    assert html.count("col-7") == 7
    assert html.count("col-lg-8") == 7


def test_form_group_with_form_inline_bs4():
    form = SampleForm()
    form.helper = FormHelper()
    html = render_crispy_form(form)
    assert '<div class="form-group">' in html

    # .row class shouldn't be together with .form-group in inline forms
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.form_class = "form-inline"
    form.helper.field_template = "bootstrap4/layout/inline_field.html"
    html = render_crispy_form(form)
    assert '<div class="form-group row">' not in html


def test_passthrough_context():
    """
    Test to ensure that context is passed through implicitly from outside of
    the crispy form into the crispy form templates.
    """
    form = SampleForm()
    form.helper = FormHelper()
    form.helper.template = "custom_form_template_with_context.html"

    c = {"prefix": "foo", "suffix": "bar"}

    html = render_crispy_form(form, helper=form.helper, context=c)
    assert "Got prefix: foo" in html
    assert "Got suffix: bar" in html