Back to index

plone3  3.1.7
test_fieldvalidation.py
Go to the documentation of this file.
00001 ################################################################################
00002 #
00003 # Copyright (c) 2002-2005, Benjamin Saller <bcsaller@ideasuite.com>, and
00004 #                              the respective authors. All rights reserved.
00005 # For a list of Archetypes contributors see docs/CREDITS.txt.
00006 #
00007 # Redistribution and use in source and binary forms, with or without
00008 # modification, are permitted provided that the following conditions are met:
00009 #
00010 # * Redistributions of source code must retain the above copyright notice, this
00011 #   list of conditions and the following disclaimer.
00012 # * Redistributions in binary form must reproduce the above copyright notice,
00013 #   this list of conditions and the following disclaimer in the documentation
00014 #   and/or other materials provided with the distribution.
00015 # * Neither the name of the author nor the names of its contributors may be used
00016 #   to endorse or promote products derived from this software without specific
00017 #   prior written permission.
00018 #
00019 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
00020 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00021 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
00022 # FOR A PARTICULAR PURPOSE.
00023 #
00024 ################################################################################
00025 
00026 from Products.Archetypes.tests.attestcase import ATTestCase
00027 
00028 from Acquisition import Explicit
00029 
00030 from Products.Archetypes.atapi import *
00031 from Products.Archetypes.config import *
00032 from Products.Archetypes.BaseObject import BaseObject
00033 from Products.validation import validation as validationService
00034 from Products.validation.interfaces.IValidator import IValidator
00035 
00036 class MyValidator:
00037     __implements__ = (IValidator,)
00038 
00039     def __init__(self, name, fun):
00040         self.name = name
00041         self.fun = fun
00042 
00043     def __call__(self, value, instance, field, *args, **kwargs):
00044         return self.fun(value)
00045 
00046 # never validates
00047 validationService.register(MyValidator('v1', lambda val:val))
00048 # always validates
00049 validationService.register(MyValidator('v2', lambda val:1))
00050 # never validates
00051 validationService.register(MyValidator('v3', lambda val:[]))
00052 
00053 settings = [
00054     {'field': {}, # this is the dict of field properties
00055      'value': None,
00056      'assertion': lambda result:result is None, # result of field.validate()
00057      },
00058 
00059     {'field': {'required': 1}, # required
00060      'value': None,            # ... but no value given
00061      'assertion': lambda result:result is not None},
00062 
00063     ]
00064 
00065 for req in 0,1: # 0 == not required, 1 == required
00066 
00067     for validator in (('v2', 'v1'), ('v1',)):
00068         # Make sure that for both sets of validators, v1 returns an error.
00069         settings.append(
00070             {'field': {'required': req, 'validators': validator},
00071              'value': 'bass',
00072              'assertion': lambda result:result.find('bass') > -1}
00073             )
00074 
00075     # the trombone is in the vocabulary
00076     settings.append(
00077         {'field': {'required': req, 'enforceVocabulary': 1,
00078                    'vocabulary': ('frenchhorn', 'trombone', 'trumpet')},
00079          'value': 'trombone',
00080          'assertion': lambda result:result is None}
00081         )
00082 
00083     # tuba is not in vocabulary, so this must fail
00084     settings.append(
00085         {'field': {'required': req, 'enforceVocabulary': 1,
00086                    'vocabulary': ('frenchhorn', 'trombone', 'trumpet')},
00087          'value': 'tuba',
00088          'assertion': lambda result:result is not None}
00089         )
00090 
00091     # tuba is not in vocabulary, so this must fail
00092     settings.append(
00093         {'field': {'required': req, 'enforceVocabulary': 1,
00094                    'multiValued': 1,
00095                    'vocabulary': ('frenchhorn', 'trombone', 'trumpet')},
00096          'value': ('tuba', 'trombone'),
00097          'assertion': lambda result:result is not None}
00098         )
00099 
00100     # enforceVocabulary, but no vocabulary given
00101     settings.append(
00102         {'field': {'required': req, 'enforceVocabulary': 1},
00103          'value': 'cello',
00104          'assertion': lambda result:result is not None}
00105         )
00106 
00107 
00108 class FakeType(Explicit, BaseObject):
00109     def unicodeEncode(self, v): return v # don't
00110 
00111 
00112 class TestSettings(ATTestCase):
00113 
00114     def afterSetUp(self):
00115         instance = FakeType('fake')
00116         self.instance = instance.__of__(self.folder)
00117 
00118     def testSettings(self):
00119         # tests every setting in global "settings"
00120         for setting in settings:
00121             field = Field('orchestra', **setting['field'])
00122             result = field.validate(setting['value'], self.instance, errors={})
00123             msg = 'Assertion failed for setting:\n%s.\nResult was "%s".' % \
00124                   (setting, result)
00125 
00126             self.assert_(setting['assertion'](result),
00127                          setting.get('failmsg', msg))
00128 
00129 
00130 class TestValidation(ATTestCase):
00131 
00132     def afterSetUp(self):
00133         self.instance = FakeType('fake')
00134 
00135     def testIntegerZeroInvalid(self):
00136         # attach a validator that never validates, so any value must fail
00137         field = IntegerField('integer', validators=('v3',))
00138 
00139         self.assert_(field.validate(1, self.instance, errors={}) is not None)
00140         self.assert_(field.validate(0, self.instance, errors={}) is not None)
00141 
00142 
00143 def test_suite():
00144     from unittest import TestSuite, makeSuite
00145     suite = TestSuite()
00146     suite.addTest(makeSuite(TestSettings))
00147     suite.addTest(makeSuite(TestValidation))
00148     return suite