def test_deserialize_bad_data2(self, bad_mock): """ Test deserialization of bad data """ data = "this is not a dictionary" bad_mock.side_effect = TypeError() data = {"id": 1, "name": "materials", "category": "widget2", "available": True, "count":1,"condition":"new"} inventory = Inventory() inventory.deserialize(data)
def test_find_by_name(self): """ Find an inventory by Name """ Inventory(name="tools", category="widget1", available=True).save() Inventory(name="materials", category="widget2", available=False).save() inventory = Inventory.find_by_name("tools") self.assertEqual(inventory[0].category, "widget1") self.assertEqual(inventory[0].name, "tools") self.assertEqual(inventory[0].available, True)
def test_find_by_category(self): """ Find an Inventory by Category """ Inventory(name="tools", category="widget1", available=True,condition="new").save() Inventory(name="materials", category="widget2", available=False,condition="old").save() inventory = Inventory.find_by_category("widget1") self.assertEqual(inventory[0].category, "widget1") self.assertEqual(inventory[0].name, "tools") self.assertEqual(inventory[0].available, True) self.assertEqual(inventory[0].condition, "new")
def test_deserialize_a_inventory(self): """ Test deserialization of a Inventory """ data = {"id": 1, "name": "materials", "category": "widget2", "available": True, "count":1,"condition":"new"} inventory = Inventory() inventory.deserialize(data) self.assertNotEqual(inventory, None) self.assertEqual(inventory.id, None) self.assertEqual(inventory.name, "materials") self.assertEqual(inventory.category, "widget2") self.assertEqual(inventory.available, True)
def make_trade(offer_b, offer_s): print("MAKING TRADE ON:", offer_b, offer_s) price_for_item_b = get_item_price(offer_b) price_for_item_s = get_item_price(offer_s) # If buy user's inventory doesn't exist - create if not Inventory.objects.filter(user=offer_b.user, item=offer_b.item).exists(): inv = Inventory(user=offer_b.user, item=offer_b.item, amount=0) inv.save() amount = offer_b.amount if offer_b.amount <= offer_s.amount else offer_s.amount total_price = amount * get_item_price(offer_s) # Making trade trade = Trade(item=offer_b.item, amount=amount, price=total_price, \ seller=offer_s.user, seller_offer=offer_s, buyer=offer_b.user, \ buyer_offer=offer_b) # Offers & inventories amount actions offer_b.amount -= amount offer_s.amount -= amount # Changing inventory amount inventory_b = get_object_or_404(Inventory, user=offer_b.user, item=offer_b.item) inventory_s = get_object_or_404(Inventory, user=offer_s.user, item=offer_s.item) inventory_s.amount -= amount inventory_b.amount += amount # Money actions money_action(offer_b.user, amount, "-") money_action(offer_s.user, amount, "+") # Check if offer is closed if offer_b.amount == 0: offer_b.is_active = False if offer_s.amount == 0: offer_s.is_active = False offer_b.price = offer_b.amount * price_for_item_b offer_s.price = offer_s.amount * price_for_item_s # Saving all data trade.save() offer_b.save() offer_s.save() inventory_b.save() inventory_s.save()
def create_inventory(): data = request.get_json() or {} #mand_fields = ('name') #if not all(field in data for field in mand_fields): if 'name' not in data: return bad_request('Please provide all mandatory fields') inventory = Inventory() inventory.from_dict(data, update_by=token_auth.current_user().email) db.session.add(inventory) db.session.commit() return inventory.to_dict()
def test_delete_a_inventory(self): """ Delete an inventory """ inventory = Inventory(name="tools", category="widget1", available=True,condition="new") inventory.save() self.assertEqual(len(Inventory.all()), 1) # delete the inventory and make sure it isn't in the database inventory.delete() self.assertEqual(len(Inventory.all()), 0)
def test_serialize_a_inventory(self): """ Test serialization of a Inventory """ inventory = Inventory(name="tools", category="widget1", available=False, condition="new") data = inventory.serialize() self.assertNotEqual(data, None) self.assertIn('id', data) self.assertEqual(data['id'], None) self.assertIn('name', data) self.assertEqual(data['name'], "tools") self.assertIn('category', data) self.assertEqual(data['category'], "widget1") self.assertIn('available', data) self.assertEqual(data['available'], False) self.assertIn('condition', data) self.assertEqual(data['condition'], "new")
def setUp(self): """ Will be called before every test """ db.create_all() # create test admin user user = User(name="Rohit", password="******",position="Stuccan",department="controls") # save users to database db.session.add(user) db.session.commit() #create static data if User.query.count()==1: user_id = user.id location = Location(description="ABQ-First") db.session.add(location) db.session.commit() inventory = Inventory(inventory_type="Fist Inv",purchased_by=user_id,location=location.id) db.session.add(inventory) db.session.commit() ticket_types = TicketType(description="First ticket_type") db.session.add(ticket_types) db.session.commit() ticket = Ticket(ticket_type=ticket_types.id,opened_by=user_id,updated_by=user_id,description="First Ticket") db.session.add(ticket) db.session.commit()
def post_inventory(): request_data = request.get_json(force=True, silent=True) if request_data == None: return jsonify({ 'success': 0, 'error': 'request contains invalid information' }) schema = { "type": "object", "properties": { "name": { "type": "string", "pattern": "^.+$" } }, "required": ["name"] } try: jsonschema.validate(schema=schema, instance=request_data) except Exception as e: return jsonify({ 'success': 0, 'error': 'request contains invalid information' }) i = Inventory(name=request_data['name']) # check for unique try: db.session.add(i) db.session.commit() except Exception as e: db.session.rollback() return jsonify({'success': '0', 'error': str(e)}) return jsonify({'success': '1', 'inventory': {'id': i.id, 'name': i.name}})
def inventory(): if request.method == "POST": try: id = int(request.form.get("id")) name = str(request.form.get("name")) except: return "الرجاء التأكد من تعبئة النموذج كاملاً" if None in (id, name): return "الرجاء التأكد من تعبئة النموذج كاملاً" newItem = Inventory(item_Id=id, item_name=name, item_stock=0) db.session.add(newItem) db.session.commit() return "/inventory" else: items = [] query = Inventory.query.order_by(Inventory.item_Id).all() for record in query: items.append({ 'id': record.item_Id, 'name': record.item_name, 'stock': record.item_stock }) print(items) return render_template('inventory.html', items=items)
def inventory_detail(): form = InventoryRecordsForm() if form.validate_on_submit(): asset = Asset.query.filter_by(name=form.asset_name.data).first() assigned_to = User.query.filter_by(name=form.assigned_to_id.data).first() date_bought_string = form.date_bought.data.strftime('%Y/%m/%d') date_assigned_string = form.date_assigned.data.strftime('%Y/%m/%d') date_returned_string = form.date_returned.data.strftime('%Y/%m/%d') date_bought_object = datetime.strptime(date_bought_string,'%Y/%m/%d') date_assigned_object = datetime.strptime(date_assigned_string,'%Y/%m/%d') date_returned_object = datetime.strptime(date_returned_string,'%Y/%m/%d') inventory = Inventory(asset_id=asset.id, serial_code=form.serial_code.data, serial_no=form.serial_no.data, asset_name=asset.name, description=form.description.data, date_bought=date_bought_object, confirmed=form.confirmed.data, assigned=form.assigned.data, revolved=form.revolved.data, assigned_to_id=assigned_to.id, date_assigned=date_assigned_object, date_returned=date_returned_object) db.session.add(inventory) db.session.commit() return redirect(url_for('main.index')) else: return render_template('main/inventory_detail.html', form=form)
def test_deserialize_bad_data1(self, bad_mock): """ Test deserialization of bad data """ data = "this is not a dictionary" bad_mock.side_effect = KeyError() data = {} inventory = Inventory() bad_mock.side_effect = DataValidationError() self.assertRaises(DataValidationError, inventory.deserialize,data)
def create_inventory(): """ Creates Inventory This endpoint will create Inventory based the data in the body that is posted """ data = {} # Check for form submission data if request.headers.get( 'Content-Type') == 'application/x-www-form-urlencoded': app.logger.info('Getting data from form submit') data = { 'name': request.form['name'], 'category': request.form['category'], 'available': request.form['available'] == True, 'condition': request.form['condition'], 'count': request.form['count'] } else: app.logger.info('Getting data from API call') data = request.get_json() app.logger.info(data) inventory = Inventory() inventory.deserialize(data) inventory.save() message = inventory.serialize() location_url = url_for('get_inventory', inventory_id=inventory.id, _external=True) return make_response(jsonify(message), status.HTTP_201_CREATED, {'Location': location_url})
def test_key_error_on_update(self, bad_mock): """ Test KeyError on update """ bad_mock.side_effect = KeyError() inventory = Inventory("tools", "widget1", False, "new") inventory.save() inventory.name = 'Wrench' inventory.update()
def home(): form = InventoryForm() items = Inventory.query.filter_by(company_id=current_user.id) if form.validate_on_submit(): item = Inventory(name=form.name.data, company_id=current_user.id) db.session.add(item) db.session.commit() return redirect(url_for('inv.home')) return render_template('inventory.html', items=items, form=form)
def test_create_a_inventory(self): """ Create inventory and assert that it exists """ inventory = Inventory(name="tools", category="widget1", available=True, condition="new") self.assertNotEqual(inventory, None) self.assertEqual(inventory.id, None) self.assertEqual(inventory.name, "tools") self.assertEqual(inventory.category, "widget1") self.assertEqual(inventory.available, True) self.assertEqual(inventory.condition, "new")
def list_inventory(): """ Returns all of the Inventory """ app.logger.info('Request for inventory list') inventory = [] category = request.args.get('category') name = request.args.get('name') condition = request.args.get('condition') count = request.args.get('count') available = request.args.get('available') if category: inventory = Inventory.find_by_category(category) elif name: inventory = Inventory.find_by_name(name) else: inventory = Inventory.all() results = [inventory.serialize() for inventory in inventory] return make_response(jsonify(results), status.HTTP_200_OK)
def get_all_inventory(): page = request.args.get('page', 1, type=int) per_page = min( request.args.get('per_page', current_app.config['PAGINATION_MIN'], type=int), current_app.config['PAGINATION_MAX']) curr_user = token_auth.current_user() data = Inventory.to_collection_dict(Inventory.query, page, per_page, 'inventory.get_all_inventory') return data
def delete_inventory(inventory_id): """ Delete an Inventory This endpoint will delete an inventory based the id specified in the path """ app.logger.info('Request to delete inventory with id: %s', inventory_id) inventory = Inventory.find(inventory_id) if inventory: inventory.delete() return make_response('', status.HTTP_204_NO_CONTENT)
def get_inventory(inventory_id): """ Retrieve a single Inventory This endpoint will return an Inventory based on it's id """ app.logger.info('Request for Inventory with id: %s', inventory_id) inventory = Inventory.find(inventory_id) if not inventory: raise NotFound( "Inventory with id '{}' was not found.".format(inventory_id)) return make_response(jsonify(inventory.serialize()), status.HTTP_200_OK)
def test_update_a_inventory(self): """ Update an Inventory """ inventory = Inventory(name="tools", category="widget1", available=True,condition="new") inventory.save() self.assertNotEqual(inventory.id, None) # Change it an save it inventory.category = "jkwidget2" inventory.save() # Fetch it back and make sure the id hasn't changed # but the data did change inventory = Inventory.all() self.assertEqual(len(inventory), 1) self.assertEqual(inventory[0].category, "jkwidget2") self.assertEqual(inventory[0].name, "tools")
def setUp(self): """ Runs before each test """ """ Initialize the Cloudant database """ self.app = app.app.test_client() Inventory.init_db("tests_inventory") Inventory.remove_all() Inventory("tools", "widget1", True, "new", 1).save() Inventory("materials", "widget2", False, "old", 2).save()
def void_inventory(inventory_id): """Void an inventory item""" app.logger.info('Request to void inventory with id: %s', inventory_id) check_content_type('application/json') inventory = Inventory.find(inventory_id) if not inventory: raise NotFound( "Inventory with id '{}' was not found.".format(inventory_id)) data = request.get_json() app.logger.info(data) inventory.deserialize(data) inventory.id = inventory_id inventory.available = False inventory.save() return make_response(jsonify(inventory.serialize()), status.HTTP_200_OK)
def test_find_inventory(self): """ Find an Inventory by ID """ Inventory("tools", "widget1").save() # saved_pet = Pet("kitty", "cat").save() saved_inventory = Inventory("materials", "widget2") saved_inventory.save() inventory = Inventory.find(saved_inventory.id) self.assertIsNot(inventory, None) self.assertEqual(inventory.id, saved_inventory.id) self.assertEqual(inventory.name, "materials")
def test_remove_inventory(self): user_id = User.query.first().id self.u.inventories.append( Inventory(ingredient_id=self.ingredient_id1, user_id=user_id, quantity=1)) self.u.remove_inventory(ingredient_id=self.ingredient_id1, quantity=.5) quantity = self.u.inventories.filter_by( ingredient_id=self.ingredient_id1).first().quantity self.assertEqual(quantity, .5) self.u.remove_inventory(ingredient_id=self.ingredient_id1, quantity=5) quantity = self.u.inventories.filter_by( ingredient_id=self.ingredient_id1).first().quantity self.assertEqual(quantity, 0)
def manage_book(): if request.method == 'GET': return render_template('manage_book.html') else: inventory = Inventory(barcode=request.form.get('barcode'), isbn=request.form.get('isbn'), storage_date=request.form.get('storage_date'), location=request.form.get('location'), status=int(request.form.get('status')), admin=request.form.get('admin')) book = Book(isbn=request.form.get('isbn'), book_name=request.form.get('book_name'), author=request.form.get('author'), press=request.form.get('press'), class_name=request.form.get('class_name')) if Book.query.filter_by(isbn=request.form.get('isbn')).first() is None: db.session.add(book) db.session.commit() db.session.add(inventory) print("book added") db.session.commit() return jsonify("success")
def test_ingredient_in_inventory(self): self.assertEqual( self.u.ingredient_in_inventory(ingredient_id=self.ingredient_id1), None) user_id = User.query.first().id self.u.inventories.append( Inventory(ingredient_id=self.ingredient_id1, user_id=user_id, quantity=1)) self.assertEqual( self.u.ingredient_in_inventory( ingredient_id=self.ingredient_id1).ingredient_id, self.ingredient_id1) self.assertEqual( self.u.ingredient_in_inventory( ingredient_id=self.ingredient_id1).quantity, 1)
def update_inventory(inventory_id): """ Update a Inventory This endpoint will update an Inventory based the body that is posted """ app.logger.info('Request to Update a inventory with id [%s]', inventory_id) check_content_type('application/json') inventory = Inventory.find(inventory_id) if not inventory: raise NotFound( "inventory with id '{}' was not found.".format(inventory_id)) data = request.get_json() app.logger.info(data) inventory.deserialize(data) inventory.id = inventory_id inventory.save() return make_response(jsonify(inventory.serialize()), status.HTTP_200_OK)
def additem(): if (session.get('logged_in')): form = AddItemForm() search = SearchForm() if request.method == 'POST' and search.validate_on_submit(): return redirect((url_for('search_page', searchQuery=search.searchParam.data))) current_user = seller.query.filter_by( seller_id=session.get('user_id')).first() flash("TESTFLASH") if form.validate_on_submit(): item = Inventory.query.filter_by( item_name=form.itemname.data).first() if (item): print("duplicate item error") return redirect(url_for('account')) else: itemname = form.itemname.data itemquantity = form.itemquantity.data itemprice = form.itemprice.data itemdescription = form.itemdescription.data item = Inventory(item_name=itemname, item_price=itemprice, item_quantity=1, item_image="dolater.jpg", item_description=itemdescription, seller=current_user) db.session.add(item) db.session.commit() return redirect(url_for('account')) else: return redirect(url_for('index')) return render_template('add.html', title="Add", form=form, search=search, user=current_user)