def test_get_an_existing_product(self):
      ProductService.addProduct(100, 'Delphix', 100, 'software')
      response=ProductService.getProductDetails(100)
      self.assertEqual(response[0], 100)
      self.assertEqual(response[1], "Delphix")
      self.assertEqual(response[2], 100.0)
      self.assertEqual(response[3], "software")
 def test_download_data_from_a_file(self):
     if os.path.exists("delphix.csv"):
         os.remove("delphix.csv")
     else:
         print("Can not delete the file as it doesn't exists")
     response=ProductService.downloadProductToCSV("delphix.csv")
     self.assertEqual("Successfully downloaded data to file: delphix.csv",response)
class RatingService:
    def __init__(self):
        self.database = database
        self.product = ProductService()
        self.user = UserService()

    def addRating(self, user_id, rating, product_id):
        if self.productAndUserExist(user_id, product_id):
            logger.info(
                "Adding rating for user: {}, product: {}, rating: {}".format(
                    user_id, product_id, rating))
            saved_record = self.database.addRating(user_id, rating, product_id)
            return saved_record
        else:
            logger.error("Product/User does not exist.")
            return None

    def productAndUserExist(self, user_id, product_id):
        product = self.database.getProduct(product_id)
        user = self.database.getUser(user_id)
        if product is not None and user is not None:
            return True
        else:
            return False

    def getRatingsDetailsForProduct(self, params):
        response = {}
        product_id = params['productId']
        response['averageRating'] = self.database.getAverageRating(product_id)
        response['totalRatings'] = self.database.getRatingsCount(product_id)
        response['productDetails'] = self.product.getProductById(product_id)
        if 'userId' in params:
            response['userDetails'] = self.user.getUserById(params['userId'])
            response[
                'loggedInUserRating'] = self.database.getProductRatingForUser(
                    product_id, params['userId'])

        if response['loggedInUserRating'] is None:
            response['loggedInUserRating'] = 0

        ratings = self.database.getRatings(product_id)
        response['ratingsBreakdown'] = self.computeRatingsBreakdown(ratings)
        return response

    def removeRating(self, params):
        return self.database.removeRating(params['userId'],
                                          params['productId'])

    @staticmethod
    def computeRatingsBreakdown(ratings):
        c = Counter(ratings)
        ratings_percentages = dict(
            (i, round(c[i] / len(ratings) * 100, 1)) for i in ratings)
        for i in range(1, 5):
            if i not in ratings_percentages:
                ratings_percentages[i] = 0
        return ratings_percentages
def addProductDetails(productId=None):
    if request.method == 'POST':
        product_id = request.form['product_id']
        product_name = request.form['product_name']
        product_price = request.form['product_price']
        product_category = request.form['product_category']
        data = ProductService.addProduct(product_id, product_name,
                                         product_price, product_category)
        return jsonify(data), 200
 def __init__(self):
     self.database = database
     self.product = ProductService()
     self.user = UserService()
def uploadProduct(file_path=None):
    if request.method == 'POST':
        file_name = request.form['file_path']
        return jsonify(ProductService.uploadProductToMongo(file_name))
def downloadProduct(file_path=None):
    if request.method == 'POST':
        file_name = request.form['file_path']
        return jsonify(ProductService.downloadProductToCSV(file_name))
def deleteProduct(productId=None):
    if request.method == 'POST':
        product_id = request.form['product_id']
        data = ProductService.removeProduct(product_id)
        return jsonify(data), 200
def getProduct(productId=None):
    if request.method == 'POST':
        productId = request.form['product_id']
        data = ProductService.getProductDetails(productId)
        return jsonify(data), 200
# app.py - a minimal flask api using flask_restful
import logging
from flask import Flask, render_template, request, jsonify
from api.v1.urlMappings import api_v1 as api_blueprint
from config.Config import Config
from config.Endpoints import Endpoints
from services.ProductService import ProductService
from core.models.Product import Product

app = Flask(__name__)
app.register_blueprint(api_blueprint, url_prefix=Endpoints.PRODUCT_URL_PREFIX)
logger = logging.getLogger("products")

ProductService = ProductService()


def initializeLogging():
    logging.basicConfig(filename=Config.LOG_FILE,
                        level=logging.DEBUG,
                        format=Config.LOG_PATTERN)
    logger.setLevel(logging.INFO)


@app.route('/get_product')
def get():
    return render_template('product.html')


@app.route('/product_search_result',
           methods=['GET', 'POST', 'DELETE', 'PATCH'])
def getProduct(productId=None):
 def test_upload_data_to_mongo(self):
     response = ProductService.uploadProductToMongo("upload.csv")
     self.assertEqual("Successfully uploaded data to MongoDB from file: upload.csv", response)
 def test_get_an_non_existing_product(self):
      ProductService.removeProduct(100)
      response=ProductService.getProductDetails(100)
      self.assertEqual("Product doesnot exist",response)
 def test_delete_an_non_existing_product(self):
     ProductService.removeProduct(100)
     response = ProductService.removeProduct(100)
     self.assertEqual("Product doesnot exist",response)
 def test_delete_an_existing_product(self):
     ProductService.addProduct(100, 'Delphix', 100, 'software')
     response = ProductService.removeProduct(100)
     self.assertEqual("Successfully removed product: 100",response)
 def test_insert_an_already_existing_product(self):
     ProductService.addProduct(100, 'Delphix', 100, 'software')
     response = ProductService.addProduct(100, 'Delphix', 100, 'software')
     self.assertEqual("Product already exist",response)
 def test_insert_an_new_product(self):
         ProductService.removeProduct(100)
         response=ProductService.addProduct(100, 'Delphix', 100, 'software')
         self.assertEqual("Successfully saved product",response)