def test_nested_form_validation_output(self): schema_nested = schemaish.Structure([ ("one", schemaish.Structure([ ("a", schemaish.String(validator=validatish.Required())), ("b", schemaish.String()), ("c", schemaish.Structure([("x", schemaish.String()), ("y", schemaish.String())])), ])), ]) # Test passing validation name = "Nested Form two" form = formish.Form(schema_nested, name) request = Request(name, { 'one.a': 'woot!', 'one.b': '', 'one.c.x': '', 'one.c.y': '' }) expected = { 'one': { 'a': u'woot!', 'b': None, 'c': { 'x': None, 'y': None } } } self.assert_(form.validate(request) == expected) self.assertEquals(form.errors, {})
def _schema(self): return schemaish.Structure([ ('seq', schemaish.Sequence( schemaish.Structure([ ('foo', schemaish.String(validator=validatish.Required())) ]))), ])
def test_structure_error(self): """ Check structure field templates emit errors correctly. """ self._test( schemaish.Structure([ ('structure', schemaish.Structure([('string', schemaish.String())])) ]), 'structure')
class TestFormData(unittest.TestCase): """Build a Simple Form and test that it doesn't raise exceptions on build and that the methods/properties are as expected""" schema_nested = schemaish.Structure([ ("one", schemaish.Structure([ ("a", schemaish.String( validator=validatish.Required(), description= "This is a field with name a and title A and has a Required validator" )), ("b", schemaish.String(title='bee')), ("c", schemaish.Structure([("x", schemaish.String(title='cee')), ("y", schemaish.String())])), ])), ]) def test_titles(self): form = formish.Form(self.schema_nested, 'nested') assert form['one.b'].title == 'bee' assert form['one.c.x'].title == 'cee' form['one.b'].title = 'bee bee cee' assert form['one.b'].title == 'bee bee cee' form['one.c.x'].title = 'bee bee cee' assert form['one.c.x'].title == 'bee bee cee' def test_widgets(self): form = formish.Form(self.schema_nested, 'nested') assert isinstance(form['one.a'].widget.widget, formish.Input) form['one.a'].widget = formish.TextArea() assert isinstance(form['one.a'].widget.widget, formish.TextArea) def test_description(self): form = formish.Form(self.schema_nested, 'nested') assert str( form['one.a'].description ) == "This is a field with name a and title A and has a Required validator" form['one.a'].description = "This is a new description" assert str(form['one.a'].description) == "This is a new description" def test_value(self): form = formish.Form(self.schema_nested, 'nested') self.assertRaises(KeyError, setattr, form['one.a'], 'value', 7)
def test_nested_form(self): """Test a form two nested levels""" one = schemaish.Structure([("a", schemaish.String()), ("b", schemaish.String())]) two = schemaish.Structure([("a", schemaish.String()), ("b", schemaish.String())]) schema_nested = schemaish.Structure([("one", one), ("two", two)]) name = "Nested Form One" form = formish.Form(schema_nested, name) # stored schema assert form.structure.attr is schema_nested # number of fields reflects first level assert len(list(form.fields)) == 2
def test_datetuple_type(self): schema_flat = schemaish.Structure([("a", schemaish.Date()), ("b", schemaish.String())]) name = "Date Form" form = formish.Form(schema_flat, name) form['a'].widget = formish.DateParts() r = {'a.day': '1', 'a.month': '3', 'a.year': '1966', 'b': '4'} request = Request(name, r) from datetime import date d = date(1966, 3, 1) # Check the data is converted correctly self.assertEquals(form.validate(request), {'a': d, 'b': '4'}) # Check req to data self.assertEqual( form.widget.from_request_data(form, request.get_post()), { 'a': d, 'b': '4' }) # Check data to req self.assert_( form.widget.to_request_data(form, { 'a': d, 'b': '4' }) == { 'a': { 'month': [3], 'day': [1], 'year': [1966] }, 'b': ['4'] })
def test_failure_and_success_callables(self): schema_flat = schemaish.Structure([ ("a", schemaish.Integer(validator=validatish.Range(min=10))), ("b", schemaish.String()) ]) name = "Integer Form" form = formish.Form(schema_flat, name) r = {'a': '2', 'b': '4'} request = Request(name, r) self.assertEquals(form.validate(request, failure, success), 'failure') self.assertEquals(form.validate(request, failure), 'failure') self.assertRaises(formish.FormError, form.validate, request, success_callable=success) r = {'a': '12', 'b': '4'} request = Request(name, r) form = formish.Form(schema_flat, name) self.assertEquals(form.validate(request, failure, success), 'success') self.assertEquals(form.validate(request, success_callable=success), 'success') self.assertEquals(form.validate(request, failure_callable=failure), { 'a': 12, 'b': '4' })
def form_from_controller(controller, form_id, actions=(), method='POST'): form_schema = schemaish.Structure() form_fields = controller.form_fields() for fieldname, field in form_fields: form_schema.add(fieldname, field) form = Form(form_schema, name=form_id, add_default_action=False, method=method) form.controller = controller for action in actions: form.add_action(action.name, action.title) form_widgets = [] if hasattr(controller, 'form_widgets'): form_widgets = controller.form_widgets(form_fields) for name, widget in form_widgets.items(): form[name].widget = widget defaults = None if hasattr(controller, 'form_defaults'): defaults = controller.form_defaults() form.defaults = defaults return form
def test_integer_form(self): """ Form with a couple of integer fields """ schema = schemaish.Structure() schema.add('fieldOne', schemaish.Integer()) schema.add('fieldTwo', schemaish.Integer()) form_name = 'form_name' form = formish.Form(schema, form_name) request_data = {'fieldOne': '1', 'fieldTwo': '2'} expected_data = {'fieldOne': 1, 'fieldTwo': 2} request = self.Request(form_name, request_data) data = form.validate(request) assert data == expected_data form.defaults = expected_data htmlsoup = BeautifulSoup(form()) assert htmlsoup.findAll( id='form_name-fieldOne--field' )[0]['class'] == 'field form_name-fieldOne type-integer widget-input' assert htmlsoup.findAll( id='form_name-fieldTwo--field' )[0]['class'] == 'field form_name-fieldTwo type-integer widget-input' assert htmlsoup.findAll(id='form_name-fieldOne')[0]['value'] == '1' assert htmlsoup.findAll(id='form_name-fieldTwo')[0]['value'] == '2'
def test_date_dateparts_form(self): """ Form with a date """ schema = schemaish.Structure() schema.add('a', schemaish.Date()) form_name = 'form_name' form = formish.Form(schema, form_name) form['a'].widget = formish.DateParts() request = self.Request(form_name, { 'a.year': '', 'a.month': '', 'a.day': '' }) data = form.validate(request) assert data == {'a': None} request_data = {'a.day': '18', 'a.month': '12', 'a.year': '1966'} expected_data = {'a': date(1966, 12, 18)} request = self.Request(form_name, request_data) data = form.validate(request) assert data == expected_data form.defaults = expected_data htmlsoup = BeautifulSoup(form()) assert htmlsoup.findAll( id='form_name-a--field' )[0]['class'] == 'field form_name-a type-date widget-dateparts' assert htmlsoup.findAll(id='form_name-a')[0]['value'] == '18'
def test_date_form(self): """ Form with a date """ schema = schemaish.Structure() schema.add('a', schemaish.Date()) form_name = 'form_name' form = formish.Form(schema, form_name) request_data = {'a': '1966-12-18'} expected_data = {'a': date(1966, 12, 18)} request = self.Request(form_name, request_data) try: data = form.validate(request) except: pass assert data == expected_data form.defaults = expected_data htmlsoup = BeautifulSoup(form()) assert htmlsoup.findAll( id='form_name-a--field' )[0]['class'] == 'field form_name-a type-date widget-input' assert htmlsoup.findAll(id='form_name-a')[0]['value'] == '1966-12-18'
def test_form_classes_not_shared(self): schema = schemaish.Structure() form = formish.Form(schema) form.classes.append('foo') form = formish.Form(schema) print "*****", form.classes self.assertTrue(set(form.classes) == set(['formish-form']))
def test_complex_error_all(self): schema = schemaish.Structure([ ("one", schemaish.Integer(validator=v.All( v.Required(), v.Integer(), v.Range(min=18), v.Range(min=20), ))), ]) f = formish.Form(schema, name="form", add_default_action=False) f.add_action('submit', "Submit Me") r = webob.Request.blank('http://localhost/', environ={'REQUEST_METHOD': 'POST'}) r.POST['__formish_form__'] = 'form' r.POST['one'] = '9' try: f.validate(r) except fv.FormError: assert str( f.errors['one'] ) == 'must be greater than or equal to 18; must be greater than or equal to 20' assert str(f['one'].field.errors.exceptions[0] ) == 'must be greater than or equal to 18'
def test_simple(self): """ Check simple field templates emit errors correctly. """ self._test(schemaish.Structure([ ('simple', schemaish.String()), ]), 'simple')
def test_form_defaults_clears_request_data(self): form = formish.Form( schemaish.Structure([("field", schemaish.String())])) form.request_data = {'field': ['value']} form.defaults = {'field': 'default value'} assert form._defaults == {'field': 'default value'} assert form._request_data == None assert 'name="field" value="default value"' in form()
def test_form_retains_request_data(self): form = formish.Form( schemaish.Structure([("field", schemaish.String())]), 'form') assert 'name="field" value=""' in form() data = form.validate(Request('form', {'field': 'value'})) assert data == {'field': 'value'} assert form.request_data['field'] == ['value'] assert 'name="field" value="value"' in form()
def test_unicode_in_template(self): # Check that new item template encoding is ok with unicode characters. schema = schemaish.Structure([ ('seq', schemaish.Sequence(schemaish.String())) ]) form = formish.Form(schema) form['seq.*'].widget = formish.SelectChoice( options=[('GBP', '£'.decode('utf-8'))]) form()
def test_form_classes(self): schema = schemaish.Structure() form = formish.Form(schema) self.assertTrue(set(form.classes) == set(['formish-form'])) form = formish.Form(schema, classes='foo') self.assertTrue(set(form.classes) == set(['formish-form', 'foo'])) form = formish.Form(schema, classes=['foo', 'bar']) self.assertTrue( set(form.classes) == set(['formish-form', 'foo', 'bar']))
def test_default(self): form = formish.Form( schemaish.Structure([ ('foo', schemaish.String()), ])) form['foo'].widget = formish.SelectChoice(['a', 'b']) self.assertTrue('selected="selected"' not in form()) form.defaults = {'foo': 'a'} self.assertTrue('value="a" selected="selected"' in form())
def get_form(request): schema = schemaish.Structure() schema.add('username', schemaish.String()) schema.add('password', schemaish.String()) for q in get_questions(request): schema.add(q, schemaish.String(validator=validatish.Required())) form = formish.Form(schema) form['password'].widget = formish.CheckedPassword() return form
def test_simple_validation(self): schema_flat = schemaish.Structure([("a", schemaish.Integer())]) name = "Integer Form" form = formish.Form(schema_flat, name) r = {'a': '3'} request = Request(name, r) reqr = {'a': ['3']} # Does the form produce an int and a string self.assertEquals(form.validate(request), {'a': 3})
def test_renders_with_options(self): schema = schemaish.Structure() schema.add('foo', schemaish.Sequence(schemaish.String())) form = formish.Form(schema) form['foo'].widget = formish.CheckboxMultiChoice(options=[('opt1', 'Opt #1')]) html = form() assert 'foo' in html assert 'opt1' in html assert 'Opt #1' in html
def test_none_option(self): form = formish.Form( schemaish.Structure([ ('foo', schemaish.String()), ])) form['foo'].widget = formish.SelectChoice(options=['a', 'b']) self.assertTrue('value=""' in form()) form['foo'].widget = formish.SelectChoice(options=['a', 'b'], none_option=None) self.assertTrue('value=""' not in form())
def test_date_conversion(self): from datetime import date, datetime schema = schemaish.Structure([('date', schemaish.Date())]) form = formish.Form(schema, name='form') form['date'].widget = formish.SelectChoice([(date(1970, 1, 1), 'a'), (date(1980, 1, 1), 'b'), (datetime(1990, 1, 1), 'c')]) self.assertRaises(formish.FormError, form.validate, Request('form', {'date': '1990-01-01T00:00:00'})) form()
def test_flat_form(self): """Test a form that has no nested sections """ schema_flat = schemaish.Structure([("a", schemaish.String()), ("b", schemaish.String())]) name = "Flat Form" form = formish.Form(schema_flat, name) # stored schema assert form.structure.attr is schema_flat # number of fields assert len(list(form.fields)) is 2
def _form(self, method): def callback1(*a, **k): return 'one' def callback2(*a, **k): return 'two' schema = schemaish.Structure([('string', schemaish.String())]) form = formish.Form(schema, method=method, add_default_action=False) form.add_action('one', 'One', callback1) form.add_action('two', 'Two', callback2) return form
def test_form(self): """Test empty form construction """ schema_empty = schemaish.Structure() name = "Empty Form" form = formish.Form(schema_empty, name) # Schema matches self.assertEqual(form.structure.attr, schema_empty) # Form name matches self.assertEqual(form.name, name) # this is really empty assert list(form.fields) == []
def test_form_error_css(self): schema = schemaish.Structure([ ('a', schemaish.String(validator=v.Required())) ]) form = formish.Form(schema) soup = BeautifulSoup(form()) self.assertTrue('error' not in soup.find('form').get('class').split()) try: form.validate(webob.Request.blank('/', POST={})) except formish.FormError: pass soup = BeautifulSoup(form()) self.assertTrue('error' in soup.find('form').get('class').split())
def test_nested_form_validation_errors(self): schema_nested = schemaish.Structure([ ("one", schemaish.Structure([ ("a", schemaish.String(validator=validatish.Required())), ("b", schemaish.String()), ("c", schemaish.Structure([("x", schemaish.String()), ("y", schemaish.String())])), ])), ]) name = "Nested Form Two" form = formish.Form(schema_nested, name) r = {'one.a': '', 'one.b': '', 'one.c.x': '', 'one.c.y': ''} request = Request(name, r) self.assertRaises(formish.FormError, form.validate, request) # Do we get an error self.assert_(form.errors['one.a'], 'is_required')
def test_complex_form(self): one = schemaish.Structure([ ("a", schemaish.String(validator=v.All(v.Email(), v.Required()))), ("b", schemaish.String()), ("c", schemaish.Sequence(schemaish.Integer())) ]) two = schemaish.Structure([("a", schemaish.String()), ("b", schemaish.Date()),\ ('c', schemaish.Sequence(schemaish.String())), ("d", schemaish.String()), \ ("e", schemaish.Integer(validator=v.Required())), ("f", schemaish.String(validator=v.Required())) ]) schema = schemaish.Structure([("one", one), ("two", two)]) f = formish.Form(schema, name="form", add_default_action=False) f['one.b'].widget = formish.TextArea() f['two.a'].widget = formish.SelectChoice( [('opt1', "Options 1"), ('opt2', "Option 2")], none_option=('-select option-', None)) f['two.b'].widget = formish.DateParts() f['two.c'].widget = formish.CheckboxMultiChoice([('opt1', "Options 1"), ('opt2', "Option 2")]) f['two.d'].widget = formish.RadioChoice([('opt1', "Options 1"), ('opt2', "Option 2")]) f['two.f'].widget = formish.CheckedPassword() f.add_action('submit', "Submit Me") f.defaults = { 'one': { 'a': 'ooteenee', 'c': ['3', '4', '5'] }, 'two': { 'a': 'opt1', 'b': date(1966, 1, 3), 'c': ['opt2'], 'd': 'opt2' } } f()