Пример #1
0
class BasketTests(unittest.TestCase):

    def setUp(self):
        self.jarin_ostoskori = Basket("Jari",
                                      ["maito","banaani","hernekeitto"],
                                      15)

    def tearDown(self):
        del self.jarin_ostoskori

    def test_customer_is_string(self):
        self.assertTrue(isinstance(self.jarin_ostoskori.customer, str),
                        "Variable customer type should be string.")

    def test_contents_is_list(self):
        self.assertTrue(isinstance(self.jarin_ostoskori.contents, list),
                        "Variable contents type should be list.")

    def test_price_is_number(self):
        self.assertTrue(isinstance(self.jarin_ostoskori.price, Number),
                        "Variable price type should be Number")

    def test_can_add_product(self):
        self.jarin_ostoskori.add_product("kala", 5)
        self.assertIn("kala", self.jarin_ostoskori.contents,
                      "Variable contents did not contain added item.")

    def test_can_delete_product(self):
        self.jarin_ostoskori.delete_product("kala", 5)
        self.assertNotIn("kala", self.jarin_ostoskori.contents,
                         "Variable contents should not contain deleted item.")
Пример #2
0
 def test_add_single_item(self):
     """
     Basket.add() a single item is successful.
     """
     basket = Basket()
     basket.add("pasta")
     self.assertEqual(len(basket), 1)
Пример #3
0
    def setUp(self):
        """
        Create the two baskets described in assignment.py
        """

        offers = [
            GetOneFree(product_sku="beans", min_items=2),
            PercentageDiscount(product_sku="sardines", discount_percent=25),
        ]

        self.basket_1 = Basket(product_catalog=catalog.products, offers=offers)

        self.basket_1.add_product("beans")
        self.basket_1.add_product("beans")
        self.basket_1.add_product("beans")
        self.basket_1.add_product("beans")
        self.basket_1.add_product("biscuits")

        self.basket_2 = Basket(product_catalog=catalog.products, offers=offers)

        self.basket_2.add_product("beans")
        self.basket_2.add_product("beans")
        self.basket_2.add_product("biscuits")
        self.basket_2.add_product("sardines")
        self.basket_2.add_product("sardines")
Пример #4
0
 def interact(self, game, player):
     if self.get_interaction_stage(player) == 0:
         # Player is not holding a basket
         if player.curr_basket is None:
             if self.quantity > 0:
                 if player.holding_food is None:
                     new_basket = Basket(0, 0, player, Direction.SOUTH)
                     new_basket.update_position(player.position[0],
                                                player.position[1])
                     game.baskets.append(new_basket)
                     game.objects.append(new_basket)
                     player.curr_basket = new_basket
                     new_basket.being_held = True
                     self.quantity -= 1
                     self.set_interaction_message(
                         player,
                         "You picked up basket. Press c to let go and pick up."
                     )
                 else:
                     self.set_interaction_message(
                         player,
                         "Can't pick up a basket while holding food!")
             else:
                 self.set_interaction_message(player,
                                              "There are no more baskets.")
             # Player is holding a basket; return it
         else:
             self.set_interaction_message(player,
                                          "You put the basket back.")
             basket = player.curr_basket
             player.curr_basket = None
             game.baskets.remove(basket)
             game.objects.remove(basket)
             self.quantity += 1
 def test_removing_product_from_basket(self):
     self.test_basket = Basket(self.test_catalouge)
     for product in self.test_products:
         self.test_basket.add_product(product)
     self.test_basket.remove_product(self.test_products[0])
     self.assertEqual(len(self.test_basket.products), len(self.test_products) - 1)
     self.assertEqual(self.test_products[0].name in self.test_basket.products, False)
 def test_basket_discount_multiple_bundle_offers(self):
     # With bundle offer on all shampoo buy 3 get the cheapest free
     self.bundle_offer_all_shampoo = BundleOffer([self.test_products[3],
                                    self.test_products[4],
                                    self.test_products[5]
                                   ], 3)
     # With bundle offer on small shampoo and sardines buy 2 get the cheapest free
     self.bundle_offer_small_shampoo_and_sardines = BundleOffer([self.test_products[3],
                                     self.test_products[2]
                                   ], 2)
     self.test_basket = Basket(self.test_catalouge, [
                                     self.bundle_offer_all_shampoo,
                                     self.bundle_offer_small_shampoo_and_sardines
                                 ])
     # Add 1 sardines
     self.test_basket.add_product(self.test_products[2], 1)
     # Add 3 small shampoo
     self.test_basket.add_product(self.test_products[3], 3)
     # Add 2 medium shampoo
     self.test_basket.add_product(self.test_products[4], 2)
     # Add 3 large shampoo
     self.test_basket.add_product(self.test_products[5], 3)
     # One large shampoo for free (3.5)
     # Two small shampoo for free (4.00)
     # Total: 7.5
     self.assertEqual(self.test_basket.calculate_discount(), 7.5)
     self.assertEqual(self.test_basket.calculate_total(),
                      round_half_up(self.test_products[2].price +
                      self.test_products[3].price * 3 +
                      self.test_products[4].price * 2 +
                      self.test_products[5].price * 3 -
                      self.test_basket.calculate_discount(), 2))
Пример #7
0
    def __init__(self):
        pygame.init()

        ICON_IMG = pygame.transform.scale(
            pygame.image.load(os.path.join('assets', 'img', 'chocolate.png')),
            (32, 32))
        self._BACKGROUND_IMG = pygame.image.load(
            os.path.join('assets', 'img', 'background.jpg'))
        self._GROUND_IMG = pygame.image.load(
            os.path.join('assets', 'img', 'ground.png'))

        self._PICKED_EGG_SOUND = pygame.mixer.Sound(
            os.path.join('assets', 'sfx', 'picked_egg.wav'))
        self._LOST_EGG_SOUND = pygame.mixer.Sound(
            os.path.join('assets', 'sfx', 'lost_egg.wav'))
        self._GAME_OVER_SOUND = pygame.mixer.Sound(
            os.path.join('assets', 'sfx', 'game_over.wav'))

        self._WIDTH, self._HEIGHT = 800, 480
        self._WIN = pygame.display.set_mode((self._WIDTH, self._HEIGHT))

        pygame.display.set_caption("Egg Hunt")
        pygame.display.set_icon(ICON_IMG)

        self._BLACK = (0, 0, 0)
        self._WHITE = (255, 255, 255)

        self._FONT = pygame.font.Font(None, 60)

        self._CLOCK = pygame.time.Clock()
        self._FPS = 60

        self._basket = Basket(self._WIN)
        self._egg = Egg(self._WIN)
        self._score_bar = ScoreBar(self._WIN)
 def test_empty_basket(self):
     self.test_basket = Basket(self.test_catalouge)
     for product in self.test_products:
         self.test_basket.add_product(product)
     self.assertEqual(len(self.test_basket.products), len(self.test_products))
     self.test_basket.empty()
     self.assertEqual(len(self.test_basket.products), 0)
    def test_basket_subtotal(self):
        # One of each item
        self.test_basket = Basket(self.test_catalouge)
        for product in self.test_products:
            self.test_basket.add_product(product)
        self.assertEqual(self.test_basket.calculate_subtotal(), 12.08)

        self.test_basket.empty()

        # 4 Baked Beans and 1 Biscuits
        # Add 4 Baked Beans
        self.test_basket.add_product(self.test_products[0], 4)
        # Add 1 Biscuits
        self.test_basket.add_product(self.test_products[1])
        self.assertEqual(self.test_basket.calculate_subtotal(), 5.16)

        self.test_basket.empty()

        # With Sardines 25% discount
        self.test_basket = Basket(self.test_catalouge)
        # Add 2 Baked Beans
        self.test_basket.add_product(self.test_products[0], 2)
        # Add 1 Biscuits
        self.test_basket.add_product(self.test_products[1])
        # Add 2 Sardines
        self.test_basket.add_product(self.test_products[2], 2)
        self.assertEqual(self.test_basket.calculate_subtotal(), 6.96)
Пример #10
0
def main(filename, shippingLogic):
	# read items into the itemStore
	# display menu
	# add item to basket in given quantity
	# repeat to display
	# calculate shipping

	
	theStore = ItemStore(filename)
	basket = Basket()
	
	choice = 0
	
	while choice != -1 :
	
		displayItems(theStore)
		choice = int(input('Select item (-1 to quit) '))
	
		if choice == 0:
			printBasket(basket)
			total = basket.getTotalShipping(shippingLogic)
			print('Estimated Shipping cost: '+ str(total))
			
		elif choice != -1:
			qty = int(input('Quantity: '))
	
			addItem(theStore, basket, choice, qty)
	
	printBasket(basket)
	
	total = basket.getTotalShipping(shippingLogic)
	print(shippingLogic.getName() +' Shipping cost: '+ str(total))
Пример #11
0
def basket_list(request):
    context = get_default_context(request)
    basket = Basket(request.session)
    basket_items = basket.get_list()
    
    if request.method == 'GET':
        # Showing basket to user
        context['basket'] = basket_items
        context['form'] = OrderForm()
    else:
        # Checking and posting the order
        form = OrderForm(request.POST)
        if form.is_valid():
            # Valid order
            # Saving to the model
            
            order = Order()
            form_cd  = form.cleaned_data
            summary_info = basket.get_summary_info()
            context['fields'] = order.send_mail(form_cd, basket_items, summary_info, request.session)
            basket.clear()
            return render_to_response('basket/good.html', context)
        else:
            # Invalid order: repeating form
            context['basket'] = basket_items
            context['form'] = form

    return render_to_response('basket/index.html', context)
Пример #12
0
 def new_basket(self):
     self.basket = Basket()
     while True:
         print("--------------------")
         print("Scan a product")
         code = input("code: ")
         print("--------------------")
         self.scan_product(code)
	def setUp(self):
		""" the text fixture, necessary setup for the tests to run
		"""
		self.theShippingLogic = ShippingLogic()
		self.theSaleShippingLogic = SaleShippingLogic()
		self.basket1 = Basket()
		self.basket2 = Basket()
		self.saleItem = SaleItem(['20', '1', "Sweater"])
		self.freeShippingItem = SaleItem(['20', '1', "SweaterFreeShipping", 'FS'])
Пример #14
0
 def test_buy_and_get_free_offer_discount(self):
     # Baked Beans buy one get one free
     self.test_offer = BuyAndGetFreeOffer(self.test_products[0], 1, 1)
     self.test_basket = Basket(self.test_catalouge)
     self.test_basket.add_product(self.test_products[0], 1)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], 0.00)
     # Add 1 more Baked Beans for a total of 2
     self.test_basket.add_product(self.test_products[0], 1)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], self.test_products[0].price)
Пример #15
0
 def test_one_without_dependent(self):
     """
     One target product in the absence of its dependent product doesn't trigger discount.
     """
     product_store = self._create_product_store()
     twix_20_discount = DependentDiscountOffer("twix", "pasta", Decimal("0.2"))
     basket = Basket(product_store)
     twix_basketitem = basket.add("twix")
     self.assertEqual(twix_20_discount.calculate_line_total(twix_basketitem, product_store, basket), Decimal("0.80"))
	def test_CalcWeightForCost(self):
		"""
		"""
		theBasket = Basket()
		
		self.assertEqual(self.theLogic.calcWeightForCost(theBasket), 0)
		
		theBasket.addItem((1, SaleItem(['10', '2', 'TestItem'])))
		self.assertEqual(self.theLogic.calcWeightForCost(theBasket), 2)
Пример #17
0
    def setUp(self):
        catalog = Catalog()

        catalog.addShippingRule("U50", 50, 4.95)
        catalog.addShippingRule("U90", 90, 2.95)
        catalog.addShippingRule("U90", 90, 0)

        catalog.addOffer(BOGO50Offer("BOGO50", "R01"))

        catalog.addProduct(Product("R01", "Red Widget", 32.95))
        catalog.addProduct(Product("G01", "Green Widget", 24.95))
        catalog.addProduct(Product("B01", "Blue Widget", 7.95))

        self.basket = Basket(catalog)
Пример #18
0
class Basket_tests(unittest.TestCase):

    # define setUp for tests
    def setUp(self):
        self.product = Product("Lego1", "Lego Toy", 2.50)
        self.basket = Basket()

    # create test for instance of Product class
    def product_instance_test(self):
        # create instance of product with name, description, and price attribute
        self.product = Product("test", "This is a sample", 2.50)
        # verify attributes of instance of product
        self.assertEqual("test", self.product.name)
        self.assertEqual("This is a sample", self.product.description)
        self.assertEqual(2.50, self.product.price)

    # create test for instance of Basket class
    def basket_instance_test(self):
        # create instance of basket class
        self.basket = Basket()

    # create test to display product details
    def display_product_details_test(self):
        result = self.product.display_product_details()
        self.assertEqual("Product name: Lego1, Desc: Lego Toy, Price: £2.50", result)

    # create test to add a product to the basket
    def add_product_to_basket_test(self):
        result = self.basket.add_product(self.product)
        self.assertEqual(["Lego1", "Lego Toy", 2.50], result)

    # create a test to add product using a dictionary as the container
    def add_prod_to_basket_test(self):
        result = self.basket.add_prods(self.product, 5)
        self.assertEqual({1:["Lego1", "Lego Toy", 2.50, 5]}, result)

    # create test to remove product item from basket items
    def remove_item_from_basket_test(self):
        # add product to basket first
        self.basket.add_prods(self.product)
        result = self.basket.remove_item(self.product)
        self.assertEqual({}, result)

    # create test to raise error when item is tried to be removed from empty basket
    def error_when_item_removed_from_empty_basket_test(self):
        # remove item from empty basket
        #result = self.basket.remove_item(self.product)
        # confirm exception error message is raised
        self.assertRaises(NameError, self.basket.remove_item, self.product)
Пример #19
0
class CashRegister:
    basket = None
    basketOnHold = None

    def __init__(self):
        pass

    def start(self):
        # verification caisse
        # Lancement nouveau panier
        self.new_basket()

    def new_basket(self):
        self.basket = Basket()
        while True:
            print("--------------------")
            print("Scan a product")
            code = input("code: ")
            print("--------------------")
            self.scan_product(code)

    def scan_product(self, code):
        product = ProductDbConnector.get_product_by_code(code)
        if product:
            product_to_add = Product(product)
            self.basket.add_product(product_to_add)
        else:
            print('Produit n\'existe pas')

    def delete_product_from_basket(self, product):
        try:
            self.basket.remove_product(product)
        except ValueError:
            return "Product not found"

    def total_price(self):
        return self.basket.totalPrice

    def pay(self):
        print('Pay')

    def put_basket_on_hold(self):
        self.basketOnHold = BasketOnHold(self.basket)
        self.basket = None
        print('On hold')

    def get_basket_on_hold(self):
        return self.basketOnHold
Пример #20
0
def test_price():
    # We add 3 products to the basket
    cash_register.basket = Basket()
    cash_register.scan_product(products[0]["code"])
    cash_register.scan_product(products[1]["code"])
    cash_register.scan_product(products[2]["code"])
    assert cash_register.total_price() == 15
 def test_basket_discount_buy_2_get_1_free(self):
     # With Baked Beans buy 2 get 1 free
     self.buy_and_get_free_offer = BuyAndGetFreeOffer(self.test_products[0], 2, 1)
     self.test_basket = Basket(self.test_catalouge, [self.buy_and_get_free_offer])
     # Add 4 Baked Beans
     self.test_basket.add_product(self.test_products[0], 4)
     # Add 1 Biscuits
     self.test_basket.add_product(self.test_products[1])
     self.assertEqual(self.test_basket.calculate_discount(), 0.99)
     # Add 4 Baked Beans
     self.test_basket.add_product(self.test_products[0], 4)
     self.assertEqual(self.test_basket.calculate_discount(), 1.98)
     self.assertEqual(self.test_basket.calculate_total(),
                      round_half_up(self.test_products[0].price * 8 +
                      self.test_products[1].price -
                      self.test_basket.calculate_discount(), 2))
Пример #22
0
def run_commands(user_input, customer_basket):
    if user_input is None or len(user_input) < 1:
        error_message()
        return

    whole_command = user_input.lower().split()
    action = whole_command[0]

    if action not in ("add", "sum", "clear"):
        error_message()
        return
    if action == "clear":
        customer_basket = Basket()
    elif action == "add":
        if len(whole_command) != 2:
            error_message()
            return
        add_to_checkout_basket(customer_basket, whole_command[1])
    # TODO: Discuss whether we want the basket to be printed on every action.
    # Currently, the behavior is to print it out on every action, so the "sum" action
    # doesn't need to do anything.
    elif action == "sum":
        pass
    print_basket(customer_basket)
    return customer_basket
Пример #23
0
 def test_percentage_offer_discount(self):
     # Baked Beans buy one get one free
     self.test_offer = PercentageOffer(self.test_products[0], 0.25)
     self.test_basket = Basket(self.test_catalouge)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], 0.00)
     self.test_basket.add_product(self.test_products[0], 1)
     self.assertEqual(self.test_offer.get_discount(
         self.test_basket.products)[0],
         round_half_up(self.test_products[0].price * 0.25, 2)
     )
     # Add 1 more Baked Beans for a total of 2
     self.test_basket.add_product(self.test_products[0], 1)
     self.assertEqual(self.test_offer.get_discount(
         self.test_basket.products)[0],
         round_half_up(self.test_products[0].price * 0.25, 2)
     )
 def test_basket_discount_percent_offer(self):
     # With Sardines 25% discount
     self.percentage_offer = PercentageOffer(self.test_products[2], 0.25)
     self.test_basket = Basket(self.test_catalouge, [self.percentage_offer])
     # Add 2 Baked Beans
     self.test_basket.add_product(self.test_products[0], 2)
     # Add 1 Biscuits
     self.test_basket.add_product(self.test_products[1])
     # Add 2 Sardines
     self.test_basket.add_product(self.test_products[2], 2)
     self.assertEqual(self.test_basket.calculate_discount(), 2 * round_half_up(self.test_products[2].price * 0.25, 2))
     self.assertEqual(self.test_basket.calculate_total(),
                      round_half_up(self.test_products[0].price * 2 +
                      self.test_products[1].price +
                      self.test_products[2].price * 2 -
                      self.test_basket.calculate_discount(), 2))
def run_game(player_name):
	# Initialize game and create a screen object.
	pygame.init()
	cg_settings = Settings()
	screen = pygame.display.set_mode((cg_settings.screen_width, cg_settings.screen_height))
	pygame.display.set_caption("Collect the Eggs!")

	#Make a play button
	play_btn = Button(screen,"Let's Play!!")
	
	#make hidden bsket
	basket_h = Basket_hidden(cg_settings,screen)
	# Make a basket.
	basket = Basket(cg_settings,screen)
	# Make a group of hens.
	hens = []
	#eggs
	eggs_w=Group()
	eggs_g=Group()
	#poops
	poops=Group()
	
	gs = GameStats(cg_settings)
	sb  = Scoreboard(cg_settings,screen,gs)
	sb.prep_score()


	#create the fleet of hens
	gf.create_fleet(cg_settings, screen, hens)
	while True:
		gf.check_events(basket,basket_h,play_btn,gs)
		basket.update()
		basket_h.update(basket)
		gf.eggs_g_update(eggs_g,basket_h,gs,cg_settings.golden_score)
		gf.eggs_w_update(eggs_w,basket_h,gs,cg_settings.white_score)
		gf.poops_update(poops,basket_h,gs,cg_settings.poop_score)
		sb.prep_score()
		if(gs.score>gs.high_score):
			gs.high_score=gs.score
	
		sb.prep_high_score()
		sb.prep_level()

		#gf.create_egg(screen,egg)
		gf.update_screen(cg_settings, screen,sb,basket_h, basket, hens, eggs_w,eggs_g,poops,gs,play_btn)
		gf.check_level_crossed(cg_settings, screen,sb, basket_h,basket, hens, eggs_w,eggs_g, poops,gs,player_name)
    def test_basket_discount_all_offers(self):
        # With bundle offer on all shampoo buy 3 get the cheapest free
        self.bundle_offer_all_shampoo = BundleOffer([self.test_products[3],
                                       self.test_products[4],
                                       self.test_products[5]
                                      ], 3)
        # With bundle offer on small shampoo and sardines buy 2 get the cheapest free
        self.bundle_offer_small_shampoo_and_sardines = BundleOffer([self.test_products[3],
                                        self.test_products[2]
                                      ], 2)

        self.buy_and_get_free_offer_baked_beans = BuyAndGetFreeOffer(self.test_products[0], 2, 1)
        self.percentage_offer_baked_beans = PercentageOffer(self.test_products[0], 0.25)
        self.test_basket = Basket(self.test_catalouge, [
                                        self.bundle_offer_all_shampoo,
                                        self.bundle_offer_small_shampoo_and_sardines,
                                        self.buy_and_get_free_offer_baked_beans,
                                        self.percentage_offer_baked_beans
                                    ])
        # Add 4 Baked Beans
        self.test_basket.add_product(self.test_products[0], 4)
        # Add 1 Biscuits
        self.test_basket.add_product(self.test_products[1])
        # Add 1 sardines
        self.test_basket.add_product(self.test_products[2], 1)
        # Add 3 small shampoo
        self.test_basket.add_product(self.test_products[3], 3)
        # Add 2 medium shampoo
        self.test_basket.add_product(self.test_products[4], 2)
        # Add 3 large shampoo
        self.test_basket.add_product(self.test_products[5], 3)
        # Baked Beans Buy 2 get one free: 0.99
        # Baked Beans 25% percent discount: 0.99 * 0.25 =  0.25
        # One large shampoo for free (3.5)
        # Two small shampoo for free (4.00)
        # Total: 7.5 + 0.99 + 0.25 = 8.74
        self.assertEqual(self.test_basket.calculate_discount(), 8.74)
        self.assertEqual(self.test_basket.calculate_total(),
                         round_half_up(self.test_products[0].price * 4 +
                         self.test_products[1].price +
                         self.test_products[2].price +
                         self.test_products[3].price * 3 +
                         self.test_products[4].price * 2 +
                         self.test_products[5].price * 3 -
                         self.test_basket.calculate_discount(), 2))
    def test_basket_discount_percent_and_buy_2_get_1_free_offers(self):
        # With Baked Beans buy 2 get 1 free and 25% discount
        self.buy_and_get_free_offer = BuyAndGetFreeOffer(self.test_products[0], 2, 1)
        self.percentage_offer = PercentageOffer(self.test_products[0], 0.25)
        self.test_basket = Basket(self.test_catalouge, [self.buy_and_get_free_offer, self.percentage_offer])
        # Add 4 Baked Beans
        self.test_basket.add_product(self.test_products[0], 4)
        # Add 1 Biscuits
        self.test_basket.add_product(self.test_products[1])
        # Baked Beans Buy 2 get one free: 0.99
        # Baked Beans 25% percent discount: 0.99 * 0.25 =  0.25
        # Total: 0.99 + 0.25 = 1.24
        self.assertEqual(self.test_basket.calculate_discount(), 1.24)
        self.assertEqual(self.test_basket.calculate_total(),
                         round_half_up(self.test_products[0].price * 4 +
                         self.test_products[1].price -
                         self.test_basket.calculate_discount(), 2))
        # Add 4 Baked Beans
        self.test_basket.add_product(self.test_products[0], 4)
        # Buy 2 get 1 free twice: 0.99 * 2 = 1.98
        # Percentage discount on remaining 2: 0.99 * 0.25 * 2 = 0.50
        # total: 1.98 + 0.50 = 2.48
        self.assertEqual(self.test_basket.calculate_discount(), 2.48)
        self.assertEqual(self.test_basket.calculate_total(),
                         round_half_up(self.test_products[0].price * 8 +
                         self.test_products[1].price -
                         self.test_basket.calculate_discount(), 2))

        # With Baked Beans buy 2 get 1 free and 50% discount
        self.buy_and_get_free_offer = BuyAndGetFreeOffer(self.test_products[0], 2, 1)
        self.percentage_offer = PercentageOffer(self.test_products[0], 0.50)
        self.test_basket = Basket(self.test_catalouge, [self.buy_and_get_free_offer, self.percentage_offer])
        # Add 4 Baked Beans
        self.test_basket.add_product(self.test_products[0], 4)
        # Add 1 Biscuits
        self.test_basket.add_product(self.test_products[1])
        # Baked Beans Buy 2 get one free: 0
        # Baked Beans 50% percent discount: 0.99 * 0.5 = 2.00
        # Total: 2.00
        self.assertEqual(self.test_basket.calculate_discount(), 2.00)
        self.assertEqual(self.test_basket.calculate_total(),
                         round_half_up(self.test_products[0].price * 4 +
                         self.test_products[1].price -
                         self.test_basket.calculate_discount(), 2))
Пример #28
0
def main(argv):

    # Configure the application, including taxes and categories
    sales_tax_exceptions = []
    if len(argv) > 1:
        with open(argv[1]) as f:
            for line in f:
                sales_tax_exceptions.append(line.strip())

    sales_tax = Tax('0.10')
    import_duty = Tax('0.05')

    # Using the same name for both taxes ensures they're aggregated and
    # printed out on the same line
    categories = [
        ExceptionCategory(
            u'Sales Taxes',
            sales_tax_exceptions,
            lambda i: sales_tax.calculate(i.value * i.quantity)
        ),
        Category(
            u'Sales Taxes',
            [u'imported'],
            last_minute_hack(import_duty)
        ),
#        Category(
#            'Student Discount',
#            ['book'],
#            lambda i: (-1) * sales_tax.calculate(i.value * i.quantity)
#        )
    ]

    # Create a basket
    basket = Basket(categories)

    # Add line items
    with open(argv[0]) as f:
        for line in f:
            line_item = parse_lineitem(line.strip())
            if line_item:
                basket.add_line(line_item)

    # "Checkout"
    print basket.receipt()
Пример #29
0
 def order_button_handler(call):
     obj_id = str.split(call.data)[1]
     product = self.bd.find_product_by_str_obj_id(obj_id)
     if product['qty'] < 1:
         message = 'No product at store'
         self.bot.answer_callback_query(call.id,
                                        message,
                                        show_alert=True)
     else:
         basket = Basket(call.from_user.id)
         basket.add_product(product)
         message = self.make_modal_message(product)
         self.bot.answer_callback_query(call.id,
                                        message,
                                        show_alert=True)
         self.bot.send_message(
             call.from_user.id,
             product[CATEGORY_NAME],
             reply_markup=self.buttons.show_products_from_category(
                 product[CATEGORY_NAME]))
    def process(self, message):

        if message['kind'] not in self.message_processors:
            return []

        basket_id = message['payload']['basket_id']
        events = self.events_repository.get_by_basket_id(basket_id)
        basket = Basket(events)
        process = self.message_processors[message['kind']]

        return process(basket, message['payload'])
Пример #31
0
 def test_bundle_offer_discount(self):
     # Baked Beans, Biscuits, Sardines
     self.test_offer = BundleOffer([self.test_products[0],
                                        self.test_products[1],
                                        self.test_products[2]
                                       ], 3)
     self.test_basket = Basket(self.test_catalouge)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], 0.00)
     self.test_basket.add_product(self.test_products[0], 1)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], 0.00)
     self.test_basket.add_product(self.test_products[1], 1)
     self.test_basket.add_product(self.test_products[2], 1)
     self.test_basket.add_product(self.test_products[3], 1)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], self.test_products[0].price)
     # Add 1 more Baked Beans for a total of 2
     self.test_basket.add_product(self.test_products[0], 1)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], self.test_products[0].price)
     # Add 1 more Biscuits for a total of 2
     self.test_basket.add_product(self.test_products[1], 1)
     self.assertEqual(self.test_offer.get_discount(self.test_basket.products)[0], self.test_products[1].price)
Пример #32
0
 def test_get_total_with_dependent_discount_offer(self):
     """
     Basket get_total returns correct value with dependent discount offer applied.
     """
     product_store = self._create_product_store()
     twix_pasta_20_discount = DependentDiscountOffer("twix", "pasta", Decimal("0.2"))
     basket = Basket(product_store)
     basket.add("twix", 2)
     basket.add("pasta")
     self.assertEqual(basket.get_total(offers=[twix_pasta_20_discount]), Decimal('2.94'))
 def test_basket_discount_bundle_offer(self):
     # With bundle offer on all shampoo buy 3 get the cheapest free
     self.test_offer = BundleOffer([self.test_products[3],
                                    self.test_products[4],
                                    self.test_products[5]
                                   ], 3)
     self.test_basket = Basket(self.test_catalouge, [self.test_offer])
     # Add 2 small shampoo
     self.test_basket.add_product(self.test_products[3], 2)
     # Add 1 medium shampoo
     self.test_basket.add_product(self.test_products[4])
     # Add 3 large shampoo
     self.test_basket.add_product(self.test_products[5], 3)
     # One large shampoo for free (3.5) and One small shampoo for free (2.00)
     # Total: 5.5
     self.assertEqual(self.test_basket.calculate_discount(), 5.5)
     self.assertEqual(self.test_basket.calculate_total(),
                      round_half_up(self.test_products[3].price * 2 +
                      self.test_products[4].price +
                      self.test_products[5].price * 3 -
                      self.test_basket.calculate_discount(), 2))
Пример #34
0
 def test_get_total_with_one_offer(self):
     """
     Basket get_total returns correct value with a bogof offer applied.
     """
     product_store = self._create_product_store()
     bogof_blueberries = MultiBuyOffer("blueberries", 1, 1)
     basket = Basket(product_store)
     basket.add("blueberries", 2)
     basket.add("fish")
     self.assertEqual(basket.get_total(offers=[bogof_blueberries]), Decimal('5.20'))
Пример #35
0
 def show_basket(message):
     basket = Basket(message.from_user.id)
     if message.text == '$ BASKET $':
         show = 'Empty' if not basket.products else basket.show_basket_items(
         )
         boolean = False if show == 'Empty' else True
         self.bot.send_message(
             message.from_user.id,
             show,
             reply_markup=self.buttons.show_basket_menu(boolean))
     elif message.text == 'CLEAR':
         basket.clear_basket()
         self.bot.send_message(
             message.from_user.id,
             CLEARED,
             reply_markup=self.buttons.show_basket_menu(False))
     elif message.text == '<<BACK':
         self.bot.send_message(
             message.from_user.id,
             message.text,
             reply_markup=self.buttons.set_categories())
Пример #36
0
class TestBasket(unittest.TestCase):
    def setUp(self):
        self.basket = Basket()
    def tearDown(self):
        self.basket = None
    def testBasketAppear(self):
        assert self.basket, "Basket must be defined."
    def testBasketCanAddProduct(self):
        self.basket.add(Product())

    def testBsketRemoveProduct(self):
        product = Product()
        self.basket.add(product)
        self.basket.remove(product)
        assert len(self.basket.products) == 0, "Basket must be empty on all products deleted"
        self.basket.add(product)
        self.basket.add(product)
        self.basket.add(product)
        self.basket.remove(product)
        assert self.basket.quantity_for(product) == 2, "Basket mst actually remove product from"
    def testBasketStoresQuantity(self):
        product = Product(1)
        product2 = Product(2)
        self.basket.add(product,5)
        self.basket.add(product2,3)
        assert self.basket.quantity_for(product2) == 3
        assert self.basket.quantity_for(product) == 5
Пример #37
0
def catalog_item(request, slug):
    context = get_default_context(request)
    product = get_object_or_404(Product, slug=slug)
    context['catalog'] = product.catalog
    context['catalog_properties'] = context['catalog'].properties.all()
    
    for size in product.pricing_set.all():
        if size.is_exist:
            context['size_is_exist'] = size.size_id
            break
    
    for p in context['catalog_properties']:
        if p.type == 4:
            fv = request.GET.getlist(p.slug)
            if fv is not None:
                p.filtered_values = fv
        else:
            fv = request.GET.get(p.slug)
            if fv is not None:
                p.filtered_value = fv

    context['catalog_position'] = product
    context['catalog_position_wtp'] = product.wtp.all()
    context['catalog_position_pricing'] = Pricing.objects.filter(product=product).order_by('size')
    context['catalog_position_images'] = product.picture_set.all()
    context['properties'] = get_extended_properties(product)
    context['crumbs'].append({ 
      'caption': product.name, 
      'path': context['current_section'].path + product.slug + '/'
    })
    basket = Basket(request.session)
    context['order_count'] = basket.get_count(product.id)
    
    #title
    if not Metatag.objects.filter(name=context['current_section'].path + product.slug + '/') \
        and product.catalog_id == 10: #пока что только для каталога Обувь
        if not ChangeTitle.objects.filter(path=context['current_section'].path + product.slug + '/'):            
            word_1 = Title.objects.filter(position=1).order_by('?')[0].title
            while True:
                word_2 = Title.objects.filter(position=2).order_by('?')[0].title
                if word_2.lower() != word_1.lower():
                    break
            while True:
                word_3 = Title.objects.filter(position=3).order_by('?')[0].title
                if word_3.lower() != word_1.lower() and word_3.lower() != word_2.lower():
                    break
            while True:
                word_4 = Title.objects.filter(position=4).order_by('?')[0].title
                if word_4.lower() != word_1.lower() and word_4.lower() != word_2.lower() and word_4.lower() != word_3.lower():
                    break
            title = ChangeTitle(path=context['current_section'].path + product.slug + '/', title='%s %s %s %s %s' % (word_1, word_2, context['catalog_position'].name, word_3, word_4))
            title.save()
            context['catalog_position'].title = '%s %s %s %s %s' % (word_1, word_2, context['catalog_position'].name, word_3, word_4)
        else:
            context['catalog_position'].title = ChangeTitle.objects.filter(path=context['current_section'].path + product.slug + '/')[0].title
    #title
    if request.method == 'POST':
        context['author_error'] = False
        context['mes_error'] = False

        if not request.POST.get('q_autor', ''):
            context['author_error'] = True
        else:
            context['q_autor'] = request.POST['q_autor']
        
        if not request.POST.get('q_mes', ''):
            context['mes_error'] = True
        else:
            context['q_mes'] = request.POST['q_mes']
        
        if context['author_error'] or context['mes_error']:
            pass
        else:
            qa = QuestAnswer(author = context['q_autor'], question = context['q_mes'])
#            send_mail(context['q_autor'], context['q_mes'])
            qa.save()
            qa.product_set.add(product)
            context['ok'] = True
    context['unanswered'] = product.qa.order_by('-date_publication').filter(is_public=False)
    context['questanswer'] = product.qa.order_by('-date_publication').filter(is_public=True)
    if 'ajax' in request.GET:
        return render_to_response('catalog/position_ajax.html', context)
    else:
        return render_to_response('catalog/position.html', context)
class TestShippingLogic(unittest.TestCase):
	
	def setUp(self):
		""" the text fixture, necessary setup for the tests to run
		"""
		self.theShippingLogic = ShippingLogic()
		self.theSaleShippingLogic = SaleShippingLogic()
		self.basket1 = Basket()
		self.basket2 = Basket()
		self.saleItem = SaleItem(['20', '1', "Sweater"])
		self.freeShippingItem = SaleItem(['20', '1', "SweaterFreeShipping", 'FS'])
		
	def tearDown(self):
		""" nothing to tear down here
		If your test created a database or built a network connection
		you might delete the database or close the network connection
		here. You might also close files you opened, close your
		TK windows if this is GUI program, or kill threads if this is
		a multithreaded application
		"""
		pass # nothing to do
	
	def test_CalcWeightForCost(self):
		
		self.basket1.addItem(1, self.saleItem)
		costWithFirstItem = self.theShippingLogic.calcWeightForCost()
		
		self.assertEqual(costWithFirstItem, 20)
		
		self.basket1.addItem(1, self.freeShippingItem)
		costWithSecondItem = self.theShippingLogic.calcWeightForCost()
		
		#cost should be the same since free shipping for second item
		self.assertEqual(costWithSecondItem, costWithFirstItem )
		
		self.assertEqual(self.freeShippingItem.getFreeShipping(), True)
		
		
	def test_calcCostForShippingByWeight(self):
		
		self.assertEqual(self.theShippingLogic.calcCostForShippingByWeight( saleItem.getWeight()), 20)
		
		self.assertEqual(self.theShippingLogic.calcCostForShippingByWeight(freeShippingItem.getWeight()), 0)
		
		
	def test_CalcWeightForCostWithSaleShipping (self):
		
		self.basket2.addItem(1, self.saleItem)
		costWithFirstItem = self.theSaleShippingLogic.calcWeightForCost()
		
		self.assertEqual(costFirstItem, 20)
		
		self.basket2.addItem(1, self.freeShippingItem)
		costWithSecondItem = self.theShippingLogic.calcWeightForCost()
		
		#cost should be the same since free shipping for second item
		self.assertEqual(costWithSecondItem, costWithFirstItem )
		
	def test_calcCostForShippingByWeightForSaleShipping(self):
		
		self.assertEqual(self.theSaleShippingLogic.calcCostForShippingByWeight( saleItem.getWeight()), 5)
		
		self.assertEqual(self.theSaleShippingLogic.calcCostForShippingByWeight(freeShippingItem.getWeight()), 5)
	def setUp (self):
		self.theBasket = Basket ()
Пример #40
0
 def setUp(self):
     self.product = Product("Lego1", "Lego Toy", 2.50)
     self.basket = Basket()
Пример #41
0
 def setUp(self):
     self.basket = Basket()
Пример #42
0
 def basket_instance_test(self):
     # create instance of basket class
     self.basket = Basket()