def run_tests(): """Test Catalogue class.""" # Test empty Catalogue (defaults) print("Test empty Catalogue:") catalogue = Catalogue() assert not catalogue.stores # an empty list is considered False # Test loading stores print("\nTest loading Stores:") catalogue.load_stores('store_saves.csv') for shop in catalogue.list_stores(): print(f'\n{shop}') print("\nTest listing shop inventory") for item in shop.inventory.list_items(): print(item) assert catalogue.stores # assuming CSV file is non-empty, non-empty list is considered True # Test adding a new Shop with values print("\nTest adding new Shop:") catalogue.add_store(Store("Squelons Wood", 300, 500, "I sell wood!")) for shop in catalogue.list_stores(): print(shop) # Test saving Stores (check CSV file manually to see results) catalogue.save_stores('test.csv')
def test_get_products_with_appropriate_price(self): p1 = Product(id_="X1", name="Toy X1", price=10.3) p2 = Product(id_="X2", name="Toy X2", price=8.3) c = Catalogue({p1.id: p1, p2.id: p2}) filtered_products = c.get_products_with_appropriate_price(lambda price: price < 10.0) self.assertDictEqual({p2.id: p2}, filtered_products)
def test_add_candle_puts_two_candles_in_list(): cat = Catalogue("2021 catalogue") candle1 = Candle("Beach", 54, "lavender", "square", "4 hours", "10cm by 10cm", "£100") candle2 = Candle("Beach", 2, "lavender", "square", "4 hours", "10cm by 10cm", "£100") cat.add_candle(candle1) cat.add_candle(candle2) assert cat.candles_list == [candle1, candle2]
def test_get_products_by_name_part_case_sensitive(self): p1 = Product(id_="X1", name="TOY uppercase", price=10) p2 = Product(id_="X2", name="toy lowercase", price=10) c = Catalogue({p1.id: p1, p2.id: p2}) filtered_products = c.get_products_by_name_part("toy") self.assertDictEqual({p2.id: p2}, filtered_products)
def __init__(self, catalogue_json_file: str, offer_types_json_file: str, product_offers_json_file: str): self.catalogue = Catalogue(catalogue_json_file) self.product_offers = ProductOffers(offer_types_json_file, product_offers_json_file) self.products = {} self.sub_total, self.discount, self.total = 0.0, 0.0, 0.0
def test_add_product(self): p = Product(id_="P", name="X", price=0) c = Catalogue() c.add_product(p) p.name = "Y" self.assertEqual("X", c.inventory["P"].name)
def test_add_too_many_products_in_a_batch(self): p1 = Product(id_="P1", name="", price=0) p2 = Product(id_="P2", name="", price=0) p3 = Product(id_="P3", name="", price=0) c = Catalogue() self.assertEqual(2, c.add_products([p1, p2, p3])) self.assertDictEqual({p1.id: p1, p2.id: p2}, c.inventory)
def test_adding_products_to_catalogue(self): self.test_catalogue = Catalogue(self.test_products) self.test_catalogue.add_products([ Product('Additional Product 1', 1.00), Product('Additional Product 2', 1.00) ]) self.assertEqual(len(self.test_catalogue.products), len(self.test_products) + 2)
def __init__(self, prix_file="test_data/prix.csv", remises_file="test_data/remises.csv"): self.catalog_manager = Catalogue(prix_file, remises_file) self.catalog_prix, self.catalog_remises = self.catalog_manager.get_dicts( ) self.tickets = []
def main(): """ Creates a library with dummy data and prompts the user for input. """ item_list = [] catalogue = Catalogue(item_list) catalogue.generate_test_items() my_epic_library = Library(catalogue) my_epic_library.display_library_menu()
async def update_store(ctx, *, details): store_details = details.split(':') if len(store_details) == 5: # Correct number of arguments provided old_store_name = store_details[0].strip() new_store_name = store_details[1].strip() new_store_location_x = store_details[2].strip() new_store_location_z = store_details[3].strip() new_store_description = store_details[4].strip() catalogue = Catalogue() catalogue.load_stores(PATH_TO_DATA_FILE) # Attempt to remove old store from catalogue. is_removed = catalogue.remove_store(old_store_name) if not is_removed: embed = discord.Embed( title=f'Store: \'{old_store_name}\' cannot be found', color=13424046) await ctx.send(embed=embed) else: # Add updated store updated_store = Store(new_store_name, new_store_location_x, new_store_location_z, new_store_description) catalogue.add_store(updated_store) # Update save file catalogue.save_stores(PATH_TO_DATA_FILE) embed = discord.Embed(title='Store Updated Successfully', color=13424046) await ctx.send(embed=embed) await stores(ctx) else: embed = discord.Embed(title='Error: Please use the following format', color=13424046) await ctx.send(embed=embed) await help(ctx, 'update_store')
async def stores(ctx): catalogue = Catalogue() catalogue.load_stores(PATH_TO_DATA_FILE) embed = discord.Embed(title='MelonCraft Stores', color=13424046) for store in catalogue.list_stores(): embed.add_field( name=store.name, value= f'{store.description} ({store.location_x}, {store.location_z})', inline=False) await ctx.send(embed=embed)
def test_inventory_overflow_init(self): p1 = Product(id_="P1", name="", price=0) p2 = Product(id_="P2", name="", price=0) p3 = Product(id_="P3", name="", price=0) big_inventory = {"1": p1, "2": p2, "3": p3} with self.assertRaises(InventoryOverflowException): c = Catalogue(big_inventory)
def test_init(self): p = Product(id_="P", name="", price=0) inventory = {p.id: p} c = Catalogue(inventory) del inventory[p.id] self.assertEqual(1, len(c.inventory))
def set_multipoles(self, s, ic=['global', 'global'], iaddbins=None): catalogue = Catalogue.load(self.params['path_randoms']) radials, densities, weights = self.get_radial_density( catalogue, iaddbins=[iaddbins] * 2, density=[False, True], power_weight=[2 if 'radial' in ic else 1, 1]) pyanalytic2pcf = PyAnalytic2PCF(**self.params) if ('global' in ic) or (('radial' in ic) and ('angular' in ic)): typewin = 'global' else: typewin = ic[0] if typewin == 'angular': angular_s = None angular_window = None else: angular_s = self.angular.s angular_window = self.angular.window[0] self.result = pyanalytic2pcf.run(s, angular_s, angular_window, radials, densities, typewin=typewin) self.result.weight_tot = scipy.sum(weights[-1]**2) self.result.rescale()
def main(): """ Creates a library with dummy data and prompts the user for input. """ lib_catalogue = Catalogue() my_epic_library = Library(lib_catalogue) my_epic_library.display_library_menu()
def set_multipoles(self, icut=0, icut1=0, ncuts=1, losn=0, modes=None): catalogues = [ Catalogue.load(self.params['path_randoms'][mode]) for mode in self.modes ] icutibins = catalogues[1].attrs['icutibins'][icut] assert (icutibins == catalogues[2].attrs['icutibins'][icut]).all() icutnbins = len(icutibins) naddbins = catalogues[0].attrs['naddbins'] assert (naddbins == catalogues[1].attrs['naddbins']) and ( naddbins == catalogues[2].attrs['naddbins']) catalogue1 = catalogues[0].slice(icut1, ncuts) pyreal3pcf = PyReal3PCF(**self.params) pyreal3pcf.set_grid() self.result = 0 for iaddbin in range(naddbins): mask2 = catalogues[1]['iaddbin'] == iaddbin mask3 = catalogues[2]['iaddbin'] == iaddbin for ibin, bin in enumerate(icutibins): self.logger.info( 'Correlating slice {:d} ({:d}/{:d}) of cut {:d}/{:d}.'. format(bin, ibin + 1, icutnbins, iaddbin + 1, naddbins)) catalogue2 = catalogues[1][mask2 & (catalogues[1]['ibin'] == bin)] catalogue3 = catalogues[2][mask3 & (catalogues[2]['ibin'] == bin)] if not catalogue2 or not catalogue3: continue self.result += pyreal3pcf.copy().run(catalogue1, catalogue2, catalogue3)
def prepare_catalogues(self, path_input, path_randoms, ic=None, rwidth=2., redges=None, nside=32, seed=42, ncuts=20, share='counts', downsample=2., additional_bins=[]): catalogue = Catalogue.load(path_input) modes = path_randoms.keys() self.params['ic'] = self.ic catalogues = self.normalize_catalogue( {mode: catalogue.deepcopy() for mode in modes}, ic=self.ic, rwidth=rwidth, redges=redges, nside=nside, seed=seed, additional_bins=additional_bins) if isinstance(downsample, float): downsample = {mode: downsample for mode in modes} for mode in modes: catalogues[mode] = catalogues[mode].downsample(downsample[mode]) if self.ic in ['angular', 'radial']: catalogues = self.slice_catalogues(catalogues, ncuts=ncuts, share=share) for mode, catalogue in catalogues.items(): catalogue.save(path_randoms[mode])
def test_delete_both_candles_gives_empty_list(): cat = Catalogue("2021 catalogue") candle1 = Candle("Beach", 54, "lavender", "square", "4 hours", "10cm by 10cm", "£100") candle2 = Candle("Beach", 2, "lavender", "square", "4 hours", "10cm by 10cm", "£100") cat.add_candle(candle1) cat.add_candle(candle2) cat.delete_candle(54) cat.delete_candle(2) assert cat.candles_list == []
def main(): """ Creates a library with dummy data and prompts the user for input. """ book_list = generate_test_books() my_epic_catalogue = Catalogue(book_list) my_epic_library = Library(my_epic_catalogue) my_epic_library.display_library_menu()
def main(): # def __init__(self, title, call_no, author, num_copies): # issue, publisher): # def __init__(self, title, call_no, author, num_copies, name, # issue, publisher): b1 = Book("Provenance", "342.2", "Anne Leckie", 20) b2 = Book("Ancillary Justice", "342.2A", "Anne Leckie", 1) j1 = Journal("Individual Psychology", "123.4", "Gabriela Pap", 1, "Journal of Psychology", 23, "SAGE Publications") d1 = Dvd("Mad Max: Fury Road", "789.0", "George Miller", 8, "May 15, 2015", "1") cat = Catalogue({ "342.2": Book("Provenance", "342.2", "Anne Leckie", 20), "342.2A": Book("Ancillary Justice", "342.2A", "Anne Leckie", 1), "123.4": Journal("Individual Psychology", "123.4", "Gabriela Pap", 1, "Journal of Psychology", 23, "SAGE Publications"), "789.0": Dvd("Mad Max: Fury Road", "789.0", "George Miller", 8, "May 15, 2015", "1") }) vpl = Library(cat) display_menu = True while display_menu: print("What would you like to do?") print("1. Find item by title (String)") print("2. Add item to catalogue") print("3. Remove item from catalogue (call no)") print("4. Check out a copy (call no)") print("5. Return your copy (call no)") print("6. Display library catalogue") print("7. Quit menu") choice = int(input("Select action: ")) if choice == 2: vpl.get_cat().add_item() elif choice == 6: vpl.display_available_books() elif choice == 7: display_menu = False elif choice not in range(1, 6): print("\nInvalid input. Try again.\n") else: par = input("Enter parameter: ") input_dict = { 1: vpl.search, 3: cat.remove_item, 4: vpl.check_out, 5: vpl.return_item } print(input_dict.get(choice)(par))
def test_catalogue(): catalog = Catalogue(prix_file="test_data/prix.csv", remises_file="test_data/remises.csv") catalog_prix, catalog_remises = catalog.get_dicts() print("- Liste des prix:") print(catalog_prix) print("- Liste des promo:") print(catalog_remises) print("--- MAJ catalogue ---") catalog_prix, catalog_remises = catalog.maj( prix_file='test_data/prix2.csv', remises_file='test_data/remises2.csv') print("- Liste des prix:") print(catalog_prix) print("- Liste des promo:") print(catalog_remises)
def set_multipoles(self, icut=0, losn=0, modes=None): catalogues = [ Catalogue.load(self.params['path_randoms'][mode]) for mode in self.modes ] icutibins = catalogues[0].attrs['icutibins'][icut] assert (icutibins == catalogues[2].attrs['icutibins'][icut]).all() icutnbins = len(icutibins) naddbins = catalogues[0].attrs['naddbins'] assert (naddbins == catalogues[1].attrs['naddbins']) and ( naddbins == catalogues[2].attrs['naddbins']) and ( naddbins == catalogues[3].attrs['naddbins']) pyreal4pcf = PyReal4PCFBinned(**self.params) pyreal4pcf.set_grid(binsize=catalogues[-1].attrs['nbins']) self.result = 0 for iaddbin1 in range(naddbins): catalogue2 = catalogues[1][catalogues[1]['iaddbin'] == iaddbin1] catalogue4 = catalogues[3][catalogues[3]['iaddbin'] == iaddbin1] for iaddbin2 in range(naddbins): mask1 = catalogues[0]['iaddbin'] == iaddbin2 mask3 = catalogues[2]['iaddbin'] == iaddbin2 for ibin, bin in enumerate(icutibins): self.logger.info( 'Correlating {}x{} slice {:d} ({:d}/{:d}) of cut {:d}/{:d} and {:d}/{:d}.' .format(self.modes[2], self.modes[3], bin, ibin + 1, icutnbins, iaddbin1 + 1, naddbins, iaddbin2 + 1, naddbins)) catalogue1 = catalogues[0][mask1 & (catalogues[0]['ibin'] == bin)] catalogue3 = catalogues[2][mask3 & (catalogues[2]['ibin'] == bin)] if not catalogue1 or not catalogue3: continue self.result += pyreal4pcf.copy().run(catalogue1, catalogue2, catalogue3, catalogue4, tobin=[2, 4]) if self.modes[2] != self.modes[3]: #if True: self.logger.info( 'Correlating {}x{} slice {:d} ({:d}/{:d}) of cut {:d}/{:d} and {:d}/{:d}.' .format(self.modes[3], self.modes[2], bin, ibin + 1, icutnbins, iaddbin1 + 1, naddbins, iaddbin2 + 1, naddbins)) self.result += pyreal4pcf.copy().run( catalogue2, catalogue1, catalogue4, catalogue3, tobin=[1, 3]) # beware: twice the normalisation if self.result and self.modes[2] != self.modes[3]: self.result.weight_tot /= 2.
def setUp(self): self.test_products = [ Product('Baked Beans', 0.99), Product('Biscuits', 1.20), Product('Sardines', 1.89), Product('Shampoo (Small)', 2.00), Product('Shampoo (Medium)', 2.50), Product('Shampoo (Large)', 3.50), ] self.test_catalouge = Catalogue(self.test_products)
def test_delete_candle_gives_error_if_candle_not_in_list(): cat = Catalogue("2021 catalogue") candle1 = Candle("Beach", 54, "lavender", "square", "4 hours", "10cm by 10cm", "£100") candle2 = Candle("Beach", 2, "lavender", "square", "4 hours", "10cm by 10cm", "£100") candle3 = Candle("Beach", 3, "lavender", "square", "4 hours", "10cm by 10cm", "£100") cat.add_candle(candle1) cat.add_candle(candle2) with pytest.raises(ValueError): cat.delete_candle(candle3) assert cat.candles_list == [candle1, candle2] with pytest.raises(ValueError) as error: cat.delete_candle(candle3) assert str(error.value) == "Item not found"
def main(): """ Creates a library and prompts the user with options. """ # Create a new library with a new catalogue library = Library(Catalogue()) # User Prompt while True: library.give_options()
async def list_inventory(ctx, *, store_name): catalogue = Catalogue() catalogue.load_stores(PATH_TO_DATA_FILE) is_valid_store = False for store in catalogue.list_stores(): if store.name.lower() == store_name.lower(): is_valid_store = True embed = discord.Embed(title=f'{store.name}', color=13424046) if store.inventory.__len__() == 0: embed.add_field(name='Currently has no Stock!', value='Please check back later.', inline=False) else: for item in store.inventory.list_items(): embed.add_field(name=item.name, value=f'{item.quantity} / {item.cost}D', inline=False) await ctx.send(embed=embed) if not is_valid_store: await ctx.send(f'\'{store_name}\' could not be found.') await stores(ctx)
def test_update_price_on_id_not_found_gives_error(): cat = Catalogue("2021 catalogue") candle1 = Candle("Beach", 54, "lavender", "square", "4 hours", "10cm by 10cm", "£100") cat.add_candle(candle1) with pytest.raises(ValueError) as e: cat.update_candle_price(2, "£80") assert str(e.value) == "Item not found"
def main(): """ Creates a library with dummy data and prompts the user for input. """ b1 = Book("100.200.300", "Harry Potter 1", 2, "J K Rowling") b2 = Book("999.224.854", "Harry Potter 2", 5, "J K Rowling") b3 = Book("631.495.302", "Harry Potter 3", 4, "J K Rowling") b4 = Book("123.02.204", "The Cat in the Hat", 1, "Dr. Seuss") cat = Catalogue([b1, b2, b3, b4]) lib = Library(cat) lib.display_library_menu()
def test_delete_candle_removes_the_candle_from_list(): cat = Catalogue("2021 catalogue") candle1 = Candle("Beach", 54, "lavender", "square", "4 hours", "10cm by 10cm", "£100") candle2 = Candle("Beach", 2, "lavender", "square", "4 hours", "10cm by 10cm", "£100") cat.add_candle(candle1) cat.add_candle(candle2) cat.delete_candle(54) assert cat.candles_list == [candle2]
# -*- coding: utf-8 -*- from selenium import webdriver from catalogue import Catalogue driver = webdriver.PhantomJS() driver.implicitly_wait(3) first_page_link = "https://market.yandex.ru/catalog/55939/list?hid=91529&how=dpop&gfilter=2142357015%3A477105268&in-stock=1&priceto=20000" page_numbers = 1 cat = Catalogue(driver, first_page_link, page_numbers) # get list of goods and its ids goods_id = cat.get_goods_id() # get good data with criteria text and its values cat.get_goods_criteria(goods_id) driver.close() driver.quit()