def testInvalidIPAddresses(self): result = validate_instance( self.Test(ip='1.1.1.1.1') ) self.assertNotEqual(result.tag, 'OK') result = validate_instance( self.Test(ip='1.1.11') ) self.assertNotEqual(result.tag, 'OK') result = validate_instance( self.Test(ip='1.1.1111.1') ) self.assertNotEqual(result.tag, 'OK')
def store(self, db, validate=True): """Store the document in the given database.""" if validate: validate_instance(self) id, rev = db.save(to_dict(self)) self._id = id self._rev = rev return self
def test_path_isfile(self): class Foo(Model): path = PathType(isfile=True) foo = Foo(path="/etc/hosts") validate_instance(foo) foo.path = "/tmp" with self.assertRaises(TypeException): validate_instance(foo)
def test_path__can_create_or_write(self): class Foo(Model): path = PathType(can_create_or_write=True) foo = Foo(path="/tmp/file_that_doesnt_exist_but_can_be_created") validate_instance(foo) foo.path = "/tmp/dir_that_doesnt_exist/file_that_doesnt_exist" with self.assertRaises(TypeException): validate_instance(foo)
def test_path(self): class Foo(Model): path = ExecutablePathType() foo = Foo(path="/bin/sh") validate_instance(foo) foo.path = "/bin/file_that_doesnt_exist" with self.assertRaises(TypeException): validate_instance(foo)
def test_path_exists(self): class Foo(Model): path = PathType(exists=True) foo = Foo(path="/tmp") validate_instance(foo) foo.path = "/tmp/this_file_doesnt_exist_with_some_random_digits_13467487681356573" result = validate_instance(foo) self.assertNotEqual(result.tag, 'OK')
def test_path_exists(self): class Foo(Model): path = PathType(exists=True) foo = Foo(path="/tmp") validate_instance(foo) foo.path = "/tmp/this_file_doesnt_exist_with_some_random_digits_13467487681356573" with self.assertRaises(TypeException): validate_instance(foo)
def test_path_isfile(self): class Foo(Model): path = PathType(isfile=True) foo = Foo(path="/etc/hosts") validate_instance(foo) foo.path = "/tmp" result = validate_instance(foo) self.assertNotEqual(result.tag, 'OK')
def validate(self, value): """Make sure that the model instance is an instance of the Model subclass provided when the model was defined. """ # Using isinstance also works for subclasses of self.model if not isinstance(value, self.model_type): raise TypeException( 'Invalid modeltype instance ' 'provided to an ModelType', self.field_name, value) validate_instance(value) return value
def validate(model, doc): '''Validate all fields. Return any/all failed validation along with details''' errors = [] try: validate_instance(model(**doc)) # model(**doc).validate(validate_all=True) except ModelException, errs: for err in errs.error_list: errors.append(err.__dict__)
def test_path(self): class Foo(Model): path = ExecutablePathType() foo = Foo(path="/bin/sh") result = validate_instance(foo) self.assertEqual(result.tag, 'OK') foo.path = "/bin/file_that_doesnt_exist" result = validate_instance(foo) self.assertNotEqual(result.tag, 'OK')
def test_path__can_create_or_write(self): class Foo(Model): path = PathType(can_create_or_write=True) foo = Foo(path="/tmp/file_that_doesnt_exist_but_can_be_created") result = validate_instance(foo) self.assertEqual(result.tag, 'OK') foo.path = "/tmp/dir_that_doesnt_exist/file_that_doesnt_exist" result = validate_instance(foo) self.assertNotEqual(result.tag, 'OK')
def validate(self, value): """Make sure that the model instance is an instance of the Model subclass provided when the model was defined. """ # Using isinstance also works for subclasses of self.model if not isinstance(value, self.model_type): raise TypeException('Invalid modeltype instance ' 'provided to an ModelType', self.field_name, value) validate_instance(value) return value
def test_validation_converts_value(self): self.testmodel.the_list = ["2","2","2","2","2","2"] result = validate_instance(self.testmodel) self.assertEqual(result.tag, 'OK') converted_data = result.value new_list = converted_data['the_list'] self.assertEqual(new_list, [2,2,2,2,2,2])
def validate(self, value): """Make sure that the model instance is an instance of the Model subclass provided when the model was defined. """ # Using isinstance also works for subclasses of self.model if not isinstance(value, self.model_type): error_msg = 'Invalid modeltype instance provided to an ModelType' return FieldResult(ERROR_FIELD_TYPE_CHECK, error_msg, self.field_name, value) return validate_instance(value)
def __set__(self, instance, value_list): """Descriptor for assigning a value to a type in a model. """ new_value = value_list is_model = lambda tipe: isinstance(tipe, ModelType) model_fields = filter(is_model, self.fields) if self.primary_embedded: model_fields.remove(self.primary_embedded) model_fields.insert(0, self.primary_embedded) if value_list is None: value_list = [] # have to use a list errors_found = False if model_fields: new_data = list() for datum in value_list: datum_instance = None is_dict = False ### Extract field names from datum datum_fields = None if isinstance(datum, dict): datum_fields = datum.keys() else: datum_fields = datum._fields.keys() ### Determine matching model for model_field in model_fields: test_keys = model_field.model_type_obj._fields.keys() if len(set(datum_fields) - set(test_keys)) == 0: if datum is None: datum = {} elif not isinstance(datum, dict): datum = datum._data datum_instance = model_field.model_type_obj(**datum) ### Validate model result = validate_instance(datum_instance) if result.tag == OK: new_data.append(datum_instance) else: errors_found = True new_value = new_data if not errors_found: instance._data[self.field_name] = new_value
def __set__(self, instance, value): """Descriptor for assigning a value to a type in a model. """ is_model = lambda tipe: isinstance(tipe, ModelType) model_fields = filter(is_model, self.fields) if self.primary_embedded: model_fields.remove(self.primary_embedded) model_fields.insert(0, self.primary_embedded) if value is None: value = [] # have to use a list if model_fields: list_of_models = list() for model in value: if isinstance(model, dict): for model_field in model_fields: model_obj = model_field.model_type_obj(**model) model = model_obj validate_instance(model) list_of_models.append(model) value = list_of_models instance._data[self.field_name] = value
def __set__(self, instance, value_list): """Descriptor for assigning a value to a type in a model. """ new_value = value_list is_model = lambda tipe: isinstance(tipe, ModelType) model_fields = filter(is_model, self.fields) if self.primary_embedded: model_fields.remove(self.primary_embedded) model_fields.insert(0, self.primary_embedded) if value_list is None: value_list = [] # have to use a list errors_found = False if model_fields: new_data = list() for datum in value_list: datum_instance = datum is_dict = False ### if `datum` is dict, attempt conversion if isinstance(datum, dict): is_dict = True ### Find a model that matches for model_field in model_fields: ### TODO Validate SMARTER datum_instance = model_field.model_type_obj(**datum) #import pdb; pdb.set_trace() result = validate_instance(datum_instance) if result.tag == OK: ### Remove double instantiation for model_field in model_fields: ### TODO Validate SMARTER datum_instance = model_field.model_type_obj(**result.value) #new_data.append(datum_instance) new_data.append(datum_instance) else: errors_found = True new_value = new_data if not errors_found: instance._data[self.field_name] = new_value
self.secret = hash_string ### ### Manually create an instance ### ### Create instance with bogus password u = User() u.secret = 'whatevz' u.name = 'test hash' ### Validation will fail because u.secret does not contain an MD5 hash print 'Attempting validation on:\n\n %s\n' % (to_json(u)) try: validate_instance(u) print 'Validation passed\n' except TypeException, se: print 'TypeException caught: %s\n' % (se) ### Set the password *correctly* using our `set_password` function u.set_password('whatevz') print 'Adjusted invalid data and trying again on:\n\n %s\n' % (to_json(u)) try: validate_instance(u) print 'Validation passed\n' except TypeException, se: print 'TypeException caught: %s (This section wont actually run)\n' % (se)
print ' OK: %s\n' % (result.value) else: print ' ERRORS: %s' % (result.message) for err in result.value: print ' -', err print '' ### Create instance with bogus password u = User() u.secret = 'whatevz' u.name = 'this name is going to be much, much, much too long for this field' ### Validation will fail print 'VALIDATING: %s' % (to_python(u)) result = validate_instance(u) ### Set the password *correctly* and validation will pass u.name = 'J2D2' u.set_password('whatevz') print 'VALIDATING: %s' % (to_python(u)) ### Validation will pass result = validate_instance(u) print_result(result) ### ### Instantiate an instance from a dict ###
def test_validation_fails(self): result = validate_instance(self.doc_simple_invalid) self.assertNotEqual(result.tag, 'OK') self.assertEqual(len(result.value), 1) self.assertEqual(result.value[0].tag, ERROR_FIELD_REQUIRED)
self.secret = hash_string ### ### Manually create an instance ### ### Create instance with bogus password u = User() u.secret = 'whatevz' u.name = 'test hash' ### Validation will fail because u.secret does not contain an MD5 hash print 'Attempting validation on:\n\n %s\n' % (to_json(u)) try: validate_instance(u) print 'Validation passed\n' except TypeException, se: print 'TypeException caught: %s\n' % (se) ### Set the password *correctly* using our `set_password` function u.set_password('whatevz') print 'Adjusted invalid data and trying again on:\n\n %s\n' % (to_json(u)) try: validate_instance(u) print 'Validation passed\n' except TypeException, se: print 'TypeException caught: %s (This section wont actually run)\n' % (se) ### ### Instantiate an instance with this data
def test_required_validates(self): result = validate_instance(self.doc_simple_valid) self.assertEqual(result.tag, 'OK')
def validate(self): return validate_instance(self)
def test_validation_failes_with_embedded(self): result = validate_instance(self.doc_embedded_invalid) self.assertNotEqual(result.tag, 'OK')
def test_validation_fails(self): result = validate_instance(self.doc_simple_invalid) self.assertNotEqual(result.tag, 'OK')
def test_choices_validates_with_embedded(self): result = validate_instance(self.doc_embedded_valid) self.assertEqual(result.tag, 'OK')
def update(self, documents, validate=True, **options): """Perform a bulk update or insertion of the given documents using a single HTTP request. >>> server = Server() >>> db = server.create('python-tests') >>> for doc in db.update([ ... Document(type='Person', name='John Doe'), ... Document(type='Person', name='Mary Jane'), ... Document(type='City', name='Gotham City') ... ],validate=False): ... print repr(doc) #doctest: +ELLIPSIS (True, u'...', u'...') (True, u'...', u'...') (True, u'...', u'...') >>> del server['python-tests'] The return value of this method is a list containing a tuple for every element in the `documents` sequence. Each tuple is of the form ``(success, docid, rev_or_exc)``, where ``success`` is a boolean indicating whether the update succeeded, ``docid`` is the ID of the document, and ``rev_or_exc`` is either the new document revision, or an exception instance (e.g. `ResourceConflict`) if the update failed. If an object in the documents list is not a dictionary, this method looks for an ``items()`` method that can be used to convert the object to a dictionary. Effectively this means you can also use this method with `mapping.Document` objects. :param documents: a sequence of dictionaries or `Document` objects, or objects providing a ``items()`` method that can be used to convert them to a dictionary :return: an iterable over the resulting documents :rtype: ``list`` :since: version 0.2 """ docs = [] for doc in documents: if isinstance(doc, Document): if validate: results = validate_instance(doc) if results.tag == 'OK': docs.append(doc) else: docs.append(doc) elif isinstance(doc, dict): docs.append(doc) elif hasattr(doc, 'items'): docs.append(dict(doc.items())) else: raise TypeError('expected dict, got %s' % type(doc)) content = options content.update(docs=docs) _, _, data = self.resource.post_json('_bulk_docs', body=content) results = [] for idx, result in enumerate(data): if 'error' in result: if result['error'] == 'conflict': exc_type = http.ResourceConflict else: # XXX: Any other error types mappable to exceptions here? exc_type = http.ServerError results.append((False, result['id'], exc_type(result['reason']))) else: doc = documents[idx] if isinstance(doc, dict): # XXX: Is this a good idea?? doc.update({'_id': result['id'], '_rev': result['rev']}) results.append((True, result['id'], result['rev'])) return results
def test_missing_required_errors(self): class TestDoc(Model): language = StringType(choices=['en', 'de'], required=True) result = validate_instance(TestDoc()) self.assertNotEqual(result.tag, 'OK')
def test_good_value_validates(self): self.testmodel.the_list = [2,2,2,2,2,2] result = validate_instance(self.testmodel) self.assertEqual(result.tag, 'OK')
def test_uncoerceible_value_passes_validation(self): self.testmodel.the_list = ["2","2","2","2","horse","2"] result = validate_instance(self.testmodel) self.assertNotEqual(result.tag, 'OK')
def testValidIP(self): test = self.Test() test.ip = '8.8.8.8' result = validate_instance(test) self.assertEqual(result.tag, 'OK')