def test_create_a_promotion_associated_with_new_product(self): """ Create a promotion which is associated with a product thats not in our db yet""" promotions = Promotion.all() products = Product.all() self.assertEqual(promotions, []) self.assertEqual(products, []) promotion = Promotion( title="test_create", promo_type=PromoType.DISCOUNT, amount=10, start_date=datetime(2020, 10, 17), end_date=datetime(2020, 10, 18), is_site_wide=True, ) product = Product(id=123) promotion.products.append(product) self.assertTrue(product is not None) promotion.create() # Assert that it was assigned an id and shows up in the database self.assertEqual(promotion.id, 1) self.assertEqual(product.id, 123) products = Product.all() promotions = Promotion.all() self.assertEqual(len(products), 1) self.assertEqual(len(promotions), 1)
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) Product.init_db(app) pass
def test_update_a_product_empty_id(self): """ Update a Product with empty id """ product = Product(name="iPhone X", description="Black iPhone", category="Technology", price=999.99) product.create() self.assertEqual(product.id, 1) # Change it and update it product.id = None self.assertRaises(DataValidationError, product.update)
def test_add_a_product_commit_error(self, commit): """ Create a product and raises an InvalidRequestError """ commit.side_effect = InvalidRequestError products = Product.all() self.assertEqual(products, []) product = Product(name="Cake", description="Chocolate Cake", category="Food", price=10.50) self.assertTrue(product is not None) self.assertEqual(product.id, None) product.create() self.assertEqual(products, [])
def create_products(order_id): """ Create an Product on an Order This endpoint will add an product to an order """ app.logger.info("Request to add an product to an order") # pylint: disable=maybe-no-member check_content_type("application/json") order = Order.find_or_404(order_id) product = Product() product.deserialize(request.get_json()) order.products.append(product) order.save() message = product.serialize() return make_response(jsonify(message), status.HTTP_201_CREATED)
def test_find_by_description_price(self): """ Find Products by Description and Price """ Product(name="iPhone X", description="Black iPhone", category="Technology", price=9999.99).create() Product(name="Cake", description="Chocolate Cake", category="Food", price=10.50).create() products = Product.find_by_description_price("iPhone", 800, 10000) self.assertEqual(products[0].category, "Technology") self.assertEqual(products[0].name, "iPhone X") self.assertEqual(products[0].description, "Black iPhone") self.assertEqual(products[0].price, 9999.99)
def test_find_by_name_category(self): """ Find Products by Name and Category """ Product(name="iPhone X", description="Black iPhone", category="Technology", price=9999.99).create() Product(name="Cake", description="Chocolate Cake", category="Food", price=10.50).create() products = Product.find_by_name_category("iPhone x", "technology") self.assertEqual(products[0].category, "Technology") self.assertEqual(products[0].name, "iPhone X") self.assertEqual(products[0].description, "Black iPhone") self.assertEqual(products[0].price, 9999.99)
def test_deserialize_bad_data(self): """ Test deserialization of bad data """ data = "this is not a dictionary" product = Product() self.assertRaises(DataValidationError, product.deserialize, data) data = { "id": 1, "name": "iPhone X", "description": "Black iPhone", "category": "Technology", "price": "a" } product = Product() self.assertRaises(DataValidationError, product.deserialize, data)
def create_products(supplier_id): """ Create a Product on a Supplier This endpoint will add a product to a supplier """ app.logger.info("Request to add an product to an supplier") check_content_type("application/json") supplier = Supplier.find_or_404(supplier_id) product = Product() product.deserialize(request.get_json()) supplier.products.append(product) supplier.save() message = product.serialize() return make_response(jsonify(message), status.HTTP_201_CREATED)
def list_products(): """ Returns all of the Products """ app.logger.info("Request for Product list") products = [] category = request.args.get("category") name = request.args.get("name") if category: products = Product.find_by_category(category) elif name: products = Product.find_by_name(name) else: products = Product.all() results = [product.serialize() for product in products] return make_response(jsonify(results), status.HTTP_200_OK)
def getRecurringProdPrice(self, item, product): print("** getRecurringProdPrice") if item is not None: prices = ProductPrices.objects.filter( Q(product_id__exact=item['id']) & Q(nickname__icontains=item['orderEvery']) ).order_by('-nickname') ## Create Price if not available if len(prices) is 0: price = ProductPrices( product_id = item['id'], price = Product.get_recurring_price( product, item['orderEvery'] ), nickname = item['orderEvery'], recurring_interval = ProductPrices.MONTHLY_RECURRING, ) price.save() prices = [] prices.append(price) return prices else: return None
def test_deserialize_a_product(self): """ Test deserialization of a Product """ data = { "id": 1, "name": "iPhone X", "description": "Black iPhone", "category": "Technology", "price": 999.99 } product = Product() product.deserialize(data) self.assertNotEqual(product, None) self.assertEqual(product.id, None) self.assertEqual(product.name, "iPhone X") self.assertEqual(product.description, "Black iPhone") self.assertEqual(product.category, "Technology") self.assertEqual(product.price, 999.99)
def get_products(order_id, product_id): # pylint: disable=unused-argument """ Get an Product This endpoint returns just an product """ app.logger.info("Request to get an product with id: %s", product_id) # pylint: disable=maybe-no-member product = Product.find_or_404(product_id) return make_response(jsonify(product.serialize()), status.HTTP_200_OK)
def add_product(): name = request.json["name"] price = request.json["price"] odoo_id = request.json["odooId"] start_time = request.json["startTime"] end_time = request.json["endTime"] tokenstr = request.headers["Authorization"] valid_days = request.json["validDay"] file = open("instance/key.key", "rb") key = file.read() file.close() tokenstr = tokenstr.split(" ") token = tokenstr[1] role = jwt.decode(token, key, algorithms=['HS256'])["role"] if role == "SuperAdmin": try: common = xmlrpc.client.ServerProxy(f"{url}xmlrpc/2/common") uid = common.authenticate(database, username, password, {}) models = xmlrpc.client.ServerProxy(f"{url}xmlrpc/2/object") odoo_counterpart = models.execute_kw( database, uid, password, "product.template", "search", [[['id', '=', odoo_id]]], ) if (odoo_counterpart == []): return json.dumps({ 'message': "ID '" + str(odoo_id) + "' does not exist in Odoo" }), 400, { 'ContentType': 'application/json' } else: new_product = Product(name, price, odoo_id, start_time, end_time) db.session.add(new_product) db.session.commit() for i in valid_days: day_of_week = i product_id = new_product.id new_valid_day = ProductValidDay(product_id, day_of_week) db.session.add(new_valid_day) db.session.commit() except exc.IntegrityError: return json.dumps( {'message': "Name '" + name + "' already exists"}), 400, { 'ContentType': 'application/json' } return (json.dumps({'message': 'success'}), 200, { 'ContentType': 'application/json' }) else: return "You are not authorised to perform this action", 400 return product_schema.jsonify(new_product)
def test_serialize_a_product(self): """ Test serialization of a Product """ product = Product(name="iPhone X", description="Black iPhone", category="Technology", price=999.99) data = product.serialize() self.assertNotEqual(data, None) self.assertIn("id", data) self.assertEqual(data["id"], None) self.assertIn("name", data) self.assertEqual(data["name"], "iPhone X") self.assertIn("description", data) self.assertEqual(data["description"], "Black iPhone") self.assertIn("category", data) self.assertEqual(data["category"], "Technology") self.assertIn("price", data) self.assertEqual(data["price"], 999.99)
def get_products(supplier_id, product_id): """ Get a Product This endpoint returns just a product """ app.logger.info("Request to get a product with id: %s", product_id) product = Product.find_or_404(product_id) return make_response(jsonify(product.serialize()), status.HTTP_200_OK)
def _create_product(self): """ Creates fake products from factory """ fake_product = ProductFactory() product = Product(quantity=fake_product.quantity, name=fake_product.name, price=fake_product.price) self.assertTrue(product is not None) self.assertEqual(product.id, None) return product
def test_delete_a_product(self): """ Delete a Product """ product = Product(name="iPhone X", description="Black iPhone", category="Technology", price=999.99) product.create() self.assertEqual(len(Product.all()), 1) # delete the product and make sure it isn't in the database product.delete() self.assertEqual(len(Product.all()), 0)
def test_find_by_name(self): """ Find a Product by Name """ products = ProductFactory.create_batch(3) for product in products: product.create() name = products[0].name test_products = Product.find_by_name(name) self.assertEqual(test_products[0].name, name) self.assertIsNot(test_products[0].name, "KEVIN") self.assertEqual(test_products[0].id, products[0].id)
def _create_product(self): """ Creates fake product from factory """ fake_product = ProductFactory() product = Product(name=fake_product.name, desc=fake_product.desc, wholesale_price=fake_product.wholesale_price, quantity=fake_product.quantity) self.assertTrue(product != None) self.assertEqual(product.id, None) return product
def test_find_or_404_found(self): """ Find or return 404 found """ products = ProductFactory.create_batch(3) for product in products: product.create() product = Product.find_or_404(products[1].id) self.assertIsNot(product, None) self.assertEqual(product.id, products[1].id) self.assertEqual(product.name, products[1].name) self.assertEqual(product.available, products[1].available)
def delete_products(order_id, product_id): """ Delete an Product This endpoint will delete an Product based the id specified in the path """ app.logger.info("Request to delete order with id: %s", order_id) # pylint: disable=maybe-no-member product = Product.find(product_id) if product: product.delete() return make_response("", status.HTTP_204_NO_CONTENT)
def test_find_by_category(self): """ Find Products by Category """ products = ProductFactory.create_batch(3) for product in products: product.create() category = products[0].category test_products = Product.find_by_category(category) self.assertEqual(test_products[0].category, category) self.assertIsNot(test_products[0].category, "kitty") self.assertEqual(test_products[0].id, products[0].id)
def test_find_product(self): """ Find a Product by ID """ products = ProductFactory.create_batch(3) for product in products: product.create() logging.debug(products) # make sure they got saved self.assertEqual(len(Product.all()), 3) # find the 2nd product in the list test_product = Product.find(products[1].id) self.assertIsNot(test_product, None) self.assertEqual(test_product.id, products[1].id) self.assertEqual(test_product.name, products[1].name) self.assertEqual(test_product.available, products[1].available) self.assertEqual(test_product.sku, products[1].sku) self.assertEqual(test_product.price, products[1].price) self.assertEqual(test_product.stock, products[1].stock) self.assertEqual(test_product.size, products[1].size) self.assertEqual(test_product.color, products[1].color) self.assertEqual(test_product.category, products[1].category)
def test_delete_a_product_commit_error(self): """ Delete a Product """ product = Product(name="iPhone X", description="Black iPhone", category="Technology", price=999.99) product.create() self.assertEqual(len(Product.all()), 1) # delete the product and make sure it isn't in the database with patch('service.models.db.session.commit') as commit: commit.side_effect = InvalidRequestError product.delete() self.assertEqual(len(Product.all()), 1)
def get_products(product_id): """ Retrieve a single Product This endpoint will return a product based on it's id """ app.logger.info("Request for product with id: %s", product_id) product = Product.find(product_id) if not product: raise NotFound( "Product with id '{}' was not found.".format(product_id)) return make_response(jsonify(product.serialize()), status.HTTP_200_OK)
def test_restock_a_product(self): """ Restock a Product """ products = ProductFactory.create_batch(1) for product in products: product.create() products[0].available = False products[0].stock = 0 product.save() products = Product.all() self.assertEqual(len(products), 1) self.assertEqual(products[0].id, 1) self.assertEqual(products[0].stock, 0) self.assertEqual(products[0].available, False) product.restock(100) product.save() products = Product.all() self.assertEqual(len(products), 1) self.assertEqual(products[0].id, 1) self.assertEqual(products[0].stock, 100) self.assertEqual(products[0].available, True)
def update_products(order_id, product_id): # pylint: disable=unused-argument """ Update an Product This endpoint will update an Product based the body that is posted """ app.logger.info("Request to update product with id: %s", product_id) # pylint: disable=maybe-no-member check_content_type("application/json") product = Product.find_or_404(product_id) product.deserialize(request.get_json()) product.id = product_id product.save() return make_response(jsonify(product.serialize()), status.HTTP_200_OK)
def delete_products(product_id): """ Delete a Product This endpoint will delete a Product based the id specified in the path """ app.logger.info("Request to delete product with id: %s", product_id) product = Product.find(product_id) if product: product.delete() app.logger.info("Product with ID [%s] delete complete.", product_id) return make_response("", status.HTTP_204_NO_CONTENT)
def test_serialize(self): """ Test serialization of a Promotion """ promotion = Promotion( id=1, title="Halloween Special", description="Some items off in honor of the spookiest month.", promo_code="hween", promo_type=PromoType.DISCOUNT, amount=25, start_date=datetime(2020, 10, 20), end_date=datetime(2020, 11, 1), is_site_wide=True, ) product_1 = Product() product_1.id = 123 promotion.products.append(product_1) product_2 = Product() product_2.id = 456 promotion.products.append(product_2) self.assertEqual( promotion.serialize(), { "id": 1, "title": "Halloween Special", "description": "Some items off in honor of the spookiest month.", "promo_code": "hween", "promo_type": "DISCOUNT", "amount": 25, "start_date": "2020-10-20T00:00:00", "end_date": "2020-11-01T00:00:00", "is_site_wide": True, "products": [123, 456], }, )