def test_ctor_wo_title_w_description(self): from zope.schema._compat import u field = self._makeOne(description=u('DESC')) self.assertEqual(field.__name__, u('')) self.assertEqual(field.__doc__, u('DESC')) self.assertEqual(field.title, u('')) self.assertEqual(field.description, u('DESC'))
def test_filtered_handler(self): from zope.schema import Text from zope.schema._compat import u field = Text( __name__='testing', description=u('DESCRIPTION'), default=u('DEFAULT'), required=True, ) prop = self._makeOne(field=field) class IFoo(interface.Interface): """ """ class Foo(object): interface.implements(IFoo) testing = prop foo = Foo() logs = [] @component.adapter(IFoo, schema.Text, schema.interfaces.IFieldUpdatedEvent) def add_field_events(obj, field, event): logs.append((obj, field, event)) component.provideHandler(add_field_events) self.assertEqual(len(logs), 0) foo.testing = u'Bla' self.assertEqual(len(logs), 1) event_inst, event_field, event = logs[0] self.assertEqual(event_inst, foo) self.assertEqual(event_field, field)
def test_validate_not_required(self): from zope.schema._compat import u field = self._makeOne(required=False) field.validate(u('')) field.validate(u('abc')) field.validate(u('abc\ndef')) field.validate(None)
def test_field_event(self): # fieldproperties are everywhere including in field themselfs # so event are triggered from zope.schema import Text from zope.schema._compat import u from zope.event import subscribers from zope.schema.fieldproperty import FieldUpdatedEvent log = [] subscribers.append(log.append) self.assertEqual(log, []) field = Text( __name__='testing', description=u('DESCRIPTION'), default=u('DEFAULT'), readonly=True, required=True, ) self.assertEqual(len(log), 6) # these are fieldproperties in the field self.assertEqual( [ev.field.__name__ for ev in log], ['min_length', 'max_length', 'title', 'description', 'required', 'readonly']) event = log[0] self.assertTrue(isinstance(event, FieldUpdatedEvent)) self.assertEqual(event.inst, field) self.assertEqual(event.old_value, 0) self.assertEqual(event.new_value, 0)
def test_validate_required(self): from zope.schema.interfaces import RequiredMissing from zope.schema._compat import u field = self._makeOne() field.validate(u('')) field.validate(u('abc')) self.assertRaises(RequiredMissing, field.validate, None)
def test_subscriber(self): from zope.schema import Text from zope.schema._compat import u field = Text( __name__='testing', description=u('DESCRIPTION'), default=u('DEFAULT'), required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() logs = [] @component.adapter(schema.interfaces.IFieldUpdatedEvent) def add_field_event(event): logs.append(event) component.provideHandler(add_field_event) self.assertEqual(len(logs), 0) foo.testing = u'Bla' self.assertEqual(len(logs), 1) event = logs[0] self.assertEqual(event.field, field) self.assertEqual(event.inst, foo)
def test_fromUnicode_miss(self): from zope.schema._compat import u txt = self._makeOne() self.assertEqual(txt.fromUnicode(u('')), False) self.assertEqual(txt.fromUnicode(u('0')), False) self.assertEqual(txt.fromUnicode(u('1')), False) self.assertEqual(txt.fromUnicode(u('False')), False) self.assertEqual(txt.fromUnicode(u('false')), False)
def __init__(self, title=u(''), description=u(''), __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=__missing_value_marker): """Pass in field values as keyword parameters. Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument. Here are some examples: >>> from zope.schema._compat import u >>> f = Field() >>> f.__doc__, f.title, f.description ('', u'', u'') >>> f = Field(title=u('sample')) >>> f.__doc__, f.title, f.description (u'sample', u'sample', u'') >>> f = Field(title=u('sample'), description=u('blah blah\\nblah')) >>> f.__doc__, f.title, f.description (u'sample\\n\\nblah blah\\nblah', u'sample', u'blah blah\\nblah') """ __doc__ = '' if title: if description: __doc__ = "%s\n\n%s" % (title, description) else: __doc__ = title elif description: __doc__ = description super(Field, self).__init__(__name__, __doc__) self.title = title self.description = description self.required = required self.readonly = readonly if constraint is not None: self.constraint = constraint self.default = default self.defaultFactory = defaultFactory # Keep track of the order of field definitions Field.order += 1 self.order = Field.order if missing_value is not self.__missing_value_marker: self.missing_value = missing_value
def __init__(self, title=u(''), description=u(''), __name__='', required=True, readonly=False, constraint=None, default=None, defaultFactory=None, missing_value=__missing_value_marker): """Pass in field values as keyword parameters. Generally, you want to pass either a title and description, or a doc string. If you pass no doc string, it will be computed from the title and description. If you pass a doc string that follows the Python coding style (title line separated from the body by a blank line), the title and description will be computed from the doc string. Unfortunately, the doc string must be passed as a positional argument. Here are some examples: >>> f = Field() >>> f.__doc__, f.title, f.description ('', u'', u'') >>> f = Field(title=u('sample')) >>> f.__doc__, f.title, f.description (u'sample', u'sample', u'') >>> f = Field(title=u('sample'), description=u('blah blah\\nblah')) >>> f.__doc__, f.title, f.description (u'sample\\n\\nblah blah\\nblah', u'sample', u'blah blah\\nblah') """ __doc__ = '' if title: if description: __doc__ = "%s\n\n%s" % (title, description) else: __doc__ = title elif description: __doc__ = description super(Field, self).__init__(__name__, __doc__) self.title = title self.description = description self.required = required self.readonly = readonly if constraint is not None: self.constraint = constraint self.default = default self.defaultFactory = defaultFactory # Keep track of the order of field definitions Field.order += 1 self.order = Field.order if missing_value is not self.__missing_value_marker: self.missing_value = missing_value
class IRSSTileData(IPersistentCoverTile): feeds = List( title=u("Feeds"), unique=True, value_type=URI(title=u('URL')), ) items_to_show = Int(title=u("Number of items to show"), ) max_per_feed = Int(title=u("Maximum number of items from a given feed"), ) blacklist = List( title=u("Blacklisted words"), unique=True, value_type=ASCII(title=u('Word')), required=False, missing_value=[], ) whitelist = List( title=u("Whitelisted words"), unique=True, value_type=ASCII(title=u('Word')), required=False, missing_value=[], )
def test_ctor_defaults(self): from zope.schema._compat import u field = self._makeOne() self.assertEqual(field.__name__, u('')) self.assertEqual(field.__doc__, u('')) self.assertEqual(field.title, u('')) self.assertEqual(field.description, u('')) self.assertEqual(field.required, True) self.assertEqual(field.readonly, False) self.assertEqual(field.constraint(object()), True) self.assertEqual(field.default, None) self.assertEqual(field.defaultFactory, None) self.assertEqual(field.missing_value, None) self.assertEqual(field.context, None)
def test_w_read_and_write_accessors(self): from zope.interface import Interface from zope.schema import Text from zope.schema._compat import u field = Text(title=u('Hmm')) class IFoo(Interface): getter, setter = self._callFUT(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.getSignatureString(), '()') info = getter.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) setter = IFoo['setter'] self.assertEqual(setter.__name__, 'setter') self.assertEqual(setter.getSignatureString(), '(newvalue)') info = setter.getSignatureInfo() self.assertEqual(info['positional'], ('newvalue', )) self.assertEqual(info['required'], ('newvalue', )) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None)
def test_w_read_and_write_accessors(self): from zope.interface import Interface from zope.schema import Text from zope.schema._compat import u field = Text(title=u('Hmm')) class IFoo(Interface): getter, setter = self._callFUT(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.getSignatureString(), '()') info = getter.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) setter = IFoo['setter'] self.assertEqual(setter.__name__, 'setter') self.assertEqual(setter.getSignatureString(), '(newvalue)') info = setter.getSignatureInfo() self.assertEqual(info['positional'], ('newvalue',)) self.assertEqual(info['required'], ('newvalue',)) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None)
def test_ctor_explicit(self): from zope.schema import Text from zope.schema._compat import u field = Text(__name__='testing', description=u('DESCRIPTION'), default=u('DEFAULT'), readonly=True, required=True, ) cname = self._getTargetClass().__name__ prop = self._makeOne(field, name='override') self.assertTrue(getattr(prop, '_%s__field' % cname) is field) self.assertEqual(getattr(prop, '_%s__name' % cname), 'override') self.assertEqual(prop.description, field.description) self.assertEqual(prop.default, field.default) self.assertEqual(prop.readonly, field.readonly) self.assertEqual(prop.required, field.required)
def test_ctor_not_created_inside_interface(self): from zope.schema import Text from zope.schema._compat import u field = Text(title=u('Hmm')) wrapped = self._makeOne(field) self.assertTrue(wrapped.field is field) self.assertEqual(wrapped.__name__, '') # __name__ set when in iface self.assertEqual(wrapped.__doc__, 'get Hmm')
def test_ctor_not_created_inside_interface(self): from zope.schema import Text from zope.schema._compat import u field = Text(title=u('Hmm')) wrapped = self._makeOne(field) self.assertTrue(wrapped.field is field) self.assertEqual(wrapped.__name__, '') #__name__ set when in interface self.assertEqual(wrapped.__doc__, 'get Hmm')
def test_ctor_w_both_title_and_description(self): from zope.schema._compat import u field = self._makeOne(u('TITLE'), u('DESC'), u('NAME')) self.assertEqual(field.__name__, u('NAME')) self.assertEqual(field.__doc__, u('TITLE\n\nDESC')) self.assertEqual(field.title, u('TITLE')) self.assertEqual(field.description, u('DESC'))
def test_ctor_created_inside_interface(self): from zope.interface import Interface from zope.schema import Text from zope.schema._compat import u field = Text(title=u('Hmm')) class IFoo(Interface): getter = self._makeOne(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.__doc__, 'get Hmm')
def test_query_value_with_default(self): from zope.schema import Text from zope.schema._compat import u field = Text( __name__='testing', description=u('DESCRIPTION'), default=u('DEFAULT'), readonly=True, required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() self.assertEqual(prop.queryValue(foo, 'test'), u('DEFAULT')) foo.testing = u('NO') self.assertEqual(prop.queryValue(foo, 'test'), u('NO'))
def test_field_event_update(self): from zope.schema import Text from zope.schema._compat import u from zope.event import subscribers from zope.schema.fieldproperty import FieldUpdatedEvent field = Text( __name__='testing', description=u('DESCRIPTION'), default=u('DEFAULT'), required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() log = [] subscribers.append(log.append) foo.testing = u('Bar') foo.testing = u('Foo') self.assertEqual(len(log), 2) event = log[1] self.assertTrue(isinstance(event, FieldUpdatedEvent)) self.assertEqual(event.inst, foo) self.assertEqual(event.field, field) self.assertEqual(event.old_value, u('Bar')) self.assertEqual(event.new_value, u('Foo'))
def __init__(self, variable_name=None, **kw): self.variable_name = variable_name if not variable_name: self.variable_name = '$' + self.__name__ if 'title' not in kw: kw['title'] = u(self.variable_name) if 'required' not in kw: kw['required'] = False super(Variable, self).__init__(**kw)
def __init__(self, variable_name=None, **kw): self.variable_name = variable_name if not variable_name: self.variable_name = "$" + self.__name__ if "title" not in kw: kw["title"] = u(self.variable_name) if "required" not in kw: kw["required"] = False super(Variable, self).__init__(**kw)
def test_basic(self): from zope.schema._compat import b from zope.schema._compat import u from zope.schema.interfaces import ValidationError c = self._makeImplementer() self.assertEqual(c.title, u('say something')) self.assertEqual(c.weight, None) self.assertEqual(c.code, b('xxxxxx')) self.assertRaises(ValidationError, setattr, c, 'title', b('foo')) self.assertRaises(ValidationError, setattr, c, 'weight', b('foo')) self.assertRaises(ValidationError, setattr, c, 'weight', -1.0) self.assertRaises(ValidationError, setattr, c, 'weight', 2) self.assertRaises(ValidationError, setattr, c, 'code', -1) self.assertRaises(ValidationError, setattr, c, 'code', b('xxxx')) self.assertRaises(ValidationError, setattr, c, 'code', u('xxxxxx')) c.title = u('c is good') c.weight = 10.0 c.code = b('abcdef') self.assertEqual(c.title, u('c is good')) self.assertEqual(c.weight, 10) self.assertEqual(c.code, b('abcdef'))
def test_non_fields(self): from zope.schema._compat import b from zope.schema._compat import u self.assertEqual(self._callFUT(None), False) self.assertEqual(self._callFUT(0), False) self.assertEqual(self._callFUT(0.0), False) self.assertEqual(self._callFUT(True), False) self.assertEqual(self._callFUT(b('')), False) self.assertEqual(self._callFUT(u('')), False) self.assertEqual(self._callFUT(()), False) self.assertEqual(self._callFUT([]), False) self.assertEqual(self._callFUT({}), False) self.assertEqual(self._callFUT(set()), False) self.assertEqual(self._callFUT(frozenset()), False) self.assertEqual(self._callFUT(object()), False)
def test_w_only_read_accessor(self): from zope.interface import Interface from zope.schema import Text from zope.schema._compat import u field = Text(title=u('Hmm'), readonly=True) class IFoo(Interface): getter, = self._callFUT(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.__doc__, 'get Hmm') self.assertEqual(getter.getSignatureString(), '()') info = getter.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None)
def test_query_value_without_default(self): from zope.schema import Text from zope.schema._compat import u field = Text( __name__='testing', description=u('DESCRIPTION'), readonly=True, required=True, ) prop = self._makeOne(field=field) class Foo(object): testing = prop foo = Foo() # field initialize its default to None if it hasn't any default # it should be zope.schema.NO_VALUE as 'None' has another semantic self.assertEqual(prop.queryValue(foo, 'test'), None)
class ISchemaTest(Interface): title = Bytes(title=u("Title"), description=u("Title"), default=b(""), required=True) description = Bytes(title=u("Description"), description=u("Description"), default=b(""), required=True) spam = Bytes(title=u("Spam"), description=u("Spam"), default=b(""), required=True)
class IBirthInfo(Interface): state1 = Choice( title=u('State of Birth'), description=u('The state in which you were born.'), vocabulary="states", default="AL", ) state2 = Choice( title=u('State of Birth'), description=u('The state in which you were born.'), vocabulary="states", default="AL", ) state3 = Choice( title=u('Favorite State'), description=u('The state you like the most.'), vocabulary=StateVocabulary(), ) state4 = Choice( title=u("Name"), description=u("The name of your new state"), vocabulary="states", )
def test_fromUnicode_hit(self): from zope.schema._compat import u txt = self._makeOne() self.assertEqual(txt.fromUnicode(u('True')), True) self.assertEqual(txt.fromUnicode(u('true')), True)
def test_fromUnicode_hit(self): from zope.schema._compat import u txt = self._makeOne() self.assertEqual(txt.fromUnicode(u('0')), 0) self.assertEqual(txt.fromUnicode(u('1')), 1) self.assertEqual(txt.fromUnicode(u('-1')), -1)
def test_fromUnicode_miss(self): from zope.schema._compat import u txt = self._makeOne() self.assertRaises(ValueError, txt.fromUnicode, u('')) self.assertRaises(ValueError, txt.fromUnicode, u('False')) self.assertRaises(ValueError, txt.fromUnicode, u('True'))
def test_constraint(self): from zope.schema._compat import u field = self._makeOne() self.assertEqual(field.constraint(u('')), True) self.assertEqual(field.constraint(u('abc')), True) self.assertEqual(field.constraint(u('abc\ndef')), False)
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Sample vocabulary supporting state abbreviations. """ from zope.schema._compat import u from zope.interface import implementer from zope.schema import interfaces from zope.schema import Choice # This table is based on information from the United States Postal Service: # http://www.usps.com/ncsc/lookups/abbreviations.html#states _states = { 'AL': u('Alabama'), 'AK': u('Alaska'), 'AS': u('American Samoa'), 'AZ': u('Arizona'), 'AR': u('Arkansas'), 'CA': u('California'), 'CO': u('Colorado'), 'CT': u('Connecticut'), 'DE': u('Delaware'), 'DC': u('District of Columbia'), 'FM': u('Federated States of Micronesia'), 'FL': u('Florida'), 'GA': u('Georgia'), 'GU': u('Guam'), 'HI': u('Hawaii'), 'ID': u('Idaho'),
class Obj(object): foo = u('Foo') bar = u('Bar')
def test_fromUnicode_hit(self): from zope.schema._compat import u deadbeef = u('DEADBEEF') txt = self._makeOne() self.assertEqual(txt.fromUnicode(deadbeef), deadbeef)
class ISchemaTestSubclass(base): foo = Bytes( title=u('Foo'), description=u('Fooness'), default=b(""), required=False)
def __init__(self, snippet=u'', name=None, parent=None): self.data = u(snippet) # PY2 will convert into unicode #zope.location.ILocation self.__name__ = name self.__parent__ = parent
class IField(Interface): """Basic Schema Field Interface. Fields are used for Interface specifications. They at least provide a title, description and a default value. You can also specify if they are required and/or readonly. The Field Interface is also used for validation and specifying constraints. We want to make it possible for a IField to not only work on its value but also on the object this value is bound to. This enables a Field implementation to perform validation against an object which also marks a certain place. Note that many fields need information about the object containing a field. For example, when validating a value to be set as an object attribute, it may be necessary for the field to introspect the object's state. This means that the field needs to have access to the object when performing validation:: bound = field.bind(object) bound.validate(value) """ def bind(object): """Return a copy of this field which is bound to context. The copy of the Field will have the 'context' attribute set to 'object'. This way a Field can implement more complex checks involving the object's location/environment. Many fields don't need to be bound. Only fields that condition validation or properties on an object containing the field need to be bound. """ title = TextLine( title=_("Title"), description=_("A short summary or label"), default=u(""), required=False, ) description = Text( title=_("Description"), description=_("A description of the field"), default=u(""), required=False, ) required = Bool( title=_("Required"), description=(_("Tells whether a field requires its value to exist.")), default=True) readonly = Bool( title=_("Read Only"), description=_("If true, the field's value cannot be changed."), required=False, default=False) default = Field( title=_("Default Value"), description=_("""The field default value may be None or a legal field value""")) missing_value = Field( title=_("Missing Value"), description=_("""If input for this Field is missing, and that's ok, then this is the value to use""")) order = Int( title=_("Field Order"), description=_(""" The order attribute can be used to determine the order in which fields in a schema were defined. If one field is created after another (in the same thread), its order will be greater. (Fields in separate threads could have the same order.) """), required=True, readonly=True, ) def constraint(value): """Check a customized constraint on the value. You can implement this method with your Field to require a certain constraint. This relaxes the need to inherit/subclass a Field you to add a simple constraint. Returns true if the given value is within the Field's constraint. """ def validate(value): """Validate that the given value is a valid field value. Returns nothing but raises an error if the value is invalid. It checks everything specific to a Field and also checks with the additional constraint. """ def get(object): """Get the value of the field for the given object.""" def query(object, default=None): """Query the value of the field for the given object. Return the default if the value hasn't been set. """ def set(object, value): """Set the value of the field for the object