def test_validate_id(): oid = ObjectIdType() oid.validate(FAKE_OID) oid.validate(str(FAKE_OID)) with pytest.raises(ConversionError): oid.validate('foo')
class CategoryModel(BaseAPIModel): name = StringType() href = StringType() description = StringType() _id = ObjectIdType(serialize_when_none=False) MONGO_COLLECTION = 'category'
def __new__(cls, name, bases, attrs): super_new = super(AsyncManagerMetaClass, cls).__new__ parents = [ b for b in bases if isinstance(b, AsyncManagerMetaClass) and not (b.__mro__ == (b, object)) ] if not parents: return super_new(cls, name, bases, attrs) else: if "id" not in attrs: attrs["id"] = ObjectIdType(serialized_name='_id', serialize_when_none=False) new_class = super_new(cls, name, bases, attrs) # Collection name attrs["__collection__"] = attrs.get( "__collection__", name.replace("Model", "").lower()) collection = attrs["__collection__"] # Add all attributes to the class. for obj_name, obj in attrs.items(): setattr(new_class, obj_name, obj) manager = AsyncManager(new_class, collection) setattr(new_class, "objects", manager) return new_class
class UserProfile(Model): """The basic things a user profile tends to carry. Isolated in separate class to keep separate from private data. """ # Provided by OwnedModelMixin owner_id = ObjectIdType(required=True) owner_username = StringType(max_length=30, required=True) # streamable # provided by StreamedModelMixin now created_at = MillisecondType() updated_at = MillisecondType() # identity info name = StringType(max_length=255) email = EmailType(max_length=100) website = URLType(max_length=255) bio = StringType(max_length=100) location_text = StringType(max_length=100) avatar_url = URLType(max_length=255) class Options: roles = { 'owner': blacklist('owner_id'), } def __init__(self, *args, **kwargs): super(UserProfile, self).__init__(*args, **kwargs) def __unicode__(self): return u'%s' % (self.name)
class CategoryModel(BaseAPIModel): """ [{"name":"Type1","href":"type1","description":"this is type1"}] """ name = StringType() href = StringType() description = StringType() _id = ObjectIdType(serialize_when_none=False) MONGO_COLLECTION = 'category'
class RecordAPiModel(BaseAPIModel): api_id = StringType() name = StringType() category_href = StringType() time = StringType() content = StringType() _id = ObjectIdType(serialize_when_none=False) MONGO_COLLECTION = 'recordapi'
class RecordModel(BaseAPIModel): name = StringType() category_href = StringType() version = StringType() time = StringType() RecordApiIdList = ListType(StringType) _id = ObjectIdType(serialize_when_none=False) MONGO_COLLECTION = 'record'
class ParamModel(BaseAPIModel): # id = IntType() name = StringType() required = BooleanType() default = StringType() type_ = StringType() description = StringType() api_id = StringType() _id = ObjectIdType(serialize_when_none=False) MONGO_COLLECTION = 'params'
class APiModel(BaseAPIModel): name = StringType() category_href = StringType() url = StringType() method = StringType() description = StringType() paramsIdList = ListType(StringType) responseIdList = ListType(StringType) paramsDemo = StringType() responseDemo = StringType() _id = ObjectIdType(serialize_when_none=False) MONGO_COLLECTION = 'api'
def test_validate_id(): oid = ObjectIdType() assert oid.validate_id(FAKE_OID) is True assert oid.validate_id(str(FAKE_OID)) is True with pytest.raises(ValidationError): oid.validate_id('foo')
def test_to_native(): oid = ObjectIdType() assert oid.to_native(FAKE_OID) == FAKE_OID assert oid.to_native(str(FAKE_OID)) == FAKE_OID with pytest.raises(ConversionError): oid.to_native('foo')
def test_to_primitive(): oid = ObjectIdType() assert oid.to_primitive(FAKE_OID) == str(FAKE_OID) assert oid.to_primitive(str(FAKE_OID)) == str(FAKE_OID)
class SubModel(Model): _id = ObjectIdType(required=False)
def test_objectidtype_on_objectd(): obj = ObjectIdType() try: obj.validate(bson.ObjectId("507f1f77bcf86cd799439011")) except pytest.raises(TypeError): pytest.fail("This exception shouldn't be raised")
def test_objectidtype_on_invalid_objectid(): obj = ObjectIdType() with pytest.raises(TypeError): obj.validate("123")
def test_objectidtype_object_empty(): obj = ObjectIdType() with pytest.raises(TypeError): obj("507f1f77bcf86cd7994390112")
class Car(Model): _id = ObjectIdType(metadata={'readOnly': True}) created_at = types.DateTimeType(metadata={'readOnly': True}) updated_at = types.DateTimeType(metadata={'readOnly': True}) vin = types.StringType() color = types.StringType() name = types.StringType() car_number = types.StringType() model = types.StringType() make = types.StringType() production_year = types.StringType() status = types.StringType(choices={'active', 'deleted'}, default='active') def _on_production_year_set(self, value): if not value: return try: datetime.strptime(value, '%Y') except ValueError: raise DataError({'production_year': "productionYear should match pattern '%Y'"}) def _on_make_set(self, value): if not value: return if not value.isupper(): raise DataError({'make': 'make should be uppercase'}) def _on_model_set(self, value): if not value: return if not value.isupper(): raise DataError({'model': 'model should be uppercase'}) def update_car(self, data): if self.status == 'deleted': raise errors.ForbiddenStatusError(self._id) if 'status' in data: raise DataError({'status': "Can not be set with this endpoint. " "Please use /api/cars/:obj_id/status"}) if 'vin' in data: raise DataError({'vin': "Can not be set with this endpoint. " "Please use /api/cars/:obj_id/vin"}) self.import_data(data) def update_car_vin(self, data): if self.status == 'deleted': raise errors.ForbiddenStatusError(self._id) vin = data.pop('vin') if data: raise DataError({'vin': "This is the only field that can be updated with this endpoint"}) if not isinstance(vin, str): raise DataError({'vin': f"Value must be string, but found {type(vin).__name__}"}) self.import_data({'vin': vin}) def update_status(self, data): if self.status == 'deleted': raise errors.ForbiddenStatusError(self._id) status = data.pop('status') if data: raise DataError({'status': "This is the only field that can be updated with this endpoint"}) if not isinstance(status, str): raise DataError({'status': f"Value must be string, but found {type(status).__name__}"}) self.import_data({'status': status})
class Order(Model): _id = ObjectIdType(required=True) client_name = StringType(required=True) phone_model = StringType() description = StringType()
class MongoModel(RDBModel): class Options: roles = {'default': blacklist('_id', )} _id: ObjectId = ObjectIdType()
class BaseModel(Model): _id = ObjectIdType()