def validate_page_size(self, value, **kwargs):
     if value <= 0:
         raise ValidationError(
             "'page_size' must be a natural positive number.")
     elif value > 100:
         raise ValidationError(
             "'page_size' must be a natural positive number.")
Exemple #2
0
    def post(self, ftype, arg, page):
        """Finder products paginated by 'search query', 'kind' or 'brand'"""
        try:
            if ftype not in self.__finder_types:
                raise ValidationError(
                    "'%s' is an invalid URL finder type. Valid: 'search', 'brand' and 'kind'"
                    % ftype)
            if page <= 0:
                raise ValidationError(
                    "'%s' is an invalid URL page value. It must be a positive natural number"
                    % page)
            else:
                in_data = SearchProductsRequest.parse_json()
                req = post("%s/api/%s/%s/%s" % (self.__url, ftype, arg, page),
                           headers=self.__headers,
                           json=in_data)
                req.raise_for_status()

                if req.status_code == 204:
                    raise NoContentError()
                else:
                    jsonsend = SearchProductsResultsResponse.marshall_json(
                        req.json())
                    return jsonsend
        except Exception as error:
            return ErrorHandler(error).handle_error()
Exemple #3
0
 def validate_prices(self, data, **kwargs):
     valmin = data["min"]
     valmax = data["max"]
     if valmin <= 0.0:
         raise ValidationError("Invalid min '%s', must be positive" %
                               valmin)
     elif valmax <= 0.0:
         raise ValidationError("Invalid max '%s', must be positive" %
                               valmax)
     elif valmax < valmin:
         raise ValidationError("Max '%s' cannot be lower than min '%s'" %
                               (valmax, valmin))
Exemple #4
0
    def post(self, item_id, amount):
        """Item add or update."""
        try:
            if amount <= 0:
                raise ValidationError("'%s' is an invalid item amount. It must be a positive natural number" % amount)
            else:
                item_dict = self.__cartservice.to_dict()
                item_dict.update({item_id: amount})
                item_list = [{"item_id": key, "amount": value} for key, value in item_dict.items()]
                items_info = {"item_list": item_list}

                req = post("%s/api/product/list" % (self.__url), headers=self.__headers, json=items_info)
                req.raise_for_status()
                result = req.json()

                self.__cartservice.update_item(item_id, amount)

                for item in item_list:
                    product = next(p for p in result["products"] if p["id"] == item["item_id"])
                    product["amount"] = item["amount"]

                jsonsend = CartResponse.marshall_json(dict(**result))
                return jsonsend
        except Exception as error:
            return ErrorHandler(error).handle_error()
Exemple #5
0
    def select_by_item_list(self, item_list) -> Tuple[List[Product], dict]:
        item_id_list = [item["item_id"] for item in item_list]
        s = Product.search(using=self.es)
        s = s[:len(item_list)]
        s = s.filter("terms", _id=item_id_list)
        results = s.execute()
        products_id = [product.meta["id"] for product in results]
        for p_id in item_id_list:
            if p_id not in products_id:
                raise ValidationError("Product id '%s' not registered." % p_id)

        total = {
            "outlet": 0.0,
            "retail": 0.0,
            "symbol": results[0].price.get_dict()["symbol"]
        }

        for item in item_list:
            product = next(p for p in results
                           if p.meta["id"] == item["item_id"])
            amount = item["amount"]
            total["outlet"] += round(product.price.outlet * amount, 2)
            total["retail"] += round(product.price.retail * amount, 2)

        return results, total
Exemple #6
0
    def post(self, ftype, arg):
        """Finder information by 'search query', 'kind' or 'brand'"""
        try:
            if ftype not in self.__finder_types:
                raise ValidationError(
                    "'%s' is an invalid URL finder type. Valid: 'search', 'brand' and 'kind'"
                )
            else:
                in_data = SearchRequest.parse_json()
                req = post("%s/api/%s/%s" % (self.__url, ftype, arg),
                           headers=self.__headers,
                           json=in_data)
                req.raise_for_status()

                if req.status_code == 204:
                    raise NoContentError()
                else:
                    jsonsend = SearchResultsResponse.marshall_json(req.json())
                    return jsonsend
        except Exception as error:
            return ErrorHandler(error).handle_error()
Exemple #7
0
    def put(self):
        """Make an order based on the cart items."""
        try:
            try:
                item_list = self.__cartservice.to_list()
            except NoContentError:
                raise ValidationError("Cart is empty")

            json_order = {
                "user_slug": current_user.uuid_slug,
                "item_list": item_list
            }

            req = put("%s/api/order/insert" % (self.__url),
                      headers=self.__headers,
                      json=json_order)
            req.raise_for_status()

            self.__cartservice.empty()

            return {}, 201
        except Exception as error:
            return ErrorHandler(error).handle_error()
Exemple #8
0
    def post(self, sessionid, page):
        """Session products paginated"""
        try:
            if page <= 0:
                raise ValidationError(
                    "'%s' is an invalid URL page value. It must be a positive natural number"
                    % page)
            else:
                in_data = SearchProductsRequest.parse_json()
                req = post("%s/api/session/%s/%s" %
                           (self.__url, sessionid, page),
                           headers=self.__headers,
                           json=in_data)
                req.raise_for_status()

                if req.status_code == 204:
                    raise NoContentError()

                jsonsend = SearchProductsResultsResponse.marshall_json(
                    req.json())
                return jsonsend
        except Exception as error:
            return ErrorHandler(error).handle_error()
Exemple #9
0
 def validate_id_list(self, value):
     if not value:
         raise ValidationError("item_list cannot be an empty list.")
Exemple #10
0
 def validate_amount(self, value):
     if value <= 0:
         raise ValidationError("Invalid amount '%s', must be positive" %
                               value)
 def validate_item_list(self, data):
     item_id_list = [item["item_id"] for item in data]
     if len(item_id_list) != len(set(item_id_list)):
         raise ValidationError("item_list must have unique item_id values")
    invalid_amount = deepcopy(request_json)
    invalid_amount["item_list"][0].update(amount=0)

    with login_disabled_app.test_client() as client:
        response = client.post("api/product/list", json=invalid_amount)

    data = json.loads(response.data)
    ErrorSchema().load(data)
    assert response.status_code == 400


@pytest.mark.parametrize(
    "method,http_method,test_url,error,status_code",
    [("select_by_item_list", "POST", "/api/product/list",
      ValidationError("test"), 400),
     ("select_by_item_list", "POST", "/api/product/list",
      ElasticsearchException(), 504),
     ("select_by_item_list", "POST", "/api/product/list",
      ElasticsearchDslException(), 504),
     ("select_by_item_list", "POST", "/api/product/list", Exception(), 500)])
def test_kind_products_controller_error(mocker, get_request_function,
                                        request_json, method, http_method,
                                        test_url, error, status_code):
    with mocker.patch.object(ProductService, method, side_effect=error):
        make_request = get_request_function(http_method)

        response = make_request(test_url, json=request_json)

        data = json.loads(response.data)
        ErrorSchema().load(data)
    with login_disabled_app.test_client() as client:
        response = client.post(
            "api/product/total",
            json=invalid_amount
        )

    data = json.loads(response.data)
    ErrorSchema().load(data)
    assert response.status_code == 400


@pytest.mark.parametrize(
    "method,http_method,test_url,error,status_code",
    [
        ("select_by_item_list", "POST", "/api/product/total", ValidationError("test"), 400),
        ("select_by_item_list", "POST", "/api/product/total", ElasticsearchException(), 504),
        ("select_by_item_list", "POST", "/api/product/total", ElasticsearchDslException(), 504),
        ("select_by_item_list", "POST", "/api/product/total", Exception(), 500)
    ]
)
def test_kind_products_controller_error(mocker, get_request_function, request_json, method, http_method, test_url, error, status_code):
    with mocker.patch.object(ProductService, method, side_effect=error):
        make_request = get_request_function(http_method)

        response = make_request(
            test_url,
            json=request_json
        )

        data = json.loads(response.data)
Exemple #14
0
 def validate_amount(self, data):
     if data <= 0:
         raise ValidationError("product item amount must be a natural positive number")
Exemple #15
0
 def validate_datespan(self, data, **kwargs):
     if data["start"] > data["end"]:
         raise ValidationError("'start' has to be a date prior to 'end'")
 def validate_pagesize(self, value):
     if value <= 0:
         raise ValidationError("Invalid pagesize '%s', must be positive" % value)