def test_an_item_is_created_successfully(self): self.assertTrue(self.user.save()) user = User.query.filter_by(email=self.user.email).first() self.assertIsNotNone(user) self.assertEqual(user.email, self.user.email) shoppinglist = ShoppingList(user.id, "groceries", "2017-12-28") self.assertEqual(shoppinglist.name, "groceries") self.assertEqual(shoppinglist.notify_date.strftime("%Y-%m-%d"), "2017-12-28") # until the shoppinglist is saved, its ID is None self.assertIsNone(shoppinglist.id) shoppinglist.save() queried_list = ShoppingList.query.filter_by(name="groceries").first() self.assertEqual(queried_list.name, shoppinglist.name) self.assertIsNotNone(shoppinglist.id) self.assertEqual(shoppinglist.user_id, user.id) item = Item(shoppinglist.id, "cabbages", "2", "5,000/=") self.assertIsNotNone(item) self.assertFalse(item.has_been_bought) self.assertIsNone(item.id) self.assertEqual(item.name, "cabbages") self.assertEqual(item.price, "5,000/=") self.assertEqual(item.quantity, "2") self.assertEqual(item.shoppinglist_id, shoppinglist.id) item.save() self.assertIsNotNone(item.id)
def test_new_item(self): list1 = ShoppingList('bucket 1', 'sammy', '528drrdd9540dab149eceedb14', _id=None) list1.new_item('dancing in town', '5', date=datetime.datetime.utcnow()) result = self.data.get_the_data('528drrdd9540dab149eceedb14', self.data.items) self.assertIsInstance(result, list)
def create_shopping_list(): form = ShoppingListForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): shopping_list = ShoppingList( name=form.data['name'], user_id=form.data['user_id'] ) db.session.add(shopping_list) db.session.commit() return {shopping_list.id: shopping_list.to_dict()} return {'errors': validation_errors_to_error_messages(form.errors)}
def post_shopping_list(): """ Insert shopping_list """ data = json.loads(request.data) if 'user_id' in data and 'item' in data and 'quantity' in data: user_id = int(data['user_id']) item = ''.join(str(e) for e in data['item']) quantity = int(data['quantity']) ShoppingList.create(user_id=user_id, item=item, quantity=quantity) return make_response(jsonify({'success':True,'result':'Shopping List Created'}), 201) else: return make_response(jsonify({'success':False,'result':'Incomplete parameters'}), 400)
def test_shoppinglist_is_created_successfully(self): self.assertTrue(self.user.save()) user = User.query.filter_by(email=self.user.email).first() self.assertIsNotNone(user) self.assertEqual(user.email, self.user.email) shoppinglist = ShoppingList(user.id, "groceries", "2018-1-28") self.assertEqual(shoppinglist.name, "groceries") self.assertEqual(shoppinglist.notify_date.strftime("%Y-%m-%d"), "2018-01-28") # until the shoppinglist is saved, its ID is None self.assertIsNone(shoppinglist.id) shoppinglist.save() queried_list = ShoppingList.query.filter_by(name="groceries").first() self.assertEqual(queried_list.name, shoppinglist.name) self.assertIsNotNone(shoppinglist.id) self.assertEqual(shoppinglist.user_id, user.id)
def get_shopping_list(id): """ Fetch shopping_list """ query = ShoppingList.objects(user_id=int(id)) if query.count > 0: data = {'results': []} i = 0 for instance in query: data['results'].append({ 'id': instance.id, 'user_id': instance.user_id, 'item': instance.item, 'quantity': instance.quantity, 'created_at': instance.created_at }) i += 1 if i == query.count(): return make_response( jsonify({ 'success': True, 'results': data['results'] }), 200) else: return make_response(jsonify({'success': True, 'results': []}), 204)
def test__shopping_list_item(self): """ Unittest ShoppingListItems model :return: """ shopping_list = ShoppingList(title='test_title', store_name='test_store') db.session.add(shopping_list) db.session.commit() shopping_list_item = ShoppingListItems(shopping_list_id=1, item_id=1, quantity=1, actual_item_price=100, discount_percentage=10, discount_per_item=10, discounted_item_price=90, actual_total_price=100, discounted_total_price=90) db.session.add(shopping_list_item) db.session.commit() self.assertTrue( ShoppingListItems.query.filter_by(shopping_list_id=1, item_id=1).first() is not None)
def update_shopping_list(id): """ Update shopping_list """ if _validate_uuid4(id): data = json.loads(request.data) if hasattr(data, 'item'): item = ''.join(str(e) for e in data['item']) ShoppingList.iff(id=id).update(item=item) if hasattr(data, 'quantity'): quantity = int(data['quantity']) ShoppingList.iff(id=id).update(quantity=quantity) return make_response(jsonify({'success':True,'result':'Shopping list updated'}), 205) else: return make_response(jsonify({'success':False,'result':'Invalid shopping list id'}), 400)
def post(): """Adds a new shoppinglist to the currently logged in user account""" user_id, message, status, status_code, _ = parse_auth_header(request) if user_id is None: return jsonify({"status": status, "message": message}), status_code # prevents errors due to empty string names name = request.form.get("name") notify_date = request.form.get("notify_date") name = name.strip() if name else "" notify_date = notify_date.strip() if notify_date else "" if name and notify_date: name = name.lower() name_already_exists = ShoppingList.query.filter( ShoppingList.user_id == user_id).filter( ShoppingList.name == name).all() if name_already_exists: return jsonify({ "status": "failure", "message": f"a shopping list with name '{name}' already exists" }), 409 date_string, message = parse_notify_date(notify_date) if date_string is None: return jsonify({ "status": "failure", "message": message, }), 400 shoppinglist = ShoppingList(user_id, name, date_string) shoppinglist.save() return jsonify({ "status": "success", "message": f"'{shoppinglist.name}' successfully created" }), 201 return jsonify({ "status": "failure", "message": "'name' and 'notify_date' of the shoppinglist are required fields" }), 400
def setUp(self): self.app = create_app(config_name="testing") self.user = Users(username="******", email="*****@*****.**", password="******") self.shoppinglist = ShoppingList(owner_id="1", title="Yellow Bananas", description="*****@*****.**") self.shoppinglistitem = ShoppingListItem(owner_id="1", shoppinglist_id="1", item_title="Yellow Bananas with green", item_description="And maracuja") self.usertoken = UserToken(token="a_certain_token") with self.app.app_context(): # create all tables db.create_all()
def delete_shopping_list(id): """ Delete shopping_list """ if _validate_uuid4(id): query = ShoppingList.get(id=id) query.delete() return make_response(jsonify({'success':True,'result':'Shopping list deleted'}), 204) else: return make_response(jsonify({'success':False,'result':'Invalid shopping list id'}), 400)
def post(self): user_id = middleware() if isinstance(user_id, int): post_data = ['title', 'description'] for arg in range(len(post_data)): parser.add_argument(post_data[arg]) args = parser.parse_args() title = args['title'] description = args['description'] valid_title = is_valid(value=title, min_length=10, _type="text") valid_description = is_valid(value=description, min_length=10, _type="text") if valid_title is True and valid_description: check_exists = ShoppingList.query.filter_by( title=title).first() if check_exists is None: shoppinglist = ShoppingList(title=title, description=description, owner_id=user_id) shoppinglist.save_shoppinglist() # Return Response response = { 'id': shoppinglist.id, 'owner': shoppinglist.owner_id, 'title': shoppinglist.title, 'description': shoppinglist.description, 'message': 'Shopping List created successfuly' } return response, 201 response = { 'message': 'Shopping List {} already exists'.format(title) } return response, 202 response = {'message': valid_title} return response, 202 else: return user_id
def test__shopping_list(self): """ Unittest ShoppingList model :return: """ shopping_list = ShoppingList(title='test_title', store_name='test_store') db.session.add(shopping_list) db.session.commit() self.assertTrue( ShoppingList.query.filter_by( title='test_title').first() is not None)
def post_shopping_list(): """ Insert shopping_list """ data = json.loads(request.data) if 'user_id' in data and 'item' in data and 'quantity' in data: user_id = int(data['user_id']) item = ''.join(str(e) for e in data['item']) quantity = int(data['quantity']) ShoppingList.create(user_id=user_id, item=item, quantity=quantity) return make_response( jsonify({ 'success': True, 'result': 'Shopping List Created' }), 201) else: return make_response( jsonify({ 'success': False, 'result': 'Incomplete parameters' }), 400)
def create_list(current_user): """ This route enables a user to create a shoppinglist """ data = request.get_json() if not data['name']: return make_response(jsonify({"message": "Name field required"})), 400 new_shoppinglist = ShoppingList.query.filter_by(name=data['name']).first() if new_shoppinglist: return jsonify({'message': 'list already exists'}), 400 new_list = ShoppingList(name=data['name'], user_id=current_user) db.session.add(new_list) db.session.commit() return jsonify({'message': 'list added'}), 201
def update_shopping_list(id): """ Update shopping_list """ if _validate_uuid4(id): data = json.loads(request.data) if hasattr(data, 'item'): item = ''.join(str(e) for e in data['item']) ShoppingList.iff(id=id).update(item=item) if hasattr(data, 'quantity'): quantity = int(data['quantity']) ShoppingList.iff(id=id).update(quantity=quantity) return make_response( jsonify({ 'success': True, 'result': 'Shopping list updated' }), 205) else: return make_response( jsonify({ 'success': False, 'result': 'Invalid shopping list id' }), 400)
def add_shopping_list(title, store_name): """ This method will add a new shopping list. If shopping list already exist then will return null :param title: :param store_name: :return: shopping_list_id """ shopping_list = ShoppingList.query.filter_by( title=title, store_name=store_name).first() if shopping_list is None: shopping_list = ShoppingList(title=title, store_name=store_name) db.session.add(shopping_list) db.session.commit() else: return "" return shopping_list.id
class TestShoppinglistModel(TestCase): """ Class containing tests for ShoppingList Model """ def setUp(self): self.shoppinglist_instance = ShoppingList('groceries') def tearDown(self): del self.shoppinglist_instance def test_shoppinglist_instance(self): """Test instantiation of shoppinglist objects""" self.assertEqual( self.shoppinglist_instance.get_details(), { "name": "groceries", "items": [] }, )
def delete_shopping_list(id): """ Delete shopping_list """ if _validate_uuid4(id): query = ShoppingList.get(id=id) query.delete() return make_response( jsonify({ 'success': True, 'result': 'Shopping list deleted' }), 204) else: return make_response( jsonify({ 'success': False, 'result': 'Invalid shopping list id' }), 400)
def get_shopping_list(id): """ Fetch shopping_list """ query = ShoppingList.objects(user_id=int(id)) if query.count > 0: data = { 'results' : [] } i = 0 for instance in query: data['results'].append({ 'id' : instance.id, 'user_id' : instance.user_id, 'item' : instance.item, 'quantity' : instance.quantity, 'created_at' : instance.created_at }) i += 1 if i == query.count(): return make_response(jsonify({'success':True,'results':data['results']}), 200) else: return make_response(jsonify({'success':True,'results':[]}), 204)
def create_list(usr_id): """This function given creates a ShoppingList object with the title as the string passed.""" form = NewListForm() if form.validate_on_submit(): new_list = ShoppingList(form.name.data, usr_id) if new_list: db.session.add(new_list) db.session.commit() response = jsonify({ 'MSG': 'Successfully created list', 'list_id': new_list.id }) response.status_code = 201 else: response = jsonify({'ERR': 'List was not created.'}) response.status_code = 400 else: response = jsonify({'ERR': form.errors}) response.status_code = 422 return response
def view_all_lists(usr_id): """This function displays all of a User's ShoppingLists. """ try: page = int(request.args.get("page")) except Exception as e: print(str(e)) page = 1 if request.args.get("q"): all_sh_lists = ShoppingList.search(request.args.get("q"), usr_id, page) if all_sh_lists['lists']: response = jsonify({ 'lists': [obj.serialize for obj in all_sh_lists['lists']], 'number_of_pages': all_sh_lists['number_of_pages'] }) response.status_code = 200 return response else: response = jsonify({'ERR': 'List does not exist.'}) response.status_code = 404 return response else: all_sh_lists = ShoppingList.query.filter_by(user_id=usr_id) limit = int(10) lists = all_sh_lists.paginate(page, limit).items lists = [obj.serialize for obj in lists] count = len(all_sh_lists.all()) if len(lists) != 0: response = jsonify({ 'lists': lists, 'number_of_pages': math.ceil(count / limit) }) response.status_code = 200 else: response = jsonify({'ERR': 'No lists found.', 'id': usr_id}) response.status_code = 404 return response
def shoppinglists(user_id): """ API that GET and POST shopping lists. """ #Pagination arguments: Setting page to 1, then min_per_page to 20 and max_per_page to 100 page = request.args.get('page', 1, type=int) limit = request.args.get('limit', 5, type=int) limit = limit if limit <= 20 else 20 if request.method == "POST": listname = str(request.data["listname"]).lower() if not re.match(r"(?=^.{1,}$)^[A-Za-z0-9_-]+( +[A-Za-z0-9_-]+)*$", listname): response = jsonify({ 'message': 'listname should contain letters, digits and with a min length of 1' }) response.status_code = 400 return response list_exists = ShoppingList.query.filter_by( created_by=user_id).filter_by(listname=listname).first() if not list_exists: shoppinglist = ShoppingList(listname=listname, created_by=user_id) shoppinglist.save() response = jsonify({ 'list_id': shoppinglist.list_id, 'listname': shoppinglist.listname, 'created_by': shoppinglist.created_by }) return { 'message': 'shoppinglist with name {} successfully created'.format( shoppinglist.listname) }, 201 else: response = jsonify( {'message': 'shoppinglist with that name already exists.'}) response.status_code = 409 return response elif request.method == "GET": results = [] q = request.args.get('q') if q: shopping_lists = ShoppingList.query.filter_by( created_by=user_id).filter( ShoppingList.listname.like('%{0}%'.format(q))) else: shopping_lists = ShoppingList.query.filter_by(created_by=user_id) if shopping_lists: pagination = shopping_lists.paginate(page, per_page=limit, error_out=False) shop_lists = pagination.items if pagination.has_prev: prev = url_for('home.shoppinglists', page=page - 1, limit=limit, _external=True) else: prev = None if pagination.has_next: next = url_for('home.shoppinglists', page=page + 1, limit=limit, _external=True) else: next = None if shop_lists: for shoppinglist in shop_lists: obj = { 'list_id': shoppinglist.list_id, 'listname': shoppinglist.listname } results.append(obj) response = jsonify({ 'shoppinglists': results, 'prev': prev, 'next': next, 'count': pagination.total }) response.status_code = 200 return response else: return {'message': 'No shopping lists to display'}, 404 else: shopping_lists = ShoppingList.query.filter_by(created_by=user_id) if shopping_lists: for item in shopping_lists: item.delete() response = jsonify( {'message': 'All shopping lists successfully deleted'}) response.status_code = 200 return response else: return {'message': 'No shopping lists to delete'}, 404
def setUp(self): self.shoppinglist_instance = ShoppingList('groceries')
def shopping_lists(): # were adding a shopping list if request.method == "POST": form = ShoppingListForm() # the form was properly filled if form.validate_on_submit(): # create the list list = ShoppingList(form.name.data, session["user"]) try: list.save() # retrieve the list and send it back to the user list = ShoppingList.query.filter_by( name=form.name.data, user_id=session["user"]).first() response = jsonify(list.serialize) response.status_code = 201 except exc.IntegrityError: response = jsonify( { "error": "The list : '" + form.name.data + "' already exists, please change the name" }) response.status_code = 406 return response # the form was not properly filled, return an error message else: response = jsonify({"error": form.errors}) response.status_code = 422 return response # we want to see all the shopping lists elif request.method == "GET": count = ShoppingList.query.filter_by( user_id=session["user"]).count() if request.args.get("q"): count = ShoppingList.query.filter_by( user_id=session["user"]).filter( ShoppingList.name.like( "%"+request.args.get("q").strip()+"%")).count() # get all the lists and send them to the user response = jsonify({ "lists": [i.serialize for i in ShoppingList.get_all( session["user"], request.args.get("q"), request.args.get("limit"), request.args.get("page"))], "count": count }) response.status_code = 200 return response