def test_all_shopcarts(self): """ Get all Shopcarts""" count = 5 for i in range(1, count + 1): Shopcart(id=i, user_id=(i + 1)).create() shopcarts_queried = Shopcart.all() self.assertEqual(len(shopcarts_queried), count)
def setUpClass(cls): """ These run once per Test suite """ app.debug = False # Set up the test database app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI app.config["SQLALCHEMY_POOL_RECYCLE"] = 30 Shopcart.init_db(app)
def setUpClass(cls): """ This runs once before the entire test suite """ app.config["TESTING"] = True app.config["DEBUG"] = False app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI app.logger.setLevel(logging.CRITICAL) Shopcart.init_db(app)
def test_find_shopcart(self): """ Find a Shopcart by id """ data = {"id": 1, "user_id": 120,} Shopcart(id=1, user_id=120).create() shopcart_queried = Shopcart.find(1) self.assertEqual(data["id"], shopcart_queried.id) self.assertEqual(data["user_id"], shopcart_queried.user_id)
def test_deserialize_a_shopcart(self): """ Test deserialization of a Shopcart """ data = {"user_id": 120} shopcart = Shopcart() shopcart.deserialize(data) self.assertNotEqual(shopcart, None) self.assertEqual(shopcart.user_id, 120)
def get(self, customer_id): """ Returns list of all of the shop cart items""" if request.args.get('price') == None: app.logger.info( 'Request to list all items in shopcart with customer_id: %s', customer_id) items = [] items = Shopcart.find_by_customer_id(customer_id) results = [item.serialize() for item in items] #if results is None or len(results) == 0: # api.abort(404, "No items for this customer.") return results, status.HTTP_200_OK else: target_price = request.args.get('price') print(target_price) app.logger.info( 'Request to query all items in shopcart with customer_id: %s', customer_id) items = [] items = Shopcart.query_by_target_price(customer_id, target_price) results = [item.serialize() for item in items] print(results) #if results is None or len(results) == 0: # api.abort(404, "No items for this customer.") return results, status.HTTP_200_OK
def test_find_by_shopcart_id_multiple(self): """ Find Shopcart Items by Shopcart id for Shopcart with multiple items """ shopcart = Shopcart().deserialize({"user_id": 12345}) shopcart.create() ShopcartItem(id=1, sid=shopcart.id, sku=3, name="obj 1", price=4, amount=5).create() ShopcartItem(id=6, sid=shopcart.id, sku=7, name="obj 2", price=8, amount=9).create() items_queried = ShopcartItem.find_by_shopcartid(shopcart.id) self.assertEqual(len(items_queried), 2)
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)
def test_place_order_invalid_shopcart(self): test_shopcart = Shopcart() test_shopcart.id = 1 resp = self.app.put( "/shopcarts/{}/place-order".format(test_shopcart.id), content_type="application/json", ) self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
def test_serialize_a_shopcart(self): """ Test serialization of a Shopcart """ shopcart = Shopcart(user_id=101) data = shopcart.serialize() self.assertNotEqual(data, None) self.assertIn("id", data) self.assertEqual(data["id"], None) self.assertIn("user_id", data) self.assertEqual(data["user_id"], 101)
def test_find_by_amount(self): """ Find Shopcart Items by amount """ shopcart = Shopcart().deserialize({"user_id": 12345}) shopcart.create() ShopcartItem(sid=shopcart.id, sku=101, name="printer", price=101.29, amount=1).create() ShopcartItem(sid=shopcart.id, sku=201, name="printer", price=101.29, amount=10).create() shopcart_items = ShopcartItem.find_by_amount(10) self.assertEqual(len(shopcart_items), 1) self.assertEqual(shopcart_items[0].amount, 10)
def test_delete_a_shopcart(self): """Delete a shopcart and everything in it""" self.assertEqual(len(Shopcart.all()), 0) shopcart = Shopcart(user_id=12345) shopcart.create() self.assertEqual(shopcart.id, 1) self.assertEqual(len(Shopcart.all()), 1) self.assertEqual(len(ShopcartItem.all()), 0) shopcart_item = ShopcartItem(sid=1, sku=5000, name="soap", price=2.23, amount=3) shopcart_item.create() self.assertEqual(shopcart_item.id, 1) shopcart_item = ShopcartItem(sid=1, sku=5001, name="shampoo", price=3.77, amount=1) shopcart_item.create() self.assertEqual(shopcart_item.id, 2) self.assertEqual(len(ShopcartItem.all()), 2) shopcart.delete() self.assertEqual(len(ShopcartItem.all()), 0) self.assertEqual(len(Shopcart.all()), 0)
def test_update_a_shopcart_item_without_id(self): """ Update a shopcart item """ shopcart = Shopcart(user_id=12345) shopcart.create() shopcart_item = ShopcartItem(sid=shopcart.id, sku=5000, name="soap", price=2.23, amount=3) shopcart_item.create() # Change it an update it shopcart_item.id = None self.assertRaises(DataValidationError, shopcart_item.update)
def test_query_by_target_price_pos(self): """ Find a shopcart by customer_id """ Shopcart(product_id=4, customer_id=11, quantity=1, price=150.30, text="book", state=0).save() Shopcart(product_id=5, customer_id=11, quantity=2, price=12.91, text="hat", state=1).save() shopcart = Shopcart.query_by_target_price(11, 30) self.assertEqual(shopcart.count(), 1) self.assertEqual(shopcart[0].product_id, 5) self.assertEqual(shopcart[0].customer_id, 11) self.assertEqual(shopcart[0].quantity, 2) self.assertEqual(float(shopcart[0].price), 12.91) self.assertEqual(shopcart[0].text, "hat") self.assertEqual(shopcart[0].state, 1)
def test_find_by_product_id_pos(self): """ Test find a shopcart item by product_id """ Shopcart(product_id=3, customer_id=10, quantity=2, price=5.0, text="pen", state=1).save() Shopcart(product_id=4, customer_id=11, quantity=1, price=150.30, text="book", state=0).save() shopcart = Shopcart.find_by_product_id(4) self.assertEqual(shopcart.count(), 1) self.assertEqual(shopcart[0].product_id, 4) self.assertEqual(shopcart[0].customer_id, 11) self.assertEqual(shopcart[0].quantity, 1) self.assertEqual(float(shopcart[0].price), 150.30) self.assertEqual(shopcart[0].text, "book") self.assertEqual(shopcart[0].state, 0)
def test_add_shopcart_item_with_not_existing_cart(self): """ Test using add shopcart_item method when shopcart doesnt exists""" shopcarts = Shopcart.all() self.assertEqual(shopcarts, []) shopcart = Shopcart(user_id=12345) self.assertTrue(shopcart is not None) self.assertEqual(shopcart.id, None) shopcart.create() self.assertEqual(shopcart.id, 1) shopcart_item = ShopcartItem(sid=1000, sku=5000, name="soap", price=2.23, amount=3) self.assertRaises(DataValidationError, shopcart_item.add)
def test_deserialize_a_shopcart(self): """ Test deserialization of a Shopcart """ data = {"id": 1, "product_id": 1, "customer_id": 1, "quantity": 2, "price": "45.66", "text": "Headphones","state":1} shopcart = Shopcart() shopcart.deserialize(data) self.assertNotEqual(shopcart, None) self.assertEqual(shopcart.id, None) self.assertEqual(shopcart.product_id,1) self.assertEqual(shopcart.customer_id,1) self.assertEqual(shopcart.quantity, 2) self.assertEqual(shopcart.price,"45.66") self.assertEqual(shopcart.text,"Headphones") self.assertEqual(shopcart.state,None)
def test_delete_an_shopcart(self): """ Delete an shopcart from the database """ shopcarts = Shopcart.all() self.assertEqual(shopcarts, []) shopcart = self._create_shopcart() shopcart.create() # Assert that it was assigned an id and shows up in the database self.assertEqual(shopcart.id, 1) shopcarts = Shopcart.all() self.assertEqual(len(shopcarts), 1) shopcart = shopcarts[0] shopcart.delete() shopcarts = Shopcart.all() self.assertEqual(len(shopcarts), 0)
def test_delete_a_shopcart_item(self): """Delete a shopcart item""" shopcart = Shopcart(user_id=12345) shopcart.create() self.assertEqual(shopcart.id, 1) self.assertEqual(len(ShopcartItem.all()), 0) shopcart_item = ShopcartItem(sid=1, sku=5000, name="soap", price=2.23, amount=3) shopcart_item.create() self.assertEqual(shopcart_item.id, 1) self.assertEqual(len(ShopcartItem.all()), 1) shopcart_item.delete() self.assertEqual(len(ShopcartItem.all()), 0)
def put(self, customer_id, product_id): """ Update an item from shopcart This endpoint will update a item for the selected product in the shopcart """ app.logger.info( 'Request to update shopcart item with customer_id: %s, product_id: %s', customer_id, product_id) cart_item = Shopcart.find_by_customer_id_and_product_id( customer_id, product_id) if not cart_item: app.logger.info( "Customer_id and product_id for update have not been found") api.abort( status.HTTP_400_BAD_REQUEST, 'No product with id [{}] found for customer id [{}].'.format( product_id, customer_id)) app.logger.debug('Payload = %s', api.payload) data = api.payload update_cart_item = Shopcart() update_cart_item.deserialize(data) try: requested_quantity = int(update_cart_item.quantity) app.logger.info("requested_quantity = %s", requested_quantity) except ValueError: app.logger.info('Non-integer quantity requested') api.abort(status.HTTP_400_BAD_REQUEST, 'Non-integer quantity given') # bounds check if requested_quantity < 1: app.logger.info('Negative quantity requested') api.abort( status.HTTP_400_BAD_REQUEST, 'No positive product with id [{}] found for customer id [{}].'. format(product_id, customer_id)) # process to update the request cart_item.quantity = requested_quantity app.logger.info("cart_item.quantity = %s", cart_item.quantity) cart_item.state = SHOPCART_ITEM_STAGE['ADDED'] cart_item.save() app.logger.info( 'Quantity for customer id %s and product id %s has been updated', customer_id, product_id) return cart_item.serialize(), status.HTTP_200_OK
def test_delete(self): """ Delete a item """ item = Shopcart(product_id = 3, customer_id = 4) item.save() self.assertEqual(len(Shopcart.all()) , 1) # delete item and make sure it isn't in the database item.delete() self.assertEqual(len(Shopcart.all()), 0)
def test_find_by_shopcart_id(self): """ Find Shopcart Items by Shopcart id for Shopcart with single item """ shopcart = Shopcart().deserialize({"user_id": 12345}) shopcart.create() data = {"id": 1, "sid": shopcart.id, "sku": 150, "name": "test obj1", "price": 100, "amount": 1} ShopcartItem(id=data["id"], sid=data["sid"], sku=data["sku"], name=data["name"], price=data["price"], amount=data["amount"]).create() item_queried = ShopcartItem.find_by_shopcartid(data["sid"])[0] self.assertEqual(item_queried.id, data["id"]) self.assertEqual(item_queried.sid, data["sid"]) self.assertEqual(item_queried.sku, data["sku"]) self.assertEqual(item_queried.name, data["name"]) self.assertEqual(item_queried.price, data["price"]) self.assertEqual(item_queried.amount, data["amount"])
def get(self): """ Returns all of the Shopcarts """ logger.info('Request to list Shopcarts...') args = shopcart_args.parse_args() if args['user_id']: logger.info('Find by user') shopcarts = Shopcart.find_by_user(args['user_id']) else: logger.info('Find all') shopcarts = Shopcart.all() results = [shopcart.serialize() for shopcart in shopcarts] logger.info('[%s] Shopcarts returned', len(results)) return results, status.HTTP_200_OK
def test_place_order(self): """ Test sending shopcart order """ test_shopcart = ShopcartFactory() resp = self.app.post("/api/shopcarts", json={"user_id": test_shopcart.user_id}, content_type="application/json") self.assertEqual(resp.status_code, status.HTTP_201_CREATED) shopcart_id = resp.json["id"] shopcart_items = self._create_shopcart_items(10, shopcart_id) test_sku = shopcart_items[0].sku sku_shopcart_items = [ shopcart_item for shopcart_item in shopcart_items if shopcart_item.sku == test_sku ] resp = self.app.get("/api/shopcarts/items", query_string="sku={}".format(test_sku)) self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.get_json() self.assertEqual(len(data), len(sku_shopcart_items)) resp = self.app.put( "/api/shopcarts/{}/place-order".format(shopcart_id), content_type="application/json", ) self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(len(resp.data), 0) self.assertEqual(len(Shopcart.all()), 0) self.assertEqual(len(ShopcartItem.all()), 0)
def _create_shopcart(self, items=[]): """ Creates an Shopcart from a Factory """ fake_shopcart = ShopcartFactory() shopcart = Shopcart( customer_id=fake_shopcart.customer_id, items_list=items ) self.assertTrue(shopcart != None) return shopcart
def test_shopcart_item_creation_using_add(self): """ Create a shopcart item and add it to the database using add method""" shopcarts = Shopcart.all() self.assertEqual(shopcarts, []) shopcart = Shopcart(user_id=12345) self.assertTrue(shopcart is not None) self.assertEqual(shopcart.id, None) shopcart.create() self.assertEqual(shopcart.id, 1) shopcart_item = ShopcartItem(sid=shopcart.id, sku=5000, name="soap", price=2.23, amount=3) shopcart_item.add() self.assertTrue(shopcart_item is not None) self.assertEqual(shopcart_item.sid, 1) self.assertEqual(shopcart_item.sku, 5000) self.assertEqual(shopcart_item.name, "soap") self.assertEqual(shopcart_item.price, 2.23) self.assertEqual(shopcart_item.amount, 3)
def test_find_by_customer_id(self): """ Find by customer_id """ shopcart = self._create_shopcart() shopcart.create() # Fetch it back by name same_shopcart = Shopcart.find_by_customer_id(shopcart.customer_id)[0] self.assertEqual(same_shopcart.customer_id, shopcart.customer_id) self.assertEqual(same_shopcart.id, shopcart.id)
def test_update_a_shopcart_item(self): """ Update a shopcart item """ shopcart = Shopcart(user_id=12345) shopcart.create() shopcart_item = ShopcartItem(sid=shopcart.id, sku=5000, name="soap", price=2.23, amount=3) shopcart_item.create() self.assertEqual(shopcart_item.id, 1) # Change it an update it shopcart_item.name = "soap" shopcart_item.update() self.assertEqual(shopcart_item.id, 1) # Fetch it back and make sure the id hasn't changed # but the data did change shopcart_item = ShopcartItem.all() self.assertEqual(len(shopcart_item), 1) self.assertEqual(shopcart_item[0].name, "soap")
def test_find_by_sku_and_sid(self): """ Find Shopcart Items by shopcart id and sku id """ shopcart_1 = Shopcart().deserialize({"user_id": 12345}) shopcart_1.create() shopcart_2 = Shopcart().deserialize({"user_id": 1235}) shopcart_2.create() sku = 3 ShopcartItem(id=1, sid=shopcart_1.id, sku=sku, name="obj 1", price=8, amount=5).create() ShopcartItem(id=6, sid=shopcart_2.id, sku=sku, name="obj 1", price=8, amount=9).create() item_queried = ShopcartItem.find_by_sku_and_sid(sku, shopcart_1.id) self.assertEqual(item_queried.amount, 5)
def put(self, shopcart_id): """ Place Order for a Shopcart This endpoint will place an order for a Shopcart based the id specified in the path """ logger.info('Request to place order for Shopcart with id: %s', shopcart_id) shopcart = Shopcart.find(shopcart_id) if not shopcart: logger.info("Shopcart with ID [%s] is does not exist.", shopcart_id) api.abort( status.HTTP_404_NOT_FOUND, "Shopcart with ID [%s] is does not exist." % shopcart_id ) shopcart_items = ShopcartItem.find_by_shopcartid(shopcart_id) if shopcart_items is None or len(shopcart_items) == 0: logger.info("Shopcart with ID [%s] is empty.", shopcart_id) api.abort( status.HTTP_404_NOT_FOUND, "Shopcart with ID [%s] is empty." % shopcart_id ) shopcart_items_list = [item.serialize() for item in shopcart_items] # once we have the list of shopcart items we can send in JSON format to the orders team #add the order status as PLACED for a new order order_items= [] for item in shopcart_items_list: order_item = {} order_item["item_id"] = int(item["id"]) order_item["product_id"] = int(item["sku"]) order_item["quantity"] = int(item["amount"]) order_item["price"] = item["price"] order_item["status"] = "PLACED" order_items.append(order_item) order = { "customer_id": int(shopcart.serialize()["user_id"]), "order_items": order_items, } payload = json.dumps(order) headers = {'content-type': 'application/json'} res = requests.post( ORDER_ENDPOINT, data=payload, headers=headers ) logger.info('Put Order response %d %s', res.status_code, res.text) if res.status_code != 201: api.abort( status.HTTP_400_BAD_REQUEST, "Unable to place order for shopcart [%s]." % shopcart_id ) shopcart.delete() logger.info('Shopcart with id: %s has been deleted', shopcart_id) return make_response("", status.HTTP_204_NO_CONTENT)