Exemple #1
0
 def post(self):
     """
     Creates a supplier
     This endpoint will create a supplier based the data in the body that is posted
     """
     app.logger.info('Request to Create a supplier')
     check_content_type('application/json')
     data = request.get_json()
     if not isinstance(data, dict):
         data = json.loads(data)
     try:
         data['supplierName']
     except KeyError as error:
         raise DataValidationError('Invalid supplier: missing ' +
                                   error.args[0])
     except TypeError as error:
         raise DataValidationError(
             'Invalid supplier: body of request contained'
             'bad or no data')
     supplier = Supplier(**data)
     supplier.save()
     app.logger.debug('Payload = %s', api.payload)
     app.logger.info('supplier with new id [%s] saved!', supplier.id)
     location_url = api.url_for(SupplierResource,
                                supplier_id=supplier.id,
                                _external=True)
     return json.loads(supplier.to_json()), status.HTTP_201_CREATED, {
         'Location': location_url
     }
    def post(self, promotion_id):
        """
        Apply a promotion on a given set of products together with their prices

        This endpoint will return those given products with their updated price.
        Products that are not eligible to the given promotion will be returned without any update
        """
        app.logger.info('Apply promotion {%s} to products', promotion_id)
        check_content_type('application/json')
        data = request.get_json()

        # Get promotion data
        promotion = Promotion.find(promotion_id)
        if not promotion:
            api.abort(
                status.HTTP_404_NOT_FOUND,
                'Promotion with id "{}" was not found.'.format(promotion_id))

        # Check promotion availability
        if not promotion.is_active():
            api.abort(
                status.HTTP_409_CONFLICT,
                'Promotion with id "{}" is not active.'.format(promotion_id))

        # Get product data
        try:
            products = data['products']
            assert isinstance(products, list)
        except KeyError:
            raise DataValidationError('Missing products key in request data')
        except AssertionError:
            raise DataValidationError('The given products in request data \
                should be a list of serialized product objects')

        # Apply promotion on products
        products_with_new_prices = []
        eligible_ids = promotion.products
        non_eligible_ids = []
        print(eligible_ids)
        for product in products:
            product_id = product['product_id']
            try:
                new_price = float(product['price'])
            except ValueError:
                raise DataValidationError(
                    'The given product prices cannot convert to a float number'
                )
            if product_id in eligible_ids:
                new_price = new_price * (promotion.percentage / 100.0)
            else:
                non_eligible_ids.append(product_id)
            product['price'] = new_price
            products_with_new_prices.append(product)

        if len(non_eligible_ids) > 0:
            app.logger.info(
                'The following products are not \
                eligible to the given promotion: %s', non_eligible_ids)

        return {"products": products_with_new_prices}, status.HTTP_200_OK
    def post(self):
        """
        Create a Wishlist
        This endpoint will create a Wishlist. It expects the name and
        customer_id in the body
        """
        app.logger.info('Request to create a wishlist')
        check_content_type('application/json')
        body = request.get_json()
        app.logger.info('Body: %s', body)

        name = body.get('name', '')
        customer_id = body.get('customer_id', 0)

        if name == '':
            raise DataValidationError('Invalid request: missing name')

        if not isinstance(customer_id, int) or customer_id <= 0:
            raise DataValidationError('Invalid request: Wrong customer_id. ' \
                                      'Expected a number > 0')

        wishlist = Wishlist(name=name, customer_id=customer_id)
        wishlist.save()

        message = wishlist.serialize()

        # TO-DO: Replace with URL for GET wishlist once ready
        # location_url = api.url_for(WishlistResource, wishlist_id=wishlist.id, _external=True)
        location_url = '%s/wishlists/%s' % (request.base_url, wishlist.id)
        return message, status.HTTP_201_CREATED, {'Location': location_url}
Exemple #4
0
 def test_request_validation_error(self, bad_request_mock):
     """ Test a Data Validation error """
     bad_request_mock.side_effect = DataValidationError()
     test_shopcart = Shopcart()
     resp = self.app.post("/api/shopcarts",
                          json=test_shopcart.serialize(),
                          content_type="application/json")
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
Exemple #5
0
 def test_bad_request_data_validation_error(self, bad_request_mock):
     """Test a bad request with DataValidationError."""
     bad_request_mock.side_effect = DataValidationError()
     payment = PaymentsFactory()
     resp = self.app.post(
         '/payments',
         json=payment.serialize(),  # pylint: disable=no-member
         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
    def post(self, wishlist_id):
        """
        This endpoint adds an item to a Wishlist. It expects the
        wishlist_id and product_id.
        """
        app.logger.info('Request to add item into wishlist')
        check_content_type('application/json')

        # checking if the wishlist exists:
        wishlist = Wishlist.find(wishlist_id)
        if not wishlist:
            api.abort(status.HTTP_404_NOT_FOUND,
                      "Wishlist with id '%s' was not found." % wishlist_id)
        wishlist_product = WishlistProduct()
        wishlist_product.wishlist_id = wishlist_id

        body = request.get_json()
        app.logger.info('Body: %s', body)

        product_name = body.get('product_name', '')
        product_id = body.get('product_id', 0)

        if product_name == '':
            raise DataValidationError('Invalid request: missing name')

        wishlist_product.product_name = product_name

        if product_id == 0:
            raise DataValidationError('Invalid request: missing product id')

        wishlist_product.product_id = product_id

        app.logger.info('Request to add %s item to wishlist %s' %
                        (wishlist_product.product_id, wishlist_id))

        wishlist_product.save()
        message = wishlist_product.serialize()

        location_url = api.url_for(ProductResource,
                                   wishlist_id=wishlist.id,
                                   product_id=wishlist_product.product_id,
                                   _external=True)

        return message, status.HTTP_201_CREATED, {'Location': location_url}
Exemple #7
0
 def test_bad_request(self, bad_request_mock):
     """ Test a bad request error from find_by_condition """
     bad_request_mock.side_effect = DataValidationError()
     resp = self.app.get('/inventory', query_string='condition=wrong')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
 def test_bad_request(self, bad_request_mock):
     """ Test a Bad Request error from Find By Name """
     bad_request_mock.side_effect = DataValidationError()
     resp = self.app.get('/suppliers', query_string='name=Aikeeya')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
Exemple #9
0
 def test_bad_request_order(self, bad_request_mock):
     """ Test a Bad Request error from Find By order """
     bad_request_mock.side_effect = DataValidationError()
     resp = self.app.get('/payments', query_string='order_id=1')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
 def test_bad_request(self, bad_request_mock):
     """ Bad Request error from Create Order """
     bad_request_mock.side_effect = DataValidationError()
     resp = self.app.post('/orders', json="",
                          content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)