Exemplo n.º 1
0
    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'
        })
Exemplo n.º 2
0
 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']))
Exemplo n.º 3
0
 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']))
Exemplo n.º 4
0
    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']
            })
Exemplo n.º 5
0
    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, {})
Exemplo n.º 6
0
def get_form(request):
    schema = Registration()
    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
Exemplo n.º 7
0
def add_view(context, request):

    import formish
    import schemaish
    import schema

    root = context.getRoot()
    kind = request.GET['content']

    new_cls = root.get_model(kind)
    if new_cls is None:
        logging.error("""Can't find registered class for kind '%s'""" %
                      self.kind)
        raise KeyError("""Can't find registered class for kind '%s'""" %
                       self.kind)

    fake_obj = new_cls()
    structure = zope.component.getAdapter(fake_obj, schema.IStructure)
    form = formish.Form(structure, name='form')
    applyWidgets(structure, form, context, request, ignore_readonly=True)

    defaults = schema.load_defaults(fake_obj, structure)
    form.defaults = defaults
    if request.method == 'GET':
        pass
    elif request.method == 'POST':
        try:
            changes = form.validate(request)
            name = changes.pop('name')
            new_obj = root.createContent(name, kind, context, request,
                                         **changes)
            return Redirect(new_obj.absolute_url(request) + 'view')
        except formish.validation.FormError, e:
            pass
Exemplo n.º 8
0
 def test_empty_checker(self):
     form = formish.Form(self._schema(), 'form')
     form['seq'].widget = formish.SequenceDefault()
     # Structure should be in form ...
     self.assertTrue('seq.0.foo' in form())
     # ... but not in data
     self.assertEquals(form.validate(self.Request('form', {})), {'seq': []})
Exemplo n.º 9
0
    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'
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
    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'
Exemplo n.º 12
0
    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'
Exemplo n.º 13
0
    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'
Exemplo n.º 14
0
 def test_min_start_with_data(self):
     form = formish.Form(self._schema(), 'form')
     form['seq'].widget = formish.SequenceDefault()
     form.defaults = {'seq': [{'foo': 'bar'}]}
     html = form()
     self.assertTrue('seq.0.foo' in html)
     self.assertTrue('value="bar"' in html)
     self.assertTrue('seq.1.foo' not in html)
Exemplo n.º 15
0
 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()
Exemplo n.º 16
0
 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()
Exemplo n.º 17
0
 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()
Exemplo n.º 18
0
    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"
Exemplo n.º 19
0
 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())
Exemplo n.º 20
0
 def test_min_start_fields(self):
     for i in range(1, 5):
         form = formish.Form(self._schema(), 'form')
         form['seq'].widget = formish.SequenceDefault(min_start_fields=i)
         html = form()
         for num in range(i):
             self.assertTrue('seq.%d.foo' % num in html)
         self.assertEquals(form.validate(self.Request('form', {})),
                           {'seq': []})
Exemplo n.º 21
0
 def test_thumbnail_sizing(self):
     schema = schemaish.Structure()
     schema.add('foo', schemaish.File())
     basic_form = formish.Form(schema)
     basic_form['foo'].widget = formish.FileUpload(
         image_thumbnail_default='/images/blank.png',
         show_image_thumbnail=True)
     advanced_form = formish.Form(schema)
     advanced_form['foo'].widget = formish.FileUpload(
         thumbnail_size="40x40",
         image_thumbnail_default='/images/blank.png',
         show_image_thumbnail=True)
     html = basic_form()
     assert 'foo' in html
     assert '/images/blank.png?size=20x20' in html
     html = advanced_form()
     assert 'foo' in html
     assert '/images/blank.png?size=40x40' in html
Exemplo n.º 22
0
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
Exemplo n.º 23
0
    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'
Exemplo n.º 24
0
    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})
Exemplo n.º 25
0
 def test_first_entry(self):
     form = formish.Form(self._schema(), 'form')
     form['seq'].widget = formish.SequenceDefault(min_start_fields=2)
     self.assertEquals(
         form.validate(
             self.Request('form', [('seq.0.foo', 'bar'),
                                   ('seq.1.foo', '')])),
         {'seq': [{
             'foo': 'bar'
         }]})
Exemplo n.º 26
0
 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
Exemplo n.º 27
0
 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())
Exemplo n.º 28
0
 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()
Exemplo n.º 29
0
    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
Exemplo n.º 30
0
    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) == []