def create(self, request, *args, **kwargs): bid = self.serializer_class(data=request.data) bid.is_valid(raise_exception=True) if request.user == bid.validated_data['lot'].animal: msg = _('Animal owner cannot buy his animal') raise exceptions.ErrorDetail(msg) if request.user.profile.balance < bid.validated_data['price']: msg = _("Don't have money enough for create this bid") raise exceptions.ErrorDetail(msg) self.queryset.create(user=request.user, **bid.validated_data) return Response(bid.data)
def test_misc_exceptions(self): msg = 'Object not found' code = 'test' response = self.force_error( self.DetailException(rest_exceptions.ErrorDetail(msg, code))) expected = { 'error_type': 'error', 'errors': [ { 'code': code, 'detail': msg }, ], 'field_errors': {}, } self.assertEqual(response.status_code, 400, msg=response.data) self.assertDictEqual(response.data, expected, msg=response.data) response = self.force_error( self.DetailException([ rest_exceptions.ErrorDetail(msg, code), rest_exceptions.ErrorDetail(msg, code), ])) expected = { 'error_type': 'error', 'errors': [ { 'code': code, 'detail': msg }, { 'code': code, 'detail': msg }, ], 'field_errors': {}, } self.assertEqual(response.status_code, 400, msg=response.data) self.assertDictEqual(response.data, expected, msg=response.data) # Disable logging, so we don't spam the test log logging.disable(logging.CRITICAL) response = self.force_error( self.DetailException([ rest_exceptions.ErrorDetail(msg, code), "should be an ErrorDetail", ])) logging.disable(logging.NOTSET) self.assertEqual(response.status_code, 500, msg=response.data)
def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None and response.status_code == 400: if 'owner_id' in response.data and response.data['owner_id'][ 0].code == 'does_not_exist': response.data['owner_id'][0] = exceptions.ErrorDetail( 'Please choose an owner.', code='does_not_exist') if 'number' in response.data and response.data['number'][ 0].code == 'unique': response.data['number'][0] = exceptions.ErrorDetail( 'This number plate already exists, please choose a different one.', code='unique') return response
def __init__(self, detail=None, code=None, reinit=True): message = detail if detail is not None else self.default_detail self.code = code if code is not None else self.default_code self.detail = { 'message': exceptions.ErrorDetail(message, self.default_code), 'reinit': reinit, }
def test_invalid_username(self): response = self.get_response(params=self.get_params(username='******')) self.assertEqual(response.data['username'], [ exceptions.ErrorDetail(u'Enter a valid username. This value may contain only ' u'letters, numbers, and @/./+/-/_ characters.', code='invalid') ] )
def _get_error_details(data, default_code=None): """加载错误详情 :param data: 错误对象 :param default_code: 默认错误码 :return: 错误对象 """ if isinstance(data, list): ret = [_get_error_details(item, default_code) for item in data] if isinstance(data, ReturnList): return ReturnList(ret, serializer=data.serializer) return ret elif isinstance(data, dict): ret = { key: _get_error_details(value, default_code) for key, value in data.items() } if isinstance(data, ReturnDict): return ReturnDict(ret, serializer=data.serializer) return ret elif isinstance(data, Trans): return data text = force_text(data) code = getattr(data, 'code', default_code) return exceptions.ErrorDetail(text, code)
def test_iterable_validators(self): """ Ensure `validators` parameter is compatible with reasonable iterables. """ data = {'char': 'abc', 'integer': 123} for validators in ([], (), set()): class ExampleSerializer(serializers.Serializer): char = serializers.CharField(validators=validators) integer = serializers.IntegerField() serializer = ExampleSerializer(data=data) assert serializer.is_valid() assert serializer.validated_data == data assert serializer.errors == {} def raise_exception(value): raise exceptions.ValidationError('Raised error') for validators in ([raise_exception], (raise_exception,), {raise_exception}): class ExampleSerializer(serializers.Serializer): char = serializers.CharField(validators=validators) integer = serializers.IntegerField() serializer = ExampleSerializer(data=data) assert not serializer.is_valid() assert serializer.data == data assert serializer.validated_data == {} assert serializer.errors == {'char': [ exceptions.ErrorDetail(string='Raised error', code='invalid') ]}
def saveModelAs(self, modelName): """Saves Model With New Name""" if self.checkModelOpen(): currentPath = self.client_session.modelInfo.uri folderPath = currentPath[:currentPath.rfind('/') + 1] file_path = f'{folderPath}{modelName}.ppl' storage = FileSystemStorage( os.path.join(settings.MEDIA_ROOT, 'models')) if not storage.exists(file_path): calcEngine = CalcEngine.factory(self.client_session) try: fullPath = f'{storage.base_location}/{file_path}' newModel = calcEngine.saveModel(fullPath) current_session = self.getSession() res = current_session.modelInfo res.uri = file_path self.saveSession() calcEngine = None return res except Exception as ex: raise exceptions.ErrorDetail( f'Error when saving the model: {str(ex)}') raise exceptions.NotAcceptable( "The file name you provide already exists") raise exceptions.NotAcceptable("There's no currentModel")
def create(self, request, *args, **kwargs): lot = self.serializer_class(data=request.data) lot.is_valid(raise_exception=True) if request.user != lot.validated_data['animal'].owner: msg = _('This animal is not your') raise exceptions.ErrorDetail(msg) self.queryset.create(owner=request.user, **lot.validated_data) return Response(lot.data)
def test_create_library(self): with self.subTest("a valid library"): new_library = { "name": "test library 1", "type": "test type 1", "data": { "foo": "bar" } } self.client.force_authenticate(self.me) with freeze_time("2019-06-01T16:35:34Z"): response = self.client.post(f"/{VERSION}/api/libraries/", new_library, format="json") assert response.status_code == status.HTTP_201_CREATED expected_result = { "created_at": "2019-06-01T16:35:34Z", "updated_at": "2019-06-01T16:35:34Z", "name": "test library 1", "type": "test type 1", "writeable": True, "data": { "foo": "bar" } } assert "id" in response.data response.data.pop("id") assert expected_result == response.data with self.subTest("a library with data as a string"): new_library = { "name": "test library 1", "type": "test type 1", "data": "foo string", } self.client.force_authenticate(self.me) with freeze_time("2019-06-01T16:35:34Z"): response = self.client.post(f"/{VERSION}/api/libraries/", new_library, format="json") assert status.HTTP_400_BAD_REQUEST == response.status_code assert { 'data': [ exceptions.ErrorDetail(string='This field is not a dict.', code='invalid') ] } == response.data
def test_reg_invalid(self): '''It does not create User and School model instances on an invalid input for Registration and valid inputs for User and School.''' params = self.get_params(registration={ 'conference': '68', 'num_beginner_delegates': 1, 'num_intermediate_delegates': 0, 'num_advanced_delegates': 0, 'num_spanish_speaking_delegates': 2, 'num_chinese_speaking_delegates': 2, }) response = self.get_response(params=params) self.assertEqual(response.data['num_spanish_speaking_delegates'], [exceptions.ErrorDetail('Cannot exceed total number of delegates.', code='invalid')]) self.assertEqual(response.data['num_chinese_speaking_delegates'], [exceptions.ErrorDetail('Cannot exceed total number of delegates.', code='invalid')]) self.assertFalse(User.objects.all().exists()) self.assertFalse(School.objects.all().exists()) self.assertFalse(Registration.objects.all().exists())
def test_2(): serializer = ExampleSerializer(data={ 'number': 'hello', 'text': "Hello world" }) with pytest.raises(exceptions.ValidationError) as exc: serializer.is_valid(raise_exception=True) assert exc.value.detail == { 'number': [exceptions.ErrorDetail('A valid integer is required.', 'invalid')] }
def test_create_assessment_fails_if_openbem_version_missing(self): self.client.force_authenticate(self.user) self.assert_create_fails( { "name": "test assessment 1", "description": "test description 2", }, status.HTTP_400_BAD_REQUEST, { 'openbem_version': [ exceptions.ErrorDetail(string='This field is required.', code='required') ] })
def test_create_assessment_fails_if_status_is_not_valid_choice(self): self.client.force_authenticate(self.user) self.assert_create_fails( {"name": "test assessment 1", "status": "bar"}, status.HTTP_400_BAD_REQUEST, { "status": [ exceptions.ErrorDetail( string='"bar" is not a valid choice.', code="invalid_choice" ) ] }, )
def test_create_assessment_fails_if_name_missing(self): self.client.force_authenticate(self.user) self.assert_create_fails( {"description": "test description 2"}, status.HTTP_400_BAD_REQUEST, { "name": [ exceptions.ErrorDetail( string="This field is required.", code="required" ) ] }, )
def test_create_assessment_fails_if_openbem_version_is_not_valid_choice( self): self.client.force_authenticate(self.user) self.assert_create_fails( { "name": "test assessment 1", "openbem_version": "foo", }, status.HTTP_400_BAD_REQUEST, { 'openbem_version': [ exceptions.ErrorDetail( string='"foo" is not a valid choice.', code='invalid_choice', ) ] })
def test_fails_if_data_field_is_a_string(self): with freeze_time("2019-07-13T12:10:12Z"): updateFields = {"data": {"foo string"}} self.client.force_authenticate(self.me) response = self.client.patch( f"/{VERSION}/api/assessments/{self.assessment.pk}/", updateFields, format="json", ) assert status.HTTP_400_BAD_REQUEST == response.status_code assert response.data == { "data": [ exceptions.ErrorDetail(string="This field is not a dict.", code="invalid") ] }
def _get_error_details(data, default_code=None): """ Descend into a nested data structure, forcing any lazy translation strings or strings into `ErrorDetail`. """ if isinstance(data, list): ret = [_get_error_details(item, default_code) for item in data] if isinstance(data, ReturnList): return ReturnList(ret, serializer=data.serializer) return ret elif isinstance(data, dict): ret = { key: _get_error_details(value, default_code) for key, value in data.items() } if isinstance(data, ReturnDict): return ReturnDict(ret, serializer=data.serializer) return ret elif isinstance(data, Trans): return data text = force_text(data) code = getattr(data, 'code', default_code) return exceptions.ErrorDetail(text, code)
def test_create_library(self): with self.subTest("a valid library"): new_library = { "name": "test library 1", "type": "test type 1", "data": { "foo": "bar" }, } self.client.force_authenticate(self.me) with freeze_time("2019-06-01T16:35:34Z"): response = self.client.post(f"/{VERSION}/api/libraries/", new_library, format="json") assert response.status_code == status.HTTP_201_CREATED expected_result = { "created_at": "2019-06-01T16:35:34Z", "updated_at": "2019-06-01T16:35:34Z", "name": "test library 1", "type": "test type 1", "permissions": { "can_write": True, "can_share": False }, "data": { "foo": "bar" }, "owner": { "id": f"{self.me.id}", "name": f"{self.me.username}", "type": "personal", }, } assert "id" in response.data response.data.pop("id") assert expected_result == response.data with self.subTest("a library with data as a string"): new_library = { "name": "test library 1", "type": "test type 1", "data": "foo string", } self.client.force_authenticate(self.me) with freeze_time("2019-06-01T16:35:34Z"): response = self.client.post(f"/{VERSION}/api/libraries/", new_library, format="json") assert status.HTTP_400_BAD_REQUEST == response.status_code assert { "data": [ exceptions.ErrorDetail(string="This field is not a dict.", code="invalid") ] } == response.data
def post(self, request, customer_id): self.customer_id = customer_id self.customer = Customer.objects.filter( customer_id=self.customer_id).get() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): quantity = 0 total = 0 products = [] for (key, item) in enumerate(request.data['products']): serializerProducts = self.serializerProducts_class(data=item) if not serializerProducts.is_valid(): localErrors = {} localErrors['products'] = { key: serializerProducts.errors.copy() } return Response(localErrors, status=status.HTTP_400_BAD_REQUEST) productId = serializerProducts.validated_data.get('product_id') check, product = self.customer_product_check(productId) if not check: localErrors = {} localErrors['products'] = [{ key: [ exceptions.ErrorDetail( string= f'The customer is not allowed to purchase the product identified by product_id {productId}', code='empty') ] }] return Response(localErrors, status=status.HTTP_409_CONFLICT) total += serializerProducts.validated_data.get( 'quantity') * product.price quantity += serializerProducts.validated_data.get('quantity') if quantity > 5: localErrors = {} localErrors['products'] = [ exceptions.ErrorDetail( string= 'The total quantity of products cannot exceed 5.', code='empty') ] return Response(localErrors, status=status.HTTP_409_CONFLICT) product.quantity = serializerProducts.validated_data.get( 'quantity') product_re = list( filter(lambda x: (x.product_id == product.product_id), products)) if not len(product_re): products.append(product) else: product_re[0].quantity += product.quantity self.products = products[:] self.deliveryAddress = request.data['delivery_address'] self.total = total self.set_products() order = { 'order_id': self.order.order_id, 'customer_id': self.order.customer.customer_id, 'creation_date': self.order.creation_date, 'delivery_address': self.order.delivery_address, 'total': self.order.total, 'products': self.get_order_details(self.order.order_id) } return Response(order, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)