def test_deserialize(self): promo = Promotion() data = {'name': 'test', 'promo_type': '%', 'value': 5.0, 'start_date': '2017-10-17 23:59:59', 'end_date': '9999-12-31 23:59:59', 'detail': 'testtest'} promo.deserialize(data) self.assertEqual(promo.serialize(), {'id': promo.id, 'name': 'test', 'promo_type': '%', 'value': 5.0, 'start_date': '2017-10-17 23:59:59', 'end_date': '9999-12-31 23:59:59', 'detail': 'testtest'})
def test_find_by_discount(self): """ Find a Promotion by Discount """ Promotion("A1234", "BOGO", True, "20").save() Promotion("B4321", "dollar", False, "5").save() promotions = Promotion.find_by_discount("20") self.assertEqual(len(promotions), 1) self.assertEqual(promotions[0].productid, "A1234")
def test_find_by_name(self): """ Find a Promotion by Name """ Promotion(name="20%OFF", product_id=9527, discount_ratio=80).save() Promotion(name="50%OFF", product_id=26668).save() promotions = Promotion.find_by_name("20%OFF") self.assertEqual(promotions[0].product_id, 9527) self.assertEqual(promotions[0].name, "20%OFF")
def test_find_by_availability(self): """ Find a Promotion by Availability """ Promotion("A1234", "BOGO", True, "20").save() Promotion("B4321", "dollar", False, "5").save() promotions = Promotion.find_by_availability(True) self.assertEqual(len(promotions), 1) self.assertEqual(promotions[0].productid, "A1234")
def test_remove_all(self): """ Remove all entries """ Promotion(name="20%OFF", product_id=9527, discount_ratio=80).save() Promotion(name="50%OFF", product_id=26668).save() Promotion.remove_all() promotions = Promotion.all() self.assertEqual(len(promotions), 0)
def list_promotions(): r""" Returns all of the Promotions Search the promotions in the database. <ul> <li>Only the first non-empty field will be considered.</li> <li>An empty query will result in a list of all promotion entries in the database</li> </ul> --- tags: - promotions produces: - application/json parameters: - name: name in: query description: name of the promotion required: false type: string - name: product_id in: query description: product_id for the promotion required: false type: integer minimum: 0 format: int32 - name: discount_ratio in: query description: discount ratio of the promotion required: false type: integer maximum: 100.0 minimum: 0 format: int32 responses: 200: description: search results matching criteria schema: type: array items: $ref: '#/definitions/ResponsePromotionObject' 400: description: bad input parameter """ promotions = [] promotion_id = request.args.get('promotion_id') name = request.args.get('name') product_id = request.args.get('product_id') discount_ratio = request.args.get('discount_ratio') if name: promotions = Promotion.find_by_name(name) elif product_id: promotions = Promotion.find_by_product_id(product_id) elif discount_ratio: promotions = Promotion.find_by_discount_ratio(discount_ratio) else: promotions = Promotion.all() results = [promotion.serialize() for promotion in promotions] return make_response(jsonify(results), status.HTTP_200_OK)
def test_find_by_category(self): """ Find a Promotion by Category """ Promotion("A1234", "BOGO", True, "20").save() Promotion("B4321", "dollar", False, "5").save() promotions = Promotion.find_by_category("dollar") self.assertNotEqual(len(promotions), 0) self.assertEqual(promotions[0].category, "dollar") self.assertEqual(promotions[0].productid, "B4321")
def setUp(self): """ Runs before each test """ server.init_db() db.drop_all() # clean up the last tests db.create_all() # create new tables Promotion(name='20%OFF', product_id=9527, discount_ratio=80).save() Promotion(name='50%OFF', product_id=26668, discount_ratio=50).save() self.app = server.app.test_client()
def test_find_by_discount_ratio(self): """ Find a Promotion by Discount ratio """ Promotion(name="20%OFF", product_id=9527, discount_ratio=80).save() Promotion(name="50%OFF", product_id=26668).save() promotions = Promotion.find_by_discount_ratio(80) Promotion.logger.info(promotions) self.assertEqual(promotions[0].product_id, 9527) self.assertEqual(promotions[0].name, "20%OFF")
def test_vcap_services(self): """ Test if VCAP_SERVICES works """ if 'VCAP_SERVICES' in os.environ: Promotion.init_db() self.assertIsNotNone(Promotion.redis) else: with patch.dict(os.environ, {'VCAP_SERVICES': json.dumps(VCAP_SERVICES)}): Promotion.init_db() self.assertIsNotNone(Promotion.redis)
def test_find_or_404_404(self): """ Find promotion or 404 expecting 404 """ Promotion(name="20%OFF", product_id=9527, discount_ratio=80).save() try: promotion = Promotion.find_or_404(2) # Should not reach beyond this line. self.assertIsNone(promotion) except: pass
def test_find_or_404(self): """ Find promotion or 404 """ Promotion(name="20%OFF", product_id=9527, discount_ratio=80).save() promotion = Promotion.find_or_404(1) self.assertIsNotNone(promotion) self.assertEqual(promotion.promotion_id, 1) self.assertEqual(promotion.name, "20%OFF") self.assertEqual(promotion.product_id, 9527) self.assertEqual(promotion.discount_ratio, 80) self.assertEqual(promotion.counter, 0)
def test_delete_unavailable_promotion(self): """ Delete all unavailable promotions """ unavailable_promo_count = Promotion.find_by_availability(False).count() # initial count of unavailable promotions, make sure it's not empty self.assertNotEqual(unavailable_promo_count, 0) resp = self.app.delete('/promotions/unavailable') self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(len(resp.data), 0) new_unavailable_promo_count = Promotion.find_by_availability( False).count() self.assertEqual(new_unavailable_promo_count, 0)
def get(self): """ Returns all of the Promotions """ conditions = request.values.to_dict() payload = Promotion.all() if conditions: payload = Promotion.find_by_conditions(conditions) payload = [promo.serialize() for promo in payload] flask_app.logger.info("GET promotions success") return payload, 200
def create_promo(): data = request.get_json() or {} if 'name' not in data or 'type' not in data or 'value' not in data or 'isActive' not in data: return bad_request('name,type,value and isActive are required') if Promotion.query.filter(Promotion.name == data['name']).first(): return bad_request('use a different name') item = Promotion() item.from_dict(data) db.session.add(item) db.session.commit() response = jsonify(item.to_dict()) response.status_code = 201 return response
def test_serialize_a_promotion(self): """ Serialize a Promotion """ promotion = Promotion("A1234", "BOGO", True, "20") data = promotion.serialize() self.assertNotEqual(data, None) self.assertNotIn('_id', data) self.assertIn('productid', data) self.assertEqual(data['productid'], "A1234") self.assertIn('category', data) self.assertEqual(data['category'], "BOGO") self.assertIn('available', data) self.assertEqual(data['available'], True) self.assertIn('discount', data) self.assertEqual(data['discount'], "20")
def test_delete_a_promotion(self): """ Delete a Promotion """ promotion = Promotion("A1234", "BOGO", False, "20") promotion.save() self.assertEqual(len(Promotion.all()), 1) # delete the promotion and make sure it isn't in the database promotion.delete() self.assertEqual(len(Promotion.all()), 0)
def test_deserialize_a_promotion(self): """ Test deserialization of a Promotion """ data = { "promotion_id": 1, "name": "20%OFF", "product_id": 9527, "discount_ratio": 80 } promotion = Promotion() promotion.deserialize(data) self.assertNotEqual(promotion, None) self.assertEqual(promotion.promotion_id, None) self.assertEqual(promotion.name, "20%OFF") self.assertEqual(promotion.product_id, 9527) self.assertEqual(promotion.discount_ratio, 80)
def get_promotions(promotion_id): """ Retrieves a single Promotion This endpoint will return a Promotion based on it's id --- tags: - promotions parameters: - name: promotion_id in: path description: Numeric ID of the promotion to get required: true type: integer responses: 200: description: promotion retrieved schema: $ref: '#/definitions/ResponsePromotionObject' 400: description: invalid input, object invalid 404: description: promotion not found, object invalid """ promotion = Promotion.find(promotion_id) if not promotion: raise NotFound( "Promotion with id '{}' was not found.".format(promotion_id)) return make_response(jsonify(promotion.serialize()), status.HTTP_200_OK)
def delete(self, promo_id): '''Delete a specific Promotion''' flask_app.logger.info('Request to Delete a promotion with id [%s]', id) promo = Promotion.find_by_id(promo_id) if promo: promo.delete() return make_response('', 204)
def test_get_promotion(self): """ Test of getting a promotion with promotion id """ promotion = Promotion.find_by_promo_name('Buy one get one free')[0] resp = self.app.get('/promotions/{}'.format(promotion.id)) self.assertEqual(resp.status_code, status.HTTP_200_OK) data = json.loads(resp.data) self.assertEqual(data['promo_name'], promotion.promo_name)
def test_deserialize_a_promotion(self): """ Deserialize a Promotion """ data = { "productid": "B4321", "category": "dollar", "available": True, "discount": "5" } promotion = Promotion() promotion.deserialize(data) self.assertNotEqual(promotion, None) self.assertEqual(promotion.id, None) self.assertEqual(promotion.productid, "B4321") self.assertEqual(promotion.category, "dollar") self.assertEqual(promotion.available, True) self.assertEqual(promotion.discount, "5")
def populate(): """ The method run when environment is set to populate. Iterate through the .csv files and getting every row of every file and populate the database. """ if __name__ == "app.populate_db": try: file_list = [ 'orders', 'order_lines', 'products', 'promotions', 'product_promotions', 'commissions' ] for file_name in file_list: file = open('app/csv_data/' + file_name + '.csv', encoding='utf8') data = reader(file, delimiter=',') next(data) for entry in data: if file_name == 'orders': row = Order(id=entry[0], created_at=datetime.strptime( entry[1], '%d/%m/%Y').date(), vendor_id=entry[2], customer_id=entry[3]) if file_name == 'order_lines': row = OrderLine(order_id=entry[0], product_id=entry[1], product_description=entry[2], product_price=entry[3], product_vat_rate=entry[4], discount_rate=entry[5], quantity=entry[6], full_price_amount=entry[7], discounted_amount=entry[8], vat_amount=entry[8], total_amount=entry[8]) if file_name == 'products': row = Products(id=entry[0], description=entry[1]) if file_name == 'promotions': row = Promotion(id=entry[0], description=entry[1]) if file_name == 'product_promotions': row = ProductPromotion(date=datetime.strptime( entry[0], '%d/%m/%Y').date(), product_id=entry[1], promotion_id=entry[2]) if file_name == 'commissions': row = VendorCommissions(date=datetime.strptime( entry[0], '%d/%m/%Y').date(), vendor_id=entry[1], rate=entry[2]) db.session.add(row) db.session.commit() print('Finished') except Exception as error: print(error)
def test_serialize_a_promotion(self): """ Test serialization of a Promotion """ promotion = Promotion(name="20%OFF", product_id=9527, discount_ratio=80) data = promotion.serialize() self.assertNotEqual(data, None) self.assertIn('promotion_id', data) self.assertEqual(data['promotion_id'], None) self.assertIn('name', data) self.assertEqual(data['name'], "20%OFF") self.assertIn('product_id', data) self.assertEqual(data['product_id'], 9527) self.assertIn('counter', data) self.assertIsNone(data['counter']) self.assertIn('discount_ratio', data) self.assertEqual(data['discount_ratio'], 80)
def redeem_promotions(promotion_id): """ Redeem a Promotion This endpoint will increment the counter of a Promotion by 1. """ promotion = Promotion.redeem_promotion(promotion_id) return make_response(jsonify(promotion.serialize()), status.HTTP_200_OK)
def test_delete_a_promotion(self): """ Delete a Promotion """ promotion = Promotion(name="20%OFF", product_id=9527, discount_ratio=80) promotion.save() self.assertEqual(len(Promotion.all()), 1) # delete the promotion and make sure it isn't in the database promotion.delete() self.assertEqual(len(Promotion.all()), 0)
def test_key_error_on_update(self, bad_mock): """ Test KeyError on update """ bad_mock.side_effect = KeyError() promotion = Promotion("A1234", "BOGO", True, "20") promotion.save() promotion.productid = 'B4321' promotion.update()
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...') data = {} # Check for form submission data if request.headers.get( 'Content-Type') == 'application/x-www-form-urlencoded': app.logger.info('Getting data from form submit') data = { 'productid': request.form['productid'], 'category': request.form['category'], 'available': True, 'discount': request.form['discount'] } else: check_content_type('application/json') app.logger.info('Getting data from API call') data = request.get_json() app.logger.info(data) promotion = Promotion() promotion.deserialize(data) promotion.save() app.logger.info('Promotion with new id [%s] saved!', promotion.id) message = promotion.serialize() location_url = url_for('get_promotions', promotion_id=promotion.id, _external=True) return make_response(jsonify(message), status.HTTP_201_CREATED, {'Location': location_url})
def test_get_promotion(self): """ Get a single Promotion """ # get the promotion_id of a promotion promotion = Promotion.find_by_name('20%OFF')[0] resp = self.app.get('/promotions/{}'.format(promotion.promotion_id), content_type='application/json') self.assertEqual(resp.status_code, status.HTTP_200_OK) data = json.loads(resp.data) self.assertEqual(data['name'], promotion.name)
def test_create_a_promotion(self): """ Create a promotion and assert that it exists """ promotion = Promotion("A1234", "BOGO", False, "20") self.assertNotEqual(promotion, None) self.assertEqual(promotion.id, None) self.assertEqual(promotion.productid, "A1234") self.assertEqual(promotion.category, "BOGO") self.assertEqual(promotion.available, False) self.assertEqual(promotion.discount, "20")