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'
class InvoiceEntrySchema(schemaish.Structure): id = schemaish.Integer() description = schemaish.String(validator=validator.Required()) currency_code = schemaish.String(validator=validator.Required()) vat = schemaish.Integer(validator=validator.Required()) unit_price = schemaish.Decimal(validator=validator.Required()) units = schemaish.Decimal( validator=validator.All(validator.Required(), validator.Range( min=0.1)))
class InvoiceSchema(schemaish.Structure): customer_contact_id = schemaish.Integer(validator=validator.Required()) project_description = schemaish.String(validator=validator.Required()) date = schemaish.Date(validator=validator.Required()) invoice_number = schemaish.Integer() recurring_term = schemaish.Integer() recurring_stop = schemaish.Date() payment_term = schemaish.Integer(validator=validator.Required()) currency = schemaish.String(validator=validator.Required()) tax = schemaish.Float() payment_date = schemaish.Date() item_list = schemaish.Sequence(invoice_item_schema, validator=validatish.Length(min=1))
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_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 test_sequencesequenceinteger_string_conversion(self): type = schemaish.Sequence(schemaish.Sequence(schemaish.Integer())) value = [[1, 2, 3], [4, 5, 6]] expected = '1,2,3\n4,5,6' actual = string_converter(type).from_type(value) self.assertEquals(actual, expected) value, expected = expected, value actual = string_converter(type).to_type(value) self.assertEquals(actual, expected)
def test_sequencestring_json_conversion(self): type = schemaish.Sequence(schemaish.Integer()) value = [1, 2, 3, 4] expected = value actual = json_converter(type).from_type(value) self.assertEquals(actual, expected) value, expected = expected, value actual = json_converter(type).to_type(value) self.assertEquals(actual, expected)
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_tuple_noneifying(self): schema = schemaish.Tuple([schemaish.Integer(), schemaish.String()]) converter = string_converter(schema) self.assertEquals(converter.from_type((None, None)), ',') self.assertEquals(converter.from_type((None, '')), ',') self.assertEquals(converter.from_type((None, 'foo')), ',foo') self.assertEquals(converter.from_type((1, None)), '1,') self.assertEquals(converter.to_type(','), (None, None)) self.assertEquals(converter.to_type(',foo'), (None, 'foo')) self.assertEquals(converter.to_type('1,'), (1, None))
def test_sequencetupleintegerstring_string_conversion(self): type = schemaish.Sequence( schemaish.Tuple((schemaish.Integer(), schemaish.String()))) value = [(1, '1'), (2, '2')] expected = '1,1\n2,2' actual = string_converter(type).from_type(value) self.assertEquals(actual, expected) value, expected = expected, value actual = string_converter(type).to_type(value) self.assertEquals(actual, expected)
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()
class InvoiceItemSchema(schemaish.Structure): item_id = schemaish.Integer() service_title = schemaish.String(validator=validator.Required()) service_description = schemaish.String(validator=validator.Required()) amount = schemaish.Float(description="Enter the amout") hours = schemaish.Float( description= "Or hours (will be multiplied by your standard or the customers special rate)" ) days = schemaish.Float( description= "Or days (will be multiplied by your standard or the customers special rate)" ) # Additional schema wide validator. validator = ItemAmountValidator()
def test_integer_to_json_conversion(self): type = schemaish.Integer() value_expected = [ (0, 0), (1, 1), (1L, 1), ] for value, expected in value_expected: actual = json_converter(type).from_type(value) self.assertEquals(actual, expected) value_expected = [ (0, 0), (1, 1), (20, 20), ] for value, expected in value_expected: actual = json_converter(type).to_type(value) self.assertEquals(actual, expected)
def test_integer_to_string_conversion(self): type = schemaish.Integer() value_expected = [ (0, '0'), (1, '1'), (1L, '1'), ] for value, expected in value_expected: actual = string_converter(type).from_type(value) self.assertEquals(actual, expected) value_expected = [ ('0', 0), ('1', 1), ('20', 20), ] for value, expected in value_expected: actual = string_converter(type).to_type(value) self.assertEquals(actual, expected)
def test_integer_type(self): schema_flat = schemaish.Structure([("a", schemaish.Integer()), ("b", schemaish.String())]) name = "Integer Form" form = formish.Form(schema_flat, name) r = {'a': '3', 'b': '4'} request = Request(name, r) reqr = {'a': ['3'], 'b': ['4']} # check scmea matches self.assert_(form.structure.attr is schema_flat) # Does the form produce an int and a string self.assertEquals(form.validate(request), {'a': 3, 'b': '4'}) # Does the convert request to data work self.assertEqual(form.widget.from_request_data(form, request.POST), { 'a': 3, 'b': '4' }) # Does the convert data to request work self.assert_( form.widget.to_request_data(form, { 'a': 3, 'b': '4' }) == reqr)
class CompanySchema(schemaish.Structure): name = schemaish.String(validator=validator.Required()) address1 = schemaish.String(validator=validator.Required()) address2 = schemaish.String() address3 = schemaish.String() postal_code = schemaish.String(validator=validator.Required()) city = schemaish.String(validator=validator.Required()) # Todo: provide a vocabulary with countries including country codes: used in combination with # postal code: CH-6004 Luzern country = schemaish.String() e_mail = schemaish.String(validator=validator.Required()) phone = schemaish.String(validator=validator.Required()) logo = schemaish.File(validator=FileMimetypeValidator(['image/jpeg']), description=".jpg / 70mm x 11mm / 300dpi") hourly_rate = schemaish.Float(validator=validator.Required()) daily_rate = schemaish.Float(validator=validator.Required()) tax = schemaish.Float(validator=validator.Required()) vat_number = schemaish.String() iban = schemaish.String() swift = schemaish.String() bank_address = schemaish.String() invoice_start_number = schemaish.Integer() invoice_template = schemaish.String(validator=validator.Required())
class BaseStructure(schemaish.Structure): def __init__(self, context, *args, **kw): self.__context = context super(BaseStructure, self).__init__(*args, **kw) self.title = '' name = schemaish.String(validator=validatish.Required()) name.readonly = True title = schemaish.String() description = schemaish.String() display_order = schemaish.Integer() _widgets = { 'description': { 'widget': formish.TextArea, 'args': [], 'kwargs': { 'cols': 80, 'rows': 5, 'empty': '' }, }, }
"""Dual (not)declarative form and casting definition. * Extensive docs. * Null readme. * NO i18n. * 4,299 SLoC, 11.10/6.24=1.78dev """ import formish, schemaish, validatish my_schema = schemaish.Structure() my_schema.add( 'name', schemaish.String() ) my_schema.add( 'age', schemaish.Integer() ) my_schema == schemaish.Structure("name": schemaish.String(), "age": schemaish.Integer()) class MyStructure(schemaish.Structure): name = schemaish.String() age = schemaish.Integer() my_schema = MyStructure() my_schema == schemaish.Structure("name": schemaish.String(), "age": schemaish.Integer()) form = formish.Form(schema) form() == '\n<form id="form" action="" class="formish-form" method="post" enctype="multipart/form-data" accept-charset="utf-8">\n\n <input type="hidden" name="_charset_" />\n <input type="hidden" name="__formish_form__" value="form" />\n\n<div id="form-name-field" class="field string input">\n\n<label for="form-name">Name</label>\n\n\n<div class="inputs">\n\n<input id="form-name" type="text" name="name" value="" />\n\n</div>\n\n\n\n\n\n</div>\n\n<div id="form-age-field" class="field integer input">\n\n<label for="form-age">Age</label>\n\n\n<div class="inputs">\n\n<input id="form-age" type="text" name="age" value="" />\n\n</div>\n\n\n\n\n\n</div>\n\n\n <div class="actions">\n <input type="submit" id="form-action-submit" name="submit" value="Submit" />\n </div>\n\n</form>\n\n' def is_string(v): """ checks that the value is an instance of basestring """
class InvoiceSchema(schemaish.Structure): payment_term = schemaish.Integer( validator=validator.All(validator.Required(), validator.Range(min=1))) note = schemaish.String() entries = schemaish.Sequence(attr=InvoiceEntrySchema())
class MyStructure(schemaish.Structure): name = schemaish.String() age = schemaish.Integer()
] class EditReportGroupFormController(EditBase): page_title = 'Edit Report Group' schema = report_group_schema class AddReportGroupFormController(AddBase): page_title = 'Add Report Group' schema = report_group_schema factory = PeopleReportGroup section_column_schema = [ ('width', schemaish.Integer()), ] class EditSectionColumnFormController(EditBase): page_title = 'Edit Section Column' schema = section_column_schema class AddSectionColumnFormController(AddBase): page_title = 'Add Section Column' schema = section_column_schema factory = PeopleSectionColumn report_filter_schema = [
from karl.views.api import TemplateAPI from karl.views.forms import widgets marker_field = schemaish.String( title='Marker', description='Customize what flavor of folder this is by choosing one of ' 'the following markers.') keywords_field = schemaish.Sequence( schemaish.String(), title='Search Keywords', description='This document will be shown first for searches for any of ' 'these keywords') weight_field = schemaish.Integer( title='Search Weight', description='Modify the relative importance of this document in search ' 'results.') marker_options = [ ('', 'No Marker'), ('reference_manual', 'Reference Manual'), ('network_events', 'Network Events'), ('network_news', 'Network News'), ] marker_widget = widgets.VerticalRadioChoice( options=marker_options, none_option=None, ) keywords_widget = widgets.SequenceTextAreaWidget(cols=20)
class RootStructure(schemaish.Structure): def __init__(self, context, *args, **kw): self.__context = context super(RootStructure, self).__init__(*args, **kw) name = schemaish.String() title = schemaish.String() description = schemaish.String() site_title = schemaish.String() body = schemaish.String() email = schemaish.String() analytics_code = schemaish.String() verification_code = schemaish.String() copyright_statement = schemaish.String() thumbnail_size = schemaish.Sequence(schemaish.Integer()) _widgets = { 'description': { 'widget': formish.TextArea, 'args': [], 'kwargs': { 'cols': 80, 'rows': 5, 'empty': '' }, }, 'body': { 'widget': formish.TextArea, 'args': [], 'kwargs': { 'cols': 80, 'rows': 15, 'empty': '' }, }, 'analytics_code': { 'widget': formish.TextArea, 'args': [], 'kwargs': { 'cols': 80, 'rows': 5, 'empty': '' }, }, 'verification_code': { 'widget': formish.TextArea, 'args': [], 'kwargs': { 'cols': 80, 'rows': 5, 'empty': '' }, }, 'thumbnail_size': { 'widget': formish.TextArea, 'args': [], 'kwargs': { 'cols': 10, 'rows': 3, 'empty': '' }, }, }