|
3 | 3 |
|
4 | 4 | from django import forms |
5 | 5 | from django.test import SimpleTestCase |
| 6 | +from django.test.testcases import assert_and_parse_html |
6 | 7 |
|
7 | 8 | from postgres_composite_types.forms import CompositeTypeField |
8 | 9 |
|
@@ -55,13 +56,14 @@ def test_validation(self): |
55 | 56 | # Errors should be formatted like 'Label: Error message' |
56 | 57 | self.assertEqual(str(form.errors['simple_field'][0]), |
57 | 58 | 'A number: Enter a whole number.') |
| 59 | + |
58 | 60 | # Fields with validation errors should render with their invalid input |
59 | | - self.assertHTMLEqual( |
60 | | - str(form['simple_field']['a']), |
| 61 | + self.assertHTMLContains( |
61 | 62 | """ |
62 | 63 | <input id="id_simple_field-a" name="simple_field-a" |
63 | 64 | placeholder="A number" required type="number" value="one" /> |
64 | | - """) |
| 65 | + """, |
| 66 | + str(form['simple_field'])) |
65 | 67 |
|
66 | 68 | def test_subfield_validation(self): |
67 | 69 | """Errors on subfields should be accessible""" |
@@ -92,6 +94,42 @@ def test_nested_prefix(self): |
92 | 94 | self.assertEqual(a_bound_field.html_name, |
93 | 95 | 'step1-simple_field-a') |
94 | 96 |
|
| 97 | + def test_initial_data(self): |
| 98 | + """ |
| 99 | + Check that forms with initial data render with the fields prepopulated. |
| 100 | + """ |
| 101 | + initial = SimpleType( |
| 102 | + a=1, b='foo', c=datetime.datetime(2016, 5, 24, 17, 38, 32)) |
| 103 | + form = self.SimpleForm(initial={'simple_field': initial}) |
| 104 | + |
| 105 | + self.assertHTMLContains( |
| 106 | + """ |
| 107 | + <input id="id_simple_field-a" name="simple_field-a" |
| 108 | + placeholder="A number" required type="number" value="1" /> |
| 109 | + """, |
| 110 | + str(form['simple_field'])) |
| 111 | + |
| 112 | + # pylint:disable=invalid-name |
| 113 | + def assertHTMLContains(self, text, content, count=None, msg=None): |
| 114 | + """ |
| 115 | + Assert that the HTML snippet ``text`` is found within the HTML snippet |
| 116 | + ``content``. Like assertContains, but works with plain strings instead |
| 117 | + of Response instances. |
| 118 | + """ |
| 119 | + content = assert_and_parse_html( |
| 120 | + self, content, None, "HTML content to search in is not valid:") |
| 121 | + text = assert_and_parse_html( |
| 122 | + self, text, None, "HTML content to search for is not valid:") |
| 123 | + |
| 124 | + matches = content.count(text) |
| 125 | + if count is None: |
| 126 | + self.assertTrue( |
| 127 | + matches > 0, msg=msg or 'Could not find HTML snippet') |
| 128 | + else: |
| 129 | + self.assertEqual( |
| 130 | + matches, count, |
| 131 | + msg=msg or 'Found %d matches, expecting %d' % (matches, count)) |
| 132 | + |
95 | 133 |
|
96 | 134 | class OptionalFieldTests(SimpleTestCase): |
97 | 135 | """ |
|
0 commit comments