def test_promotion_deserialize_exceptions(self):
        """ Test Promotion deserialization exceptions"""
        promotion = PromotionFactory()
        json_data = json.dumps(dict(
            percentage=promotion.percentage,
            start_date=promotion.start_date,
        ))
        promotion_deserialized = Promotion()
        try:
            promotion_deserialized.deserialize(json.loads(json_data))
        except DataValidationError:
            self.assertRaises(DataValidationError)

        json_data = json.dumps(dict(
            code=promotion.code,
            percentage=promotion.percentage,
            expiry_date="shouldn't like this",
            start_date=promotion.start_date,
            products=promotion.products
        ))
        promotion_deserialized = Promotion()
        try:
            promotion_deserialized.deserialize(json.loads(json_data))
        except DataValidationError:
            self.assertRaises(DataValidationError)
Beispiel #2
0
 def test_deserialize_a_promotion(self):
     """ Deserialize a Promotion """
     data = {"productid": "A002", "category": "BOGO", "available": True, "discount": 10 }
     promotion = Promotion()
     promotion.deserialize(data)
     self.assertNotEqual(promotion, None)
     #self.assertEqual(promotion.id, None)
     self.assertEqual(promotion.productid, "A002")
     self.assertEqual(promotion.category, "BOGO")
     self.assertEqual(promotion.available, True)
     self.assertEqual(promotion.discount, 10)
Beispiel #3
0
def create_promotions():
    """
    Creates a Promotion
    This endpoint will create a Promotion based the data in the body that is posted
    """
    app.logger.info("Request to create a promotion")
    check_content_type("application/json")
    promotion = Promotion()
    promotion.deserialize(request.get_json())
    promotion.create()
    message = promotion.serialize()
    #location_url = url_for("get_promotions", promotion_id=promotion.id, _external=True)
    location_url = "not implemented"
    return make_response(jsonify(message), status.HTTP_201_CREATED,
                         {"Location": location_url})
    def post(self):
        """
        Add a promotion

        This endpoint will return a Promotion based on it's id and the URL to that promotion
        """
        app.logger.info('Request to create a Promotion')
        check_content_type('application/json')
        promotion = Promotion()
        app.logger.debug('Payload = %s', api.payload)
        promotion.deserialize(api.payload)
        promotion.save()
        message = promotion.serialize()
        location_url = api.url_for(PromotionResource,
                                   promotion_id=promotion.id,
                                   _external=True)

        return message, status.HTTP_201_CREATED, {'Location': location_url}
 def test_promotion_deserialize(self):
     """ Test Promotion deserialization"""
     promotion = PromotionFactory()
     json_data = json.dumps(dict(
         code=promotion.code,
         percentage=promotion.percentage,
         expiry_date=promotion.expiry_date,
         start_date=promotion.start_date,
         products=promotion.products
     ))
     promotion_deserialized = Promotion()
     promotion_deserialized.deserialize(json.loads(json_data))
     self.assertEqual(promotion.code, promotion_deserialized.code)
     self.assertEqual(promotion.percentage,
                      promotion_deserialized.percentage)
     self.assertEqual(promotion.expiry_date,
                      promotion_deserialized.expiry_date)
     self.assertEqual(promotion.start_date,
                      promotion_deserialized.start_date)
Beispiel #6
0
    def post(self):
        """
        Creates a Promotion

        This endpoint will create a Promotion based the data in the body that is posted
        or data that is sent via an html form post.
        """
        app.logger.info('Request to Create a Promotion')
        content_type = request.headers.get('Content-Type')
        if not content_type:
            abort(status.HTTP_400_BAD_REQUEST, "No Content-Type set")

        data = {}
        # Check for form submission data
        if content_type == 'application/x-www-form-urlencoded':
            app.logger.info('Processing FORM data')
            app.logger.info(type(request.form))
            app.logger.info(request.form)
            data = {
                'productid': request.form['productid'],
                'category': request.form['category'],
                'available': request.form['available'].lower() in ['yes', 'y', 'true', 't', '1'],
                'discount': request.form['discount']
            }
        elif content_type == 'application/json':
            app.logger.info('Processing JSON data')
            data = request.get_json()
        else:
            message = 'Unsupported Content-Type: {}'.format(content_type)
            app.logger.info(message)
            abort(status.HTTP_400_BAD_REQUEST, message)

        promotion = Promotion()
        try:
            promotion.deserialize(data)
        except DataValidationError as error:
            raise BadRequest(str(error))
        promotion.save()
        app.logger.info('Promotion with new id [%s] saved!', promotion.id)
        location_url = api.url_for(PromotionResource, promotion_id=promotion.id, _external=True)
        return promotion.serialize(), status.HTTP_201_CREATED, {'Location': location_url}
Beispiel #7
0
 def test_deserialize_a_promotion(self):
     """ Test deserialization of a promotion """
     promotion = Promotion(
         name="New_Sale",
         description="Amazing",
         start_date=datetime.strptime('2001-01-01 00:00:00',
                                      '%Y-%m-%d %H:%M:%S'),
         end_date=datetime.strptime('2001-01-01 00:00:00',
                                    '%Y-%m-%d %H:%M:%S'))
     data = promotion.serialize()
     promotion.deserialize(data)
     self.assertNotEqual(promotion, None)
     self.assertEqual(promotion.id, None)
     self.assertEqual(promotion.name, "New_Sale")
     self.assertEqual(promotion.description, "Amazing")
     self.assertEqual(
         promotion.start_date,
         datetime.strptime('2001-01-01 00:00:00', DATETIME_FORMAT))
     self.assertEqual(
         promotion.end_date,
         datetime.strptime('2001-01-01 00:00:00', DATETIME_FORMAT))
Beispiel #8
0
    def test_deserialize(self):
        """ Test deserialization of a promotion """
        promotion = Promotion(
            id=2,
            title="Thanksgiving Special",
            description="Some items off in honor of the most grateful month.",
            promo_code="tgiving",
            promo_type=PromoType.DISCOUNT,
            amount=50,
            start_date=datetime(2020, 11, 1),
            end_date=datetime(2020, 11, 30),
            is_site_wide=False,
        )
        product_1 = Product()
        product_1.id = 123
        promotion.products.append(product_1)
        product_2 = Product()
        product_2.id = 456
        promotion.products.append(product_2)
        db.session.add(product_1)
        db.session.add(product_2)

        data = promotion.serialize()
        promotion.deserialize(data)

        self.assertNotEqual(promotion, None)
        self.assertEqual(promotion.id, 2)
        self.assertEqual(promotion.title, "Thanksgiving Special")
        self.assertEqual(
            promotion.description,
            "Some items off in honor of the most grateful month.")
        self.assertEqual(promotion.promo_code, "tgiving")
        self.assertEqual(promotion.amount, 50)
        self.assertEqual(promotion.start_date, "2020-11-01T00:00:00")
        self.assertEqual(promotion.end_date, "2020-11-30T00:00:00")
        self.assertEqual(promotion.is_site_wide, False)
        self.assertEqual(
            [product.id for product in promotion.products],
            [123, 456],
        )
Beispiel #9
0
 def post(self):
     """
     Creates a Promotion
     This endpoint will create a Promotion based the data in the body that is posted
     """
     app.logger.info("Request to create a promotion")
     check_content_type("application/json")
     json = request.get_json()
     if "products" in json:
         for product_id in json["products"]:
             if product_id != "" and Product.query.get(product_id) is None:
                 Product(id=product_id).create()
     promotion = Promotion()
     promotion.deserialize(json)
     promotion.create()
     location_url = api.url_for(
         PromotionResource, promotion_id=promotion.id, _external=True
     )
     app.logger.info("Promotion with ID [%s] created.", promotion.id)
     return (
         promotion.serialize(),
         status.HTTP_201_CREATED,
         {"Location": location_url},
     )