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) Supplier.init_db(app)
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 test_vcap_services(self): """ Test VCAP_SERVICES """ if 'VCAP_SERVICES' not in os.environ: os.environ.update({'VCAP_SERVICES': json.dumps(VCAP_SERVICES)}) Supplier.init_db("test") self.assertIsNotNone(Supplier.client) self.assertIsNotNone(Supplier.database)
def test_update_supplier_product(self): """ Update an suppliers product """ suppliers = Supplier.all() self.assertEqual(suppliers, []) product = self._create_product() supplier = self._create_supplier(products=[product]) supplier.create() # Assert that it was assigned an id and shows up in the database self.assertEqual(supplier.id, 1) suppliers = Supplier.all() self.assertEqual(len(suppliers), 1) # Fetch it back supplier = Supplier.find(supplier.id) old_product = supplier.products[0] self.assertEqual(old_product.desc, product.desc) old_product.desc = "XX" supplier.save() # Fetch it back again supplier = Supplier.find(supplier.id) product = supplier.products[0] self.assertEqual(product.desc, "XX")
def test_delete_a_supplier(self): """ Delete a Supplier """ supplier = SupplierFactory() supplier.create() self.assertEqual(len(Supplier.all()), 1) # delete the supplier and make sure it isn't in the database supplier.delete() self.assertEqual(len(Supplier.all()), 0)
def test_delete_a_supplier_with_wrong_id(self): """ Delete a Supplier with wrong Id""" supplier = SupplierFactory() supplier.save() self.assertEqual(len(Supplier.all()), 1) # delete the supplier with wrong Id and make sure nothing happens supplier.id = "0" supplier.delete() self.assertEqual(len(Supplier.all()), 1)
def test_add_a_supplier(self): """ Create a Supplier and add it to the database """ suppliers = Supplier.all() self.assertEqual(suppliers, []) supplier = self._create_supplier() supplier.create() # Assert that it was assigned an id and shows up in the database self.assertEqual(supplier.id, 1) suppliers = Supplier.all() self.assertEqual(len(suppliers), 1)
def test_find_by_is_active(self): """ Find a Supplier by is_active """ Supplier("supplier1", 2, True, [1, 2, 3], 8.5).save() Supplier("supplier2", 4, False, [1, 3, 5, 7], 6.5).save() suppliers = Supplier.find_by_is_active(True) self.assertEqual(len(suppliers), 1) self.assertEqual(suppliers[0].name, "supplier1") self.assertEqual(suppliers[0].like_count, 2) self.assertEqual(suppliers[0].is_active, True) self.assertEqual(len(suppliers[0].products), 3) self.assertEqual(suppliers[0].rating, 8.5)
def test_deserialize_a_supplier(self): """ Deserialize a Supplier """ data = {"_id": 1, "name": "supplier1", "like_count": 2, "is_active": True, "products": [1, 2, 3], "rating": 8.5} supplier = Supplier() supplier.deserialize(data) self.assertNotEqual(supplier, None) self.assertEqual(supplier.id, 1) self.assertEqual(supplier.name, "supplier1") self.assertEqual(supplier.like_count, 2) self.assertEqual(supplier.is_active, True) self.assertEqual(supplier.products, [1, 2, 3]) self.assertEqual(supplier.rating, 8.5)
def delete_all_suppliers(): """ Returns IDs of the Suppliers """ app.logger.info("Request for Supplier list") suppliers = [] id = request.args.get("id") if id: suppliers = Supplier.find(id) else: suppliers = Supplier.all() results = [supplier.delete() for supplier in suppliers] return make_response("", status.HTTP_204_NO_CONTENT)
def test_list_all_supplier(self): """ Test return a list of suppliers """ Supplier(supplierName="Walmart", address="NYC", averageRating=5, productIdList=['1', '2', '3']).save() Supplier(supplierName="Costco", address="SF", averageRating=2, productIdList=['1', '3', '4']).save() suppliers = Supplier.all() self.assertEqual(len(suppliers), 2) self.assertEqual(suppliers[0].supplierName, 'Walmart') self.assertEqual(suppliers[1].supplierName, 'Costco')
def put(self, supplier_id): """ Update a supplier """ app.logger.info('Request to update a supplier with id [%s]', supplier_id) check_content_type('application/json') supplier = Supplier.find(supplier_id) data = request.get_json() if not supplier: return api.abort( status.HTTP_404_NOT_FOUND, "Supplier with id '{}' not found".format(supplier_id)) supplier.update(**data) # supplier.reload() supplier = Supplier.find(supplier.id) return json.loads(supplier.to_json()), status.HTTP_200_OK
def get(self, product_id): """ Recommend a Supplier This endpoint will recommend top 1 highly-rated supplier based on a given product """ app.logger.info( 'Recommend suppliers containing product with id %s in their products', product_id) product_id = int(product_id) # retrieve all suppliers including this product first suppliers = [ supplier for supplier in Supplier.all() if product_id in supplier.products and supplier.is_active == True ] # get top 1 rated supplier, None if suppliers is empty if suppliers: res_supplier = max(suppliers, key=lambda x: x.rating).serialize() app.logger.info('Recommended supplier is: {}'.format(res_supplier)) else: res_supplier = [] app.logger.info("No Recommended supplier!!") return res_supplier, status.HTTP_200_OK
def list_suppliers(): """ Returns all of the suppliers """ app.logger.info("Request for Supplier list") suppliers = [] name = request.args.get("name") category = request.args.get("category") if name: suppliers = Supplier.find_by_name(name) elif category: suppliers = Supplier.find_by_category(category) else: suppliers = Supplier.all() results = [supplier.serialize() for supplier in suppliers] return make_response(jsonify(results), status.HTTP_200_OK)
def test_query_by_name(self): """ Test return a supplier given a name """ Supplier(supplierName="Walmart", address="NYC", averageRating=5, productIdList=['1', '2', '3']).save() Supplier(supplierName="Costco", address="SF", averageRating=2, productIdList=['1', '3', '4']).save() supplier = Supplier.find_by_name("Walmart") self.assertEqual(supplier.address, "NYC") self.assertEqual(supplier.averageRating, 5) self.assertEqual(supplier.productIdList, ['1', '2', '3']) nowhere = Supplier.find_by_name("NoWhere") self.assertEqual(nowhere, None)
def test_query_by_product(self): """ Test query by product """ Supplier(supplierName="Walmart", address="NYC", averageRating=5, productIdList=['1', '2', '3']).save() Supplier(supplierName="Costco", address="SF", averageRating=2, productIdList=['1', '3', '4']).save() suppliers = Supplier.find_by_product("4") supplier = suppliers[0] self.assertEqual(supplier.supplierName, "Costco") self.assertEqual(supplier.address, "SF") self.assertEqual(supplier.averageRating, 2) self.assertEqual(supplier.productIdList, ['1', '3', '4'])
def test_find_by_email(self): """ Find Suppliers by email """ suppliers = SupplierFactory.create_batch(3) for supplier in suppliers: supplier.create() results = Supplier.find_by_email(suppliers[0].email) self.assertNotEqual(results, []) self.assertEqual(results[0].email, suppliers[0].email)
def test_find_by_address(self): """ Find Suppliers by address """ suppliers = SupplierFactory.create_batch(3) for supplier in suppliers: supplier.create() results = Supplier.find_by_address(suppliers[0].address) self.assertNotEqual(results, []) self.assertEqual(results[0].address, suppliers[0].address)
def test_find_by_name(self): """ Find a Supplier by Name """ suppliers = SupplierFactory.create_batch(3) for supplier in suppliers: supplier.create() results = Supplier.find_by_name(suppliers[0].name) self.assertNotEqual(results, []) self.assertEqual(results[0].name, suppliers[0].name)
def test_find_supplier(self): """ Find a Supplier by ID """ suppliers = SupplierFactory.create_batch(3) for supplier in suppliers: supplier.create() logging.debug(suppliers) # make sure they got saved self.assertEqual(len(Supplier.all()), 3) # find the 2nd supplier in the list supplier = Supplier.find(suppliers[1].id) self.assertIsNot(supplier, None) self.assertEqual(supplier.id, suppliers[1].id) self.assertEqual(supplier.name, suppliers[1].name) self.assertEqual(supplier.category, suppliers[1].category) self.assertEqual(supplier.email, suppliers[1].email) self.assertEqual(supplier.address, suppliers[1].address) self.assertEqual(supplier.phone_number, suppliers[1].phone_number)
def test_find_by_phone_number(self): """ Find Suppliers by phone_number """ suppliers = SupplierFactory.create_batch(3) for supplier in suppliers: supplier.create() results = Supplier.find_by_phone_number(suppliers[0].phone_number) self.assertNotEqual(results, []) self.assertEqual(results[0].phone_number, suppliers[0].phone_number)
def preferred_suppliers(supplier_id): """ Marking a supplier preferred """ supplier = Supplier.find(supplier_id) if not supplier: abort(status.HTTP_404_NOT_FOUND, "Supplier with id '{}' was not found.".format(supplier_id)) supplier.preferred = "true" supplier.save() return make_response(jsonify(supplier.serialize()), status.HTTP_200_OK)
def get_suppliers(supplier_id): """ Retrieve a single Supplier This endpoint will return a Supplier based on it's id """ app.logger.info("Request for Supplier with id: %s", supplier_id) supplier = Supplier.find_or_404(supplier_id) return make_response(jsonify(supplier.serialize()), status.HTTP_200_OK)
def get(self, productId): """ Recommend a supplier given a product id""" app.logger.info('Recommend suppliers') suppliers = Supplier.action_make_recommendation(productId) if len(suppliers) <= 0: return api.abort(status.HTTP_404_NOT_FOUND, 'Supplier Not Found') app.logger.info('[%s] suppliers returned', len(suppliers)) results = [json.loads(supplier.to_json()) for supplier in suppliers] return results, status.HTTP_200_OK
def test_serialize_a_supplier(self): """ Serialize a Supplier """ supplier = Supplier("supplier1", 2, True, [1, 2, 3], 8.5) supplier.id = 1 data = supplier.serialize() self.assertNotEqual(data, None) self.assertIn('_id', data) self.assertEqual(data['_id'], 1) self.assertIn('name', data) self.assertEqual(data['name'], "supplier1") self.assertIn('like_count', data) self.assertEqual(data['like_count'], 2) self.assertIn('is_active', data) self.assertEqual(data['is_active'], True) self.assertIn('products', data) self.assertEqual(data['products'], [1, 2, 3]) self.assertIn('rating', data) self.assertEqual(data['rating'], 8.5)
def test_update_a_supplier_with_wrong_id(self): """ Update a Supplier with wrong Id""" supplier = SupplierFactory() supplier.id = "0" self.assertEqual(supplier.id, "0") # Call save() with wrong Id, will call update(), nothing will happen supplier.save() # Fetch suppliers and make sure nothing exists in DB suppliers = Supplier.all() self.assertEqual(len(suppliers), 0)
def delete_suppliers(supplier_id): """ Delete a Supplier This endpoint will delete a Supplier based the id specified in the path """ app.logger.info("Request to delete supplier with id: %s", supplier_id) suppliers = Supplier.find(supplier_id) if suppliers: suppliers.delete() return make_response("", status.HTTP_204_NO_CONTENT)
def get_suppliers_products(supplier_id): """ Retrieve a single Supplier's prpoducts This endpoint will return a Supplier's products based on Supplier's id """ app.logger.info("Request for Supplier's products for id: %s", supplier_id) supplier = Supplier.find_or_404(supplier_id) results = supplier.products products = [product.serialize() for product in results] return make_response(jsonify(products), status.HTTP_200_OK)
def test_find_or_404_found(self): """ Find or return 404 found """ suppliers = SupplierFactory.create_batch(3) for supplier in suppliers: supplier.create() supplier = Supplier.find_or_404(suppliers[1].id) self.assertIsNot(supplier, None) self.assertEqual(supplier.id, suppliers[1].id) self.assertEqual(supplier.name, suppliers[1].name)
def test_find_or_404(self): """ Find or throw 404 error """ supplier = self._create_supplier() supplier.create() # Assert that it was assigned an id and shows up in the database self.assertEqual(supplier.id, 1) # Fetch it back supplier = Supplier.find_or_404(supplier.id) self.assertEqual(supplier.id, 1)