Skip to content

Commit c175a07

Browse files
author
Tim Heap
committed
Add tests for CompositeTypeForm with initial data
1 parent e32276f commit c175a07

1 file changed

Lines changed: 41 additions & 3 deletions

File tree

tests/test_forms.py

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from django import forms
55
from django.test import SimpleTestCase
6+
from django.test.testcases import assert_and_parse_html
67

78
from postgres_composite_types.forms import CompositeTypeField
89

@@ -55,13 +56,14 @@ def test_validation(self):
5556
# Errors should be formatted like 'Label: Error message'
5657
self.assertEqual(str(form.errors['simple_field'][0]),
5758
'A number: Enter a whole number.')
59+
5860
# Fields with validation errors should render with their invalid input
59-
self.assertHTMLEqual(
60-
str(form['simple_field']['a']),
61+
self.assertHTMLContains(
6162
"""
6263
<input id="id_simple_field-a" name="simple_field-a"
6364
placeholder="A number" required type="number" value="one" />
64-
""")
65+
""",
66+
str(form['simple_field']))
6567

6668
def test_subfield_validation(self):
6769
"""Errors on subfields should be accessible"""
@@ -92,6 +94,42 @@ def test_nested_prefix(self):
9294
self.assertEqual(a_bound_field.html_name,
9395
'step1-simple_field-a')
9496

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+
95133

96134
class OptionalFieldTests(SimpleTestCase):
97135
"""

0 commit comments

Comments
 (0)