def post(self, item_id): """Item removal.""" try: self.__cartservice.remove_item(item_id) item_list = self.__cartservice.to_list() if item_list == []: raise NoContentError() else: 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() 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()
def select(self, query=None, gender=None, sessionid=None, sessionname=None, brand=None, kind=None, pricerange=None, page=1, pagesize=10) -> List[Product]: s = self.__search(query=query, gender=gender, sessionid=sessionid, sessionname=sessionname, brand=brand, kind=kind, pricerange=pricerange) beginpage = (page - 1) * pagesize endpage = page * pagesize s = s[beginpage:endpage] results = s.execute() if not results: raise NoContentError() else: return results
def super_discounts(self, gender=None, amount=10) -> List[Product]: s = Product.search(using=self.es) s = s[:amount] if gender is not None: s = s.filter("term", gender=gender.lower()) s = s.query({ "range": { "price.retail": { "gt": 0.0 } } }).query({"range": { "price.outlet": { "gt": 0.0 } }}) s = s.sort({ "_script": { "type": "number", "script": "(1.0 - (doc['price.outlet'].value / " "doc['price.retail'].value)) * 100", "order": "desc" } }) results = s.execute() if not results: raise NoContentError() else: return results
def select_pricerange(self, query=None, gender=None, sessionid=None, sessionname=None, brand=None, kind=None) -> dict: s = self.__search(query=query, gender=gender, sessionid=sessionid, sessionname=sessionname, brand=brand, kind=kind) s = s[:1] s.aggs.metric("minprice", "min", field="price.outlet") s.aggs.metric("maxprice", "max", field="price.outlet") results = s.execute() if not results: raise NoContentError() else: return { "min": round(results.aggs.minprice.value, 2), "max": round(results.aggs.maxprice.value, 2) }
def select_kinds(self, query=None, gender=None, sessionid=None, sessionname=None, brand=None, kind=None, pricerange=None) -> List[dict]: s = self.__search(query=query, gender=gender, sessionid=sessionid, sessionname=sessionname, brand=brand, kind=kind, pricerange=pricerange) s = s[:0] s.aggs.bucket("kinds", "terms", field="kind.keyword", size=2147483647) results = s.execute() if not results.aggs.kinds.buckets: raise NoContentError() else: return [{ "kind": hit.key, "amount": hit.doc_count } for hit in results.aggs.kinds.buckets]
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()
def select_by_user_slug(self, user_slug: str, page: int = 1, page_size: int = 10, datespan: dict = None) -> dict: try: user_uuid = slug_to_uuid(user_slug) search_query = self.db_session.query(Order).filter( Order.user_uuid == user_uuid) if datespan is not None: search_query = search_query.filter( and_( Order.updated_at >= datespan["start"], Order.updated_at < datespan["end"] + timedelta(days=1))) data = search_query.order_by( Order.updated_at.desc()).limit(page_size).offset( (page - 1) * page_size).all() total = search_query.order_by(None).count() pages = ceil(total / page_size) if not data: raise NoContentError() return {"orders": data, "total": total, "pages": pages} except DataError: self.db_session.rollback() raise
def test_order_controller_empty_cart(mocker, login_disabled_app): mocker.patch.object(CartService, "to_list", side_effect=NoContentError()) with login_disabled_app.test_client() as client: response = client.put("api/cart/order") data = json.loads(response.data) ErrorSchema().load(data) assert response.status_code == 400
def post(self, gender="Men"): """Gender information.""" try: in_data = GenderRequest.parse_json() req = post("%s/api/gender/%s" % (self.__url, gender), headers=self.__headers, json=in_data) req.raise_for_status() if req.status_code == 204: raise NoContentError() jsonsend = GenderResultsResponse.marshall_json(req.json()) return jsonsend except Exception as error: return ErrorHandler(error).handle_error()
def post(self): """Orders for the logged in user.""" try: in_data = UserOrdersRequest.parse_json() user_slug = current_user.uuid_slug req = post("%s/api/order/user/%s" % (self.__url, user_slug), headers=self.__headers, json=in_data) req.raise_for_status() if req.status_code == 204: raise NoContentError() else: jsonsend = UserOrdersResponse.marshall_json(req.json()) return jsonsend except Exception as error: return ErrorHandler(error).handle_error()
def post(self, sessionid): """Session information.""" try: in_data = SearchRequest.parse_json() req = post("%s/api/session/%s" % (self.__url, sessionid), headers=self.__headers, json=in_data) req.raise_for_status() if req.status_code == 204: raise NoContentError() jsonsend = SessionResultsResponse.marshall_json(req.json()) return jsonsend except Exception as error: return ErrorHandler(error).handle_error()
def select(self, gender=None, name=None) -> List[dict]: s = Session.search(using=self.es) s = s[:10000] if gender is not None: s = s.filter("term", gender=gender.lower()) if name is not None: s = s.query("match_phrase", name=name) results = s.execute() if not results: raise NoContentError() else: sessions = [] for hit in results: sdict = hit.get_dict() total = self.__count_products(hit.meta["id"]) sdict["total"] = total sessions.append(sdict) return sessions
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()
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()
with login_disabled_app.test_client() as client: response = client.post( "api/session/test/1", json=invalid_pagesize ) 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", "POST", "/api/session/test/1", NoContentError(), 204), ("select", "POST", "/api/session/test/1", ElasticsearchException(), 504), ("select", "POST", "/api/session/test/1", ElasticsearchDslException(), 504), ("select", "POST", "/api/session/test/1", Exception(), 500) ] ) def test_start_controller_error(mocker, get_request_function, 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 ) if status_code == 204: with pytest.raises(JSONDecodeError):
assert response.status_code == 400 invalid_amount = deepcopy(request_json) invalid_amount.update(amount=0) with login_disabled_app.test_client() as client: response = client.post("api/gender/test", 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", [("super_discounts", "POST", "/api/gender/test", NoContentError(), 204), ("super_discounts", "POST", "/api/gender/test", ElasticsearchException(), 504), ("super_discounts", "POST", "/api/gender/test", ElasticsearchDslException(), 504), ("super_discounts", "POST", "/api/gender/test", Exception(), 500)]) def test_gender_controller_error(mocker, get_request_function, 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) if status_code == 204: with pytest.raises(JSONDecodeError): json.loads(response.data)
assert response.status_code == 400 invalid_pagesize = deepcopy(request_json) invalid_pagesize.update(pagesize=0) with login_disabled_app.test_client() as client: response = client.post("api/brand/test/1", json=invalid_pagesize) 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", "POST", "/api/brand/test/1", NoContentError(), 204), ("select", "POST", "/api/brand/test/1", ElasticsearchException(), 504), ("select", "POST", "/api/brand/test/1", ElasticsearchDslException(), 504), ("select", "POST", "/api/brand/test/1", Exception(), 500)]) def test_kind_products_controller_error(mocker, get_request_function, 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) if status_code == 204: with pytest.raises(JSONDecodeError): json.loads(response.data) else:
ErrorSchema().load(data) assert response.status_code == 400 invalid_range = deepcopy(request_json) invalid_range["pricerange"].update(min=100.0, max=50.0) with login_disabled_app.test_client() as client: response = client.post("api/brand/test", json=invalid_range) data = json.loads(response.data) ErrorSchema().load(data) assert response.status_code == 400 @pytest.mark.parametrize("method,http_method,test_url,error,status_code", [ ("get_total", "POST", "/api/brand/test", NoContentError(), 204), ("get_total", "POST", "/api/brand/test", ElasticsearchException(), 504), ("get_total", "POST", "/api/brand/test", ElasticsearchDslException(), 504), ("get_total", "POST", "/api/brand/test", Exception(), 500) ]) def test_brand_controller_error(mocker, get_request_function, 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) if status_code == 204: with pytest.raises(JSONDecodeError): json.loads(response.data) else:
ErrorSchema().load(data) assert response.status_code == 400 invalid_pagesize = deepcopy(request_json) invalid_pagesize.update(pagesize=0) with login_disabled_app.test_client() as client: response = client.post("api/search/test/1", json=invalid_pagesize) 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", "POST", "/api/search/test/1", NoContentError(), 204), ("select", "POST", "/api/search/test/1", ElasticsearchException(), 504), ("select", "POST", "/api/search/test/1", ElasticsearchDslException(), 504), ("select", "POST", "/api/search/test/1", Exception(), 500) ]) def test_search_products_controller_error(mocker, get_request_function, 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) if status_code == 204: with pytest.raises(JSONDecodeError): json.loads(response.data)
with login_disabled_app.test_client() as client: response = client.post( "api/order/user/WILLrogerPEREIRAslugBR", json=overflow_datespan ) 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_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", NoContentError(), 204), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", HTTPException(), 400), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", ConnectionError(), 502), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", DataError("statement", "params", "DETAIL: orig\n"), 400), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", DatabaseError("statement", "params", "orig"), 400), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", SQLAlchemyError(), 504), ("select_by_user_slug", "POST", "api/order/user/WILLrogerPEREIRAslugBR", Exception(), 500) ] ) def test_select_by_user_slug_controller_error(mocker, get_request_function, method, http_method, test_url, error, status_code): mocker.patch.object(OrderService, method, side_effect=error) make_request = get_request_function(http_method) response = make_request( test_url
assert response.status_code == 400 invalid_range = deepcopy(request_json) invalid_range["pricerange"].update(min=100.0, max=50.0) with login_disabled_app.test_client() as client: response = client.post("api/search/test", json=invalid_range) data = json.loads(response.data) ErrorSchema().load(data) assert response.status_code == 400 @pytest.mark.parametrize( "method,http_method,test_url,error,status_code", [("get_total", "POST", "/api/search/test", NoContentError(), 204), ("get_total", "POST", "/api/search/test", ElasticsearchException(), 504), ("get_total", "POST", "/api/search/test", ElasticsearchDslException(), 504), ("get_total", "POST", "/api/search/test", Exception(), 500)]) def test_search_controller_error(mocker, get_request_function, 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) if status_code == 204: with pytest.raises(JSONDecodeError): json.loads(response.data) else: data = json.loads(response.data)
with login_disabled_app.test_client() as client: response = client.post( "api/session/test", json=invalid_range ) 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_id", "POST", "/api/session/test", NoContentError(), 204), ("select_by_id", "POST", "/api/session/test", NotFoundError(), 404), ("select_by_id", "POST", "/api/session/test", ElasticsearchException(), 504), ("select_by_id", "POST", "/api/session/test", ElasticsearchDslException(), 504), ("select_by_id", "POST", "/api/session/test", Exception(), 500) ] ) def test_start_controller_error(mocker, get_request_function, method, http_method, test_url, error, status_code): with mocker.patch.object(SessionService, method, side_effect=error): make_request = get_request_function(http_method) response = make_request( test_url ) if status_code == 204: