def _schema(self, fields=('id',), formvalidators=()): schema = SchemaValidator() assert set(fields).issubset(set(('id', 'key'))) if 'id' in fields: schema.add('id', IntegerValidator()) if 'key' in fields: schema.add('key', StringValidator()) for formvalidator in formvalidators: schema.add_formvalidator(formvalidator) return schema
def _process_field_validators(self, fields, context): validated_fields = {} exceptions = {} for key, validator in self.fieldvalidators().items(): self._process_field(key, validator, fields, context, validated_fields, exceptions) if len(exceptions) > 0: self._raise_exception(exceptions, context) if (not self.allow_additional_parameters) and (not set(fields).issubset(set(self.fieldvalidators()))): additional_items = set(fields).difference(set(self.fieldvalidators())) additional_arguments = ' '.join(["'%s'" % fields[key] for key in additional_items]) self.error('additional_items', None, context, additional_items=additional_arguments) return validated_fields
def test_existing_keys_are_kept(self): schema = self.schema() extended_schema = SchemaValidator() extended_schema.add('id', StringValidator()) extended_schema.add_missing_validators(schema) self.assert_equals(set(['id']), self.known_fields(schema)) self.assert_isinstance(extended_schema.validator_for('id'), StringValidator)
def test_can_add_additional_validators_to_existing_schema(self): schema = self.schema() extended_schema = SchemaValidator() extended_schema.add('name', StringValidator()) extended_schema.add_missing_validators(schema) self.assert_equals(set(['id', 'name']), self.known_fields(extended_schema)) self.assert_length(1, schema.formvalidators())
def test_can_add_validators_from_schema_in_a_declarative_way(self): class ExtendedSchema(self.schema_class()): name = StringValidator() formvalidators = (StringValidator(), ) extended_schema = ExtendedSchema() self.assert_equals(set(['id', 'name']), self.known_fields(extended_schema)) self.assert_length(2, extended_schema.formvalidators()) self.assert_isinstance(extended_schema.formvalidators()[1], StringValidator)
def _freeze_implementations_for_class(self): class_for_key = {} implementations_for_class = {} known_functions = set() for cls in reversed(inspect.getmro(self.__class__)): if self._class_defines_custom_keys(cls, known_functions): known_functions.add(cls.keys) for key in cls.keys(self): class_for_key[key] = self._implementations_by_key(cls) implementations_for_class[cls] = class_for_key[key] return class_for_key, implementations_for_class
def test_also_can_use_validator_classes(self): self.assert_contains('amount', self.schema().fieldvalidators().keys()) self.assert_equals(set(['id', 'amount']), set(self.schema().fieldvalidators().keys()))
def known_fields(self, schema): return set(schema.fieldvalidators().keys())