def test_bakery(self): vs = Product("Vegemite Scroll", "VS5", {3: 6.99, 5: 8.99}) mb = Product("Blueberry Muffin", "MB11", {2: 9.95, 5: 16.95, 8: 24.95}) cf = Product("Croissant", "CF", {3: 5.95, 5: 9.95, 9: 16.99}) bakery = Bakery([vs, mb, cf]) # test get product by code test_code = "VS5" self.assertEqual(bakery.get_product("VS5").code, test_code) self.assertRaises(KeyError, bakery.get_product, "not_exist_code") # init order for test order = Order({"VS5": "10", "WRONG_CODE": 14, "CF": 13}) # input format test bakery.process_order(order) self.assertTrue(order.get_product("WRONG_CODE")["total_price"] is None) # test single product order order = Order({"VS5": 10}) bakery.process_order(order) self.assertEqual(order.get_product("VS5")["packs"], {5: 2}) # test combined products order order = Order({"VS5": 10, "MB11": 14, "CF": 13}) bakery.process_order(order) self.assertEqual(order.get_product("VS5")["packs"], {5: 2}) self.assertEqual(order.get_product("VS5")["remainder"], 0) self.assertEqual(order.get_product("MB11")["packs"], {8: 1, 2: 3}) self.assertEqual(order.get_product("MB11")["remainder"], 0) self.assertEqual(order.get_product("CF")["remainder"], 0) self.assertEqual(order.get_product("CF")["packs"], {5: 2, 3: 1})
def init_db(): # Create the fixtures try: polo = Product(code='c001', name='Polo', color='blue', price=20, quantity=100) polo.save() jersey = Product(code='c002', name='Jersey', color='black', price=30, quantity=80) jersey.save() dressShirt = Product(code='c003', name='Dress Shirt', color='white', price=25, quantity=80) dressShirt.save() except BaseException: print("DB already initialized")
def create_fixtures(self): self.user_email = self.user_email_template.format(random_string(8)) self.user = User(self.user_email, 'test_user') self.db.session.add(self.user) self.group_name = self.group_template.format(random_string(8)) self.group = ProductGroup(type='test', name=self.group_name, capacity_max=10) self.product1 = Product(name=self.product1_name, parent=self.group, capacity_max=3) self.tier1_1 = PriceTier(name=self.tier1_1_name, parent=self.product1) self.price1_1 = Price(price_tier=self.tier1_1, currency='GBP', price_int=10) self.db.session.add(self.tier1_1) self.tier1_2 = PriceTier(name=self.tier1_2_name, parent=self.product1) self.price1_2 = Price(price_tier=self.tier1_2, currency='GBP', price_int=20) self.db.session.add(self.tier1_2) self.product2 = Product(name=self.product2_name, parent=self.group) self.tier3 = PriceTier(name=self.tier3_name, parent=self.product2) self.price3 = Price(price_tier=self.tier3, currency='GBP', price_int=30) self.db.session.add(self.tier3) self.db.session.commit()
def setup(self): self.product_1 = Product( 'Omnitronic BD-1350 Turntable', 'Belt drive DJ turntable with adjustable speed control', '50', '80', '150') self.product_2 = Product('Pioneer DDJ-400', 'DJ Controller with FULL Rekordbox Software', '40', '150', '200')
def _create_cart(self): iphone_silver = Product('Iphone Silver', 'Silver', 999) iphone_black = Product('Iphone Black', 'Black', 899) cart = Cart(self._create_user()) cart.add(iphone_silver, 2) cart.add(iphone_black, 1) return cart
def test_capacity_propagation(db, parent_group, user): product1 = Product(name="product", parent=parent_group, capacity_max=3) tier1_1 = PriceTier(name="tier1", parent=product1) Price(price_tier=tier1_1, currency="GBP", price_int=10) db.session.add(tier1_1) tier1_2 = PriceTier(name="tier2", parent=product1) Price(price_tier=tier1_2, currency="GBP", price_int=20) db.session.add(tier1_2) product2 = Product(name="product2", parent=parent_group) tier3 = PriceTier(name="tier3", parent=product2) Price(price_tier=tier3, currency="GBP", price_int=30) db.session.commit() # Check all our items have the correct initial capacity assert parent_group.get_total_remaining_capacity() == 10 assert product1.get_total_remaining_capacity() == 3 assert tier1_1.get_total_remaining_capacity() == 3 assert tier1_2.get_total_remaining_capacity() == 3 assert product2.get_total_remaining_capacity() == 10 assert tier3.get_total_remaining_capacity() == 10 # Issue three instances to exhaust product1 create_purchases(tier1_1, 3, user) db.session.commit() # Now we shouldn't be able to issue any more tickets from this product with pytest.raises(CapacityException): create_purchases(tier1_1, 1, user) with pytest.raises(CapacityException): create_purchases(tier1_2, 1, user) db.session.commit() # All the capacity went from product1 assert tier1_1.get_total_remaining_capacity() == 0 assert tier1_2.get_total_remaining_capacity() == 0 assert product1.get_total_remaining_capacity() == 0 # produtill has capacity but is limited by the parent assert parent_group.get_total_remaining_capacity() == 7 assert product2.get_total_remaining_capacity() == 7 assert tier3.get_total_remaining_capacity() == 7 price1 = Price(price_tier=tier1_1, currency="GBP", price_int=5) price2 = Price(price_tier=tier1_2, currency="GBP", price_int=500) db.session.add(price1) db.session.add(price2) db.session.commit() assert price1 == product1.get_cheapest_price("GBP")
def index(): products = [] products.append(Product('日語五十音入門班')) products.append(Product('N2綜合實力養成班', 6000)) products.append(Product('韓語入門班', 4599)) products.append(Product('英文會話班Level E', 5800)) products.append(Product('日語閱讀理解實力養成班', 6500)) return render_template('shop/index.html', products=products)
def test_total_voucher(self): product_a = Product(sku='prod-a', name='Producto A') product_a.set_pricing(country_code='ES', price=50., discount=0.1) product_b = Product(sku='prod-b', name='Producto B') product_b.set_pricing(country_code='ES', price=20., discount=0.) cart = Cart() cart.apply_voucher(code='promo5', amount=5., min_amount=90.) cart.add_item(product=product_a, quantity=1) cart.add_item(product=product_b, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 65.0) cart.add_item(product=product_a, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 105.0)
def create_and_setup_categories(category_obj): category_soup = get_soup_for_obj(category_obj) try: category_obj.description = category_soup.\ find('div', {'class': 'categoryDesc'}).\ find('p').text except: category_obj.description = '' category_obj.save() try: sub_category_tags = category_soup.\ find('table', {'class': 'categoryList'}). \ find_all('td', {'class': 'categoryListItem'}) for sub_category_tag in sub_category_tags[:5]: category_obj.sub_categories.append( get_sub_category(sub_category_tag)) category_obj.save() except: product_tags = category_soup.find_all('td', {'class': 'prodWrap'}) for product_tag in product_tags[:5]: product_obj = Product() product_obj.category = category_obj product_obj.href = product_tag.find('a').get('href') product_obj.image_url = product_tag.\ find('td', {'class': 'imageWrap'}).find('img').get('src') product_obj.title = product_tag.\ find('div', {'class': 'productsname'}).find('a').text product_obj.save()
def setUp(self): product_name = "Universe 51" type_name = "Dumbphone" # to create product_type product_type = ProductType( type_name ) # PRODUCT_TYPE brand_name = "Dapple" # to create brand brand_description = "ScroogeMcDuck" # to create brand brand_warranty_details = "AllOutOfWarranty" # to create brand product_brand = Brand( brand_name, brand_description, brand_warranty_details ) # BRAND product_description = "Is a phone and a computor" product_distributor_price = 100 product_sale_price = 400 product_warranty_length = 365 self.product1 = Product( product_name, product_type, product_brand, product_description, product_warranty_length, product_distributor_price, product_sale_price, )
def new_product(copy_id, parent_id): if parent_id: parent = ProductGroup.query.get_or_404(parent_id) else: parent = Product.query.get(copy_id).parent form = NewProductForm() if form.validate_on_submit(): product = Product(parent=parent, name=form.name.data, display_name=form.display_name.data, expires=form.expires.data or None, capacity_max=form.capacity_max.data or None, description=form.description.data or None) app.logger.info('%s adding new Product %s', current_user.name, product) db.session.add(product) db.session.commit() flash('Your new ticket product has been created') return redirect(url_for('.product_details', product_id=product.id)) if copy_id: form.init_with_product(Product.query.get(copy_id)) return render_template('admin/products/new-product.html', parent=parent, product_id=copy_id, form=form)
def get_products(self, category): ''' Gets all the products of the specified category. Args: category (category.Category): The category. Returns: products (list [product.Product]): Products. ''' products = [] with connector.connect(**self.connection_config) as connection: with connection.cursor() as cursor: query = ("SELECT product_id, name, category_id, " "description, nutri_score, stores, url " "FROM Product " "WHERE category_id = %s " "ORDER BY product_id ASC") data = (category.category_id, ) cursor.execute(query, data) for product_id, name, category_id, description, \ nutri_score, stores, url in cursor: product = { 'product_id': product_id, 'name': name, 'category_id': category_id, 'description': description, 'nutri_score': nutri_score, 'stores': stores, 'url': url } products.append(Product(product)) connection.commit() return products
def edit2(id): cat = Category() pro = Product() a = cat.getCategories() b = pro.getProductById(id) print(b) return render_template('product/edit2.html', arr=a, u=b)
def on_ticket_clicked(self, button): from reportlab.platypus import Table from reportlab.platypus import SimpleDocTemplate from reportlab.lib.pagesizes import A4 from reportlab.lib import colors script = [] table_header = [["ID", "NOMBRE", "TIPO", "STOCK", "PRECIO", "DESCRIPCION"]] table = Table(table_header) table.setStyle([('INNERGRID', (0,0),(-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black)]) script.append(table) product = Product(self.search_entry.get_text()) # New costumer object with the user id on search_entry product_list = product.get_products() # Gets the database data if product_list == []: #self.validation_label.set_markup("<span color='red'>No existe ese usuario</span>") '''''' else: table = Table(product_list) table.setStyle([('BOX', (0,0),(-1,-1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) script.append(table) #creacion del archivo pdf doc = SimpleDocTemplate("productos.pdf", pagesize=A4, showBoundary=1) doc.build(script)
def test_check_in(db, parent_group, user): product = Product(name="product", capacity_max=3, parent=parent_group) tier = PriceTier(name="tier", parent=product) price = Price(price_tier=tier, currency="GBP", price_int=666) db.session.add(price) db.session.commit() purchases = create_purchases(tier, 1, user) purchase = purchases[0] with pytest.raises(PurchaseStateException): # Issuing tickets should fail if the purchase hasn't been paid for purchase.ticket_issued = True with pytest.raises(CheckinStateException): # Likewise, checking in should fail. purchase.check_in() purchase.state = "paid" db.session.commit() purchase.ticket_issued = True assert purchase.checked_in is False purchase.check_in() assert purchase.checked_in is True
def _get_products_from_current_page(self, driver): products = [] time.sleep(3) try: subcategories = driver.find_element_by_id('subcategories') subcategories = subcategories.find_elements_by_tag_name('li') subcategories = list( map( lambda x: x.find_element_by_tag_name('a').get_attribute( 'href'), subcategories)) for c in subcategories: products.extend(self._crawl(c, driver)) return products except: els = driver.find_elements_by_class_name('ajax_block_product') for e in els: name = e.find_elements_by_class_name( 's_title_block')[0].find_element_by_tag_name('a').text price = e.find_elements_by_class_name('price')[0].text image = e.find_elements_by_class_name( 'front-image')[0].get_attribute('src') products.append(Product(name, price, image)) return products
def delete(self, num_serie): product = Product() product.serial_num = num_serie result = product.read() if result: product.delete() return 1
def populate() -> bool: """ populate database from all dumps :return: """ file_storage: str = current_app.config.get('FILE_STORAGE') file_parser = FileParser(storage_path=file_storage) parsed_results: dict = file_parser.parse_storage() for filename, search in parsed_results.items(): products: list = search.pop('products', []) new_search = Search(filename=filename, **search) db.session.add(new_search) db.session.commit() print(new_search) for product in products: flights: list = product.pop('flights', []) new_product = Product(search_id=new_search.id, **product) db.session.add(new_product) db.session.commit() for flight in flights: new_flight = Flight(product_id=new_product.id, **flight) db.session.add(new_flight) db.session.commit() return True
def update(self, *args): try: product: Product = Product() if len(args) is 0: raise Exception('Invalid arguments') if isinstance(args[0], int) or isinstance(int(args[0]), int): product.fill() product.id = args[0] values = product.getValues().split(',') old_values = self.getById(args[0]).getValues().split(',') keys = product.getKeys().split(',') for i in range(len(keys)): if values[i] == 'null': product.__setattr__(keys[i], old_values[i]) if isinstance(args[0], Product): product = args[0] if not product.isFull(): raise Exception('Invalid input') queryStr = '' keys = product.getKeys().split(',') values = product.getValues().split(',') for i in range(len(keys)): queryStr += keys[i] + ' = ' + values[i] + ', ' self.db.cursor.execute( f'Update "Product" Set {queryStr[:-2]} Where id = {product.id}' ) self.db.connect.commit() return True except Exception as err: print("Update error! ", err) return False
def post(self): product_data = ProductSchema().load(request.json) quantity = product_data.pop("quantity", None) shop_id = product_data.pop("shop_id", None) product = Product(**product_data) try: product.save() except: return {"message": ERROR_INSERTING_PRODUCT}, 500 inventory_data = { "product_id": product.id, "quantity": quantity, "shop_id": shop_id } inventory = Inventory(**inventory_data) try: inventory.save() except: return {"message": ERROR_INSERTING_INVENTORY}, 500 return {"id": str(product.id)}, 201
def generate_report(): try: product = Product() myresult = product.get_inf_report() wb = Workbook() headers = [ "ProductID", "DepartmentID", "Category", "IDSKU", "ProductName", "Quantity", "UnitPrice", "UnitPriceUSD", "UnitPriceEuro", "Ranking", "ProductDesc", "UnitsInStock", "UnitsInOrder" ] sheet1 = wb.add_sheet("Report") for i in range(len(headers)): sheet1.write(0, i, headers[i]) counter = 0 for x in myresult: counter += 1 for i in range(len(headers)): sheet1.write(counter, i, x[i]) now = datetime.now() datetime_now = now.strftime("%d%m%Y_%H%M%S") wb.save("report_" + str(datetime_now) + ".xls") print(get_time_now() + " Report generated successfully!") logging.info(get_time_now() + " Report generated successfully!") except BaseException as e: print(get_time_now() + " Problem with generate_report function." + str(e)) logging.error(get_time_now() + " Problem with generate_report function." + str(e))
def save_product(self, product): link = product.find("a", {"class": "product"}).get("href") image = product.find("img").get("src") try: site_product_id = link.split("?productId=xlsImpprod")[1] except IndexError: site_product_id = link.split("productId=")[1] brand = product.find("h4", {"class": "prod-title"}).text.strip() item_name = product.find("p", {"class": "prod-desc"}).text.strip() item_name = item_name.replace("Online Only ", "") try: price = product.find("span", {"class": "regPrice"}) except AttributeError: price = product.find("span", {"class": "pro-new-price"}) if price is not None: price = WebFunctions.only_digits(price.text) product = Product(site_name="ulta", link=link, image=image, site_product_id=site_product_id, brand=brand, item_name=item_name, price=price) product.add_product(self.database)
def _get_product(category, json_product): '''Gets a cleaned product from a product in json format.''' product = { 'product_id': None, 'name': None, 'category_id': category.category_id, 'description': '', 'nutri_score': None, 'stores': '', 'url': None } product = Product(product) if 'product_name_fr' in json_product: if json_product['product_name_fr'] != '': product.name = json_product['product_name_fr'] elif 'product_name' in json_product: if json_product['product_name'] != '': product.name = json_product['product_name'] if 'generic_name_fr' in json_product: product.description = json_product['generic_name_fr'] elif 'generic_name' in json_product: product.description = json_product['generic_name'] if 'nutrition_grade_fr' in json_product: if json_product['nutrition_grade_fr'] in 'abcdeABCDE': product.nutri_score = json_product['nutrition_grade_fr'] if 'stores' in json_product: product.stores = json_product['stores'] if 'url' in json_product: url = json_product['url'].lower() if 'https://' in url and '.openfoodfacts.org/' in url: product.url = json_product['url'] if not (product.name and product.nutri_score and product.url): product = None return product
def create_products(): product_id = 0 for category_obj in Category.objects(): category_soup = BeautifulSoup(r.get(f'{SHOP_URL}{category_obj.href}').content) product_tags = category_soup.find_all('td', {'class': 'prodWrap'}) for product_tag in product_tags: product_obj = Product() product_obj.product_id = product_id product_obj.category = category_obj product_obj.items = randint(0, 10) product_obj.availability = (product_obj.items != 0) product_obj.views = 0 product_name = product_tag.find('div', {'class': 'productsname'}).\ find('a').text product_obj.name = product_name print(product_name) try: product_price = product_tag.find('span', {'class': 'price'}).\ find('b', {'class': 'int'}).text except: break product_price = product_price.replace('\xa0', '') product_obj.price = int(product_price) product_obj.save() product_id += 1
def create_fixtures(self): self.user1_email = self.user1_email_template.format(random_string(8)) self.user2_email = self.user2_email_template.format(random_string(8)) self.user1 = User(self.user1_email, 'test_user1') self.user2 = User(self.user2_email, 'test_user2') self.db.session.add(self.user1) self.db.session.add(self.user2) self.group_name = self.group_template.format(random_string(8)) self.group = ProductGroup(type='admissions', name=self.group_name) self.product = Product(name=self.product_name, parent=self.group) self.tier = PriceTier(name=self.tier_name, parent=self.product) self.price = Price(price_tier=self.tier, currency='GBP', price_int=666) self.db.session.add(self.price) self.db.session.commit() # PriceTier needs to have been committed before this basket = Basket(self.user1, 'GBP') basket[self.tier] = 1 basket.create_purchases() basket.ensure_purchase_capacity() payment = basket.create_payment(BankPayment) assert len(payment.purchases) == 1 self.db.session.commit()
def post(self): product = Product() product.from_json(request.json) product_repository.add_product(product, current_user.id) inventory = Inventory() inventory.product_id = product.id inventory_repository.add_inventory(inventory)
def test_create_purchases(db, parent_group, user): product = Product(name="product", capacity_max=3, parent=parent_group) tier = PriceTier(name="tier", parent=product) price = Price(price_tier=tier, currency="GBP", price_int=666) db.session.add(price) db.session.commit() assert tier.capacity_used == 0 purchases = create_purchases(tier, 1, user) purchase = purchases[0] assert tier.capacity_used == 1 assert product.capacity_used == 1 # NB: Decimal('6.66') != Decimal(6.66) == Decimal(float(6.66)) ~= 6.6600000000000001 assert purchase.price.value == Decimal("6.66") # Test issuing multiple instances works new_purchases = create_purchases(tier, 2, user) assert len(new_purchases) == 2 assert product.capacity_used == 3 # Test issuing beyond capacity errors with pytest.raises(CapacityException): create_purchases(tier, 1, user)
def post(self): parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True) argname = parser.parse_args() if argname['name'] is None: abort( 404, "Could not find product name in message body!", ) pname = argname['name'] is_alredy_exists = Product.query.filter( Product.name == pname).one_or_none() if is_alredy_exists is not None: abort( 404, "Product:{} already exists with id: {}".format( is_alredy_exists.name, is_alredy_exists.id), ) else: obj = Product(name=pname) db.session.add(obj) db.session.commit() p_schema = ProductSchema() data = json.dumps(p_schema.dump(obj)) return data
def post(self): new_cdf = pd.read_csv('product.csv') column_name = list(new_cdf.columns) df = pd.DataFrame(columns=column_name) data_list = [] for index, row in new_cdf.iterrows(): data_dict = { 'id': row['id'], 'name': row['name'], 'description': row['description'], 'brand': row['brand'], 'price': row['price'] } data_list.append(data_dict) for data in data_list: name = data['name'] description = data['description'] brand = data['brand'] price = data['price'] new_product = Product(name=name, brand=brand, description=description, price=price) db.session.add(new_product) db.session.commit() result = post_schema.dump(new_product), status.HTTP_201_CREATED return {"message": "Created successfully.", "data": result}
def setup_products(): product_1_name = "ED209" product_1_description = "Not great on stairs" product_1_distributor_price = 200 product_1_sale_price = 600 product_1_warranty_length = 120 global product_1 product_1 = Product( product_1_name, product_type_1, brand1, product_1_description, product_1_distributor_price, product_1_sale_price, product_1_warranty_length, ) product_2_name = "dezapper" product_2_description = "It will zapp you into the past" product_2_distributor_price = 300 product_2_sale_price = 700 product_2_warranty_length = 140 global product_2 product_2 = Product( product_2_name, product_type_1, brand1, product_2_description, product_2_distributor_price, product_2_sale_price, product_2_warranty_length, ) global product_3 product_3 = Product( product_2_name, product_type_3, brand2, product_2_description, 130, 500, 300 ) global product_4 product_4 = Product( product_2_name, product_type_4, brand2, product_2_description, 140, 360, 150 ) product_repository.save(product_1) product_repository.save(product_2) product_repository.save(product_3) product_repository.save(product_4)