def setUp(self): self.user = UserModel.objects.create(username='******', email='*****@*****.**') self.model_class = drfs.generate_model( 'TestModelRalationBelongsTo.json') self.model_class_wt_ignore = drfs.generate_model( 'TestModelRalationBelongsTo_withIgnore404Object.json')
def test_relations_nested(self): modelClass = drfs.generate_model('TestModelWithRelations_Nested.json') serializerClass = drfs.generate_serializer(modelClass) instance = modelClass.objects.create( belongs_to_field=self.user, has_one=self.test, ) instance.has_many.add(*self.test_many) instance.save() ser = serializerClass(instance) self.assertDictEqual( dict(ser.data), { 'id': instance.pk, 'has_one': { 'id': self.test.pk, 'string_field': 'my string' }, 'has_many': self.test_many_data, 'belongs_to_field': { 'id': self.user.pk, 'username': '******', 'email': '*****@*****.**' } })
def test_abstract(self): TestModelAbstract = drfs.generate_model('TestModelAbstract.json') self.assertEqual( TestModelAbstract._meta.abstract, True ) with open('./tests/models.json/TestModelFromAbstract.json') as f: modelJson = json.load(f) gen = DjangoOrmModelGenerator(modelJson, 'tests') TestModelFromAbstract = gen.to_django_model() opts = TestModelFromAbstract._meta field_names = [ f.name for f in opts.get_fields() ] self.assertEqual( TestModelFromAbstract._meta.abstract, False ) self.assertEqual( sorted(field_names), [ 'array_field', 'bool_field', 'datetime_field', 'id', 'int_field', 'new_field', 'object_field', 'string_field' ])
def test_selializergen(self): modelClass = drfs.generate_model('TestModelForJsonData.json') serializerClass = drfs.generate_serializer(modelClass) ser = serializerClass(data={'required': {}}) self.assertEqual(ser.is_valid(), True) ser = serializerClass(data={'required': {}, 'not_required': None}) self.assertEqual(ser.is_valid(), True) ser = serializerClass(data={'required': {}, 'not_required': 'nnoooo'}) self.assertEqual(ser.is_valid(), False) self.assertEqual(ser.errors['not_required'], ["Invalid JSON"]) ser = serializerClass(data={}) self.assertEqual(ser.is_valid(), False) self.assertEqual(ser.errors, {'required': ['This field is required.']}) ser = serializerClass(data={'required': None}) self.assertEqual(ser.is_valid(), False) self.assertEqual(ser.errors, {'required': ['This field may not be null.']}) ser = serializerClass(data={'required': {'some': 'value'}}) ser.is_valid() instance = ser.create(ser.validated_data) self.assertEqual(instance.not_required, {'default': 'not_required'})
def test_modelgen(self): def test_field(field, settings): field_class = FIELD_MAP[settings['type']] if not isinstance(field, field_class): self.fail("Field '"+field.name+"' is not an instance of "+str(field_class)) if 'default' in settings: # JSONField support for django >= 3.1 dvalue = field.default if callable(dvalue): dvalue = dvalue() self.assertEqual(dvalue, settings['default']) if 'max' in settings: if settings['type'] in ['string']: self.assertEqual(field.max_length, settings['max']) if settings['type'] == 'datetime': self.assertEqual( field.auto_now_add, settings['auto_now_add'] ) modelClass = drfs.generate_model('TestModel.json') with open('./tests/models.json/TestModel.json') as f: modelJson = json.load(f) opts = modelClass._meta hidden = [ "id", "TestModelWithRelations_Flat_by_hasOne", "TestModelWithRelations_Flat_by_hasMany", "TestModelWithRelations_Nested_by_hasOne", "TestModelWithRelations_Nested_by_hasMany" ] for field in opts.get_fields(): if field.name in hidden: continue test_field( field, modelJson['properties'][field.name] ) # test mixin for model instance = modelClass.objects.create(string_field="test") self.assertEqual( instance.string_field, 'test' ) instance.save(my_prop="world!") self.assertEqual( instance.string_field, 'world!' ) self.assertEqual( instance.say_hello(), "hello %s" % instance.id )
def test_relations_flat(self): modelClass = drfs.generate_model('TestModelWithRelations_Flat.json') serializerClass = drfs.generate_serializer(modelClass) instance = modelClass.objects.create( belongs_to_field=self.user, has_one=self.test, ) instance.has_many.add(*self.test_many) instance.save() ser = serializerClass(instance) ## # serialize ## self.assertDictEqual( dict(ser.data), { 'id': instance.pk, 'has_one': self.test.pk, 'has_many': [o.pk for o in self.test_many], 'belongs_to_field': self.user.pk }) ## # create ## has_many = [self.test_many[0].pk, self.test_many[2].pk, self.test.pk] ser = serializerClass(data={ 'belongs_to_field': self.user.pk, 'has_many': has_many }) ser.is_valid() instance = ser.create(ser.validated_data) self.assertEqual(instance.belongs_to_field, self.user) self.assertEqual(len(instance.has_many.all()), 3) pks = [o.pk for o in instance.has_many.all()] pks.sort() has_many.sort() self.assertEqual(pks, has_many) ## # update ## ser = serializerClass( data={ 'id': instance.pk, 'belongs_to_field': self.user2.pk, 'has_many': [self.test.pk] }) ser.is_valid() instance_updated = ser.update(instance, ser.validated_data) self.assertEqual(instance_updated.belongs_to_field, self.user2) self.assertEqual(len(instance_updated.has_many.all()), 1) self.assertEqual(instance_updated.has_many.all()[0], self.test)
def test_relations_has_one(self): modelClass = drfs.generate_model('TestModelRalationHasOne.json') opts = modelClass._meta has_one_field = opts.get_field('has_one_field') if not isinstance(has_one_field, OneToOneField): self.fail( "Field 'has_one_field' in model 'TestModelRalationHasOne' not instance of OneToOneField" ) remote_field = has_one_field.remote_field self.assertEqual( remote_field.model, UserModel )
def test_relations_belongs_to(self): modelClass = drfs.generate_model('TestModelRalationBelongsTo.json') opts = modelClass._meta belongs_to_field = opts.get_field('belongs_to_field') if not isinstance(belongs_to_field, ForeignKey): self.fail( "Field 'belongs_to_field' in model 'TestModelRalationBelongsTo' not instance of ForeignKey" ) remote_field = belongs_to_field.remote_field self.assertEqual( remote_field.model, UserModel )
def setUp(self): self.factory = RequestFactory() self.user = UserModel.objects.create( username='******', email='*****@*****.**') self.user2 = UserModel.objects.create( username='******', email='*****@*****.**') TestModel = drfs.generate_model('TestModel.json') self.m1 = TestModel.objects.create(int_field=100) self.m2 = TestModel.objects.create(int_field=200) self.test_model_class = drfs.generate_model( 'TestModelWithRelations_Flat.json') self.orig_test_model_definition = self.test_model_class.DRFS_MODEL_DEFINITION self.test1 = self.test_model_class.objects.create( belongs_to_field=self.user) self.test1.has_many.add(self.m1, self.m2) self.test2 = self.test_model_class.objects.create( belongs_to_field=self.user2) self.test2.has_many.add(self.m1) self.test3 = self.test_model_class.objects.create() self.test3.has_many.add(self.m2) self.maxDiff = None
def test_selializergen(self): modelClass = drfs.generate_model('TestModel.json') with open('./tests/models.json/TestModel.json') as f: modelJson = json.load(f) serializerClass = drfs.generate_serializer(modelClass) opts = serializerClass.Meta self.assertEqual(opts.model, modelClass) fields = [ "id", "TestModelWithRelations_Flat_by_hasOne", "TestModelWithRelations_Flat_by_hasMany", "TestModelWithRelations_Nested_by_hasOne", "TestModelWithRelations_Nested_by_hasMany" ] + list(modelJson['properties'].keys()) serializer_fields = opts.fields fields.sort() serializer_fields.sort() self.assertEqual(fields, serializer_fields)
def setUp(self): self.user = UserModel.objects.create( username='******', email='*****@*****.**') self.user2 = UserModel.objects.create( username='******', email='*****@*****.**') self.test_model_class = drfs.generate_model('TestModel.json') self.test = self.test_model_class.objects.create( string_field='my string') self.test_many = [ self.test_model_class.objects.create(string_field='string 1', int_field=2), self.test_model_class.objects.create(string_field='string 2', int_field=3), self.test_model_class.objects.create(string_field='string 3', int_field=4), ] self.test_many_data = [ { 'id': self.test_many[0].pk, 'string_field': 'string 1', 'int_field': 2 }, { 'id': self.test_many[1].pk, 'string_field': 'string 2', 'int_field': 3 }, { 'id': self.test_many[2].pk, 'string_field': 'string 3', 'int_field': 4 }, ] self.maxDiff = None
def test_embedsManyAsObject(self): modelClass = drfs.generate_model( 'TestModelWithEmbeddedManyAsObject.json') TestModel = drfs.generate_model('TestModel.json') serializerClass = drfs.generate_serializer(modelClass) test_model_id = TestModel.objects.last().id instance = modelClass.objects.create( many_embedded_as_object={'1': { 'estring': 'test' }}, nested_many_embedded_as_object={ '1': { 'estring': 'test2', 'one_embedded2': { "eint2": 200 } } }, many_embedded_as_object_with_model_key={ str(test_model_id): { 'estring': 'test3', 'one_embedded2': { "eint2": 100 } }, '500': { 'estring': 'test4', 'one_embedded2': { "eint2": 100 } } }) ser = serializerClass(instance) self.assertDictEqual(ser.data['many_embedded_as_object'], {"1": { "estring": "test", "eint": 90 }}) self.assertDictEqual(ser.data['nested_many_embedded_as_object'], { "1": { "estring": "test2", "one_embedded2": { "eint2": 200 }, "eint": 90 } }) self.assertDictEqual( ser.data['many_embedded_as_object_with_model_key'], { str(test_model_id): { "estring": "test3", "one_embedded2": { "eint2": 100 }, "eint": 90 } }) ## # update ## ser = serializerClass( data={ 'many_embedded_as_object_with_model_key': { str(test_model_id): { 'eint': 5, 'one_embedded2': {} }, 'nnnnooooonn': { 'eint': 6, } } }) ser.is_valid() instance_updated = ser.update(instance, ser.validated_data) self.assertDictEqual( ser.validated_data['many_embedded_as_object_with_model_key'], {str(test_model_id): { 'eint': 5, 'one_embedded2': { 'eint2': 90 } }}) self.assertDictEqual( instance_updated.many_embedded_as_object_with_model_key, {str(test_model_id): { 'eint': 5, 'one_embedded2': { 'eint2': 90 } }})
import drfs TestModel = drfs.generate_model('TestModel.json') TestModel2 = drfs.generate_model('TestModel2.json') TestModelWithOwner = drfs.generate_model('TestModelWithOwner.json') ModelWithRefToTestModel = drfs.generate_model('ModelWithRefToTestModel.json') TestModelWithRelations_Flat = drfs.generate_model( 'TestModelWithRelations_Flat.json') TestModelWithRelations_Nested = drfs.generate_model( 'TestModelWithRelations_Nested.json') TestModelRalationBelongsTo = drfs.generate_model( 'TestModelRalationBelongsTo.json') TestModelRalationBelongsTo_withIgnore404Object = drfs.generate_model( 'TestModelRalationBelongsTo_withIgnore404Object.json') TestModelRalationHasOne = drfs.generate_model('TestModelRalationHasOne.json') TestModelAbstract = drfs.generate_model('TestModelAbstract.json') TestModelForJsonData = drfs.generate_model('TestModelForJsonData.json') TestModelWithEmbeddedOne = drfs.generate_model('TestModelWithEmbeddedOne.json') TestModelWithEmbeddedManyAsObject = drfs.generate_model( 'TestModelWithEmbeddedManyAsObject.json')
def test_relations_embedsManyAsObject(self): from drfs.db.fields import EmbeddedManyAsObjectModel modelClass = drfs.generate_model('TestModelWithEmbeddedManyAsObject.json') field = modelClass._meta.get_field('many_embedded_as_object') self.assertTrue(isinstance(field, EmbeddedManyAsObjectModel)) instance = modelClass.objects.create(many_embedded_as_object={ '1': { 'estring': 'test' } }) self.assertEqual( instance.many_embedded_as_object['1']['estring'], 'test' ) # autoset self.assertEqual( instance.many_embedded_as_object['1']['eint'], 90 ) # nested embedded instance = modelClass.objects.create(nested_many_embedded_as_object={ '1': { 'estring': 'test', 'one_embedded2': { "eint2": 100 } } }) self.assertDictEqual( instance.nested_many_embedded_as_object, {'1': {'estring': 'test', 'one_embedded2': {'eint2': 100}, 'eint': 90}} ) # autoclean for model keys instance = modelClass.objects.create(many_embedded_as_object_with_model_key={ '1': { 'estring': 'test', 'one_embedded2': { "eint2": 100 } }, '2': { 'estring': 'test', 'one_embedded2': { "eint2": 100 } } }) # none will be saved self.assertDictEqual(instance.many_embedded_as_object_with_model_key, {}) # create object with id == 2 TestModel = drfs.generate_model('TestModel.json') TestModel.objects.create(id=2) instance = modelClass.objects.create(many_embedded_as_object_with_model_key={ '1': { 'estring': 'test', 'one_embedded2': { "eint2": 100 } }, '2': { 'estring': 'test', 'one_embedded2': { "eint2": 100 } } }) self.assertDictEqual( instance.many_embedded_as_object_with_model_key, { '2': { 'estring': 'test', 'eint': 90, 'one_embedded2': { "eint2": 100 } } } ) # errors self.assertRaisesMessage( ValidationError, "Wrong keys 'notExists' in {'estring': 'test', 'notExists': 'invalid'}", modelClass.objects.create, many_embedded_as_object={ '1': { 'estring': 'test', 'notExists': 'invalid' } } ) self.assertRaisesMessage( ValidationError, "2 should be instance of 'dict'", modelClass.objects.create, many_embedded_as_object={}, nested_many_embedded_as_object={ '1': 2 } ) self.assertRaisesMessage( ValidationError, "Wrong keys \'blabla\' in {\'blabla\': 100}", modelClass.objects.create, many_embedded_as_object={}, nested_many_embedded_as_object={ '1': { 'blabla': 100 } } )
def test_relations_has_one_drfs(self): modelClass = drfs.generate_model('TestModel2.json') modelClass = drfs.generate_model('ModelWithRefToTestModel.json') opts = modelClass._meta has_one_field = opts.get_field('has_one_field')
def test_selializergen(self): modelClass = drfs.generate_model('TestModelForGeoPoint.json') serializerClass = drfs.generate_serializer(modelClass) ser = serializerClass(data={'geo_point': ['invalid data']}) self.assertEqual(ser.is_valid(), False) self.assertEqual( ser.errors, { 'geo_point': ['Value must be valid JSON.'] } ) ser = serializerClass(data={'geo_point': {'key': 'invalid data'}}) self.assertEqual(ser.is_valid(), False) self.assertEqual( ser.errors, { 'geo_point': [ """Please provide 'lat' and 'lng' value. Ex.: {'lat': 0.3, 'lng': 32.122}""" ] } ) ser = serializerClass(data={'geo_point': {'lat': 'invalid data', 'lng': 0}}) self.assertEqual(ser.is_valid(), False) self.assertEqual( ser.errors, { 'geo_point': [ GeoPointSerializer.custom_error_messages['invalid_lat_lng_type'].format( field='lat', type=type('') ) ] } ) ser = serializerClass(data={'geo_point': {'lat': 0, 'lng': False}}) self.assertEqual(ser.is_valid(), False) self.assertEqual( ser.errors, { 'geo_point': [ GeoPointSerializer.custom_error_messages['invalid_lat_lng_type'].format( field='lng', type=type(False) ) ] } ) ser = serializerClass(data={'geo_point': {'lat': 0, 'lng': 0, 'text': False}}) self.assertEqual(ser.is_valid(), False) self.assertEqual( ser.errors, { 'geo_point': [ GeoPointSerializer.custom_error_messages['invalid_text_type'].format( type=type(False) ) ] } ) data = { 'geo_point': { 'lat': 0, 'lng': 0, 'field_to_remove': 'clean_me!' } } ser = serializerClass(data=data) ser.is_valid() self.assertEqual( ser.validated_data, { 'geo_point': { 'lat': 0, 'lng': 0 } } )