Esempio n. 1
0
def vending_machine_gen(price_list, additional_drinks):

    vending_machine = VendingMachine(price_list)
    for d in additional_drinks:
        vending_machine.add_drink(d)

    return vending_machine
 def test_display_shows_insert_coins(self):
     vendmachine = VendingMachine()
     # add coins to vending machine so that it does not display the exact change only message
     map(vendmachine.add_to_coin_bank, [self.dime, self.nickle])
     current_balance = vendmachine.get_current_balance()
     if current_balance < vendmachine.get_product_price("cola"):
         self.assertEqual(vendmachine.check_display(), "INSERT COINS")
Esempio n. 3
0
def test_buy_product_returns_instance_when_valid():
    machine = VendingMachine()
    machine.insert_coin(coins.Toonie())
    machine.insert_coin(coins.Toonie())
    result = machine.buy_product(products.Drink)

    assert isinstance(result, products.Drink)
Esempio n. 4
0
def buy_product(request):
    vm = VendingMachine()
    try:
        vm.buy_product()
        return JsonResponse({'msg': vm.message, 'product': "product"})
    except RuntimeError as e:
        return JsonResponse({'msg': e.message, 'product': None})
Esempio n. 5
0
 def test_half_dollar_and_quarter(self):
     fsm = VendingMachine()
     events = [Coin.half_dollar, Coin.quarter]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([fsm.start_state, fsm.dispensing], fsm.history)
     self.assertEqual(fsm.change, 0)
Esempio n. 6
0
 def test_three_dimes(self):
     fsm = VendingMachine()
     events = [Coin.dime, Coin.dime, Coin.dime]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([fsm.start_state, fsm.got_10, fsm.got_20,
                       fsm.dispensing], fsm.history)
     self.assertEqual(fsm.change, 5)
Esempio n. 7
0
 def test_nickel_and_quarter(self):
     fsm = VendingMachine()
     events = [Coin.nickel, Coin.quarter]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([fsm.start_state, fsm.got_5, fsm.dispensing],
                      fsm.history)
     self.assertEqual(fsm.change, 5)
Esempio n. 8
0
 def test_six_nickels(self):
     fsm = VendingMachine()
     events = [Coin.nickel, Coin.nickel, Coin.nickel, Coin.nickel,
               Coin.nickel, Coin.nickel, Coin.nickel]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([fsm.start_state, fsm.got_5, fsm.got_10, fsm.got_15,
                       fsm.got_20, fsm.dispensing], fsm.history)
     self.assertEqual(fsm.change, 0)
Esempio n. 9
0
def main():
    print('===order a cup of coffee===')
    order_a_coffee(VendingMachine(3))
    print('===order two cup of coffee===')
    order_two_coffee(VendingMachine(3))
    print('===order a cup of coffee, but money is not correct===')
    order_coffe_but_not_correct_money(VendingMachine(3, 20))
    print('===eject money===')
    eject_money(VendingMachine(3))
    print('===eject money failed===')
    eject_money_fail(VendingMachine(3))
def test_accept_coins(machine: VendingMachine, printer: VendingMachinePrinter,
                      coins: dict):
    # TODO: use the printer and approvaltests.verify instead of assertions

    assert machine.display == "INSERT COIN"

    machine.insert_coin(coins["nickel"])

    assert machine.balance == 5
    assert machine.coins == [5]
    assert machine.display == "5"
def main():
    vending_machine = VendingMachine()

    vending_machine.dispense_product()
    print()

    vending_machine.insert_money_and_select_product(3, 'Pepsi')
    print()

    vending_machine.insert_money_and_select_product(3, 'Fanta')
    print()
    vending_machine.dispense_product()
Esempio n. 12
0
def input_action(machine: VendingMachine):

    while True:
        print("Possible actions:")
        print(
            "1. Refill\n2. Insert Coin\n3. Make Selection\n4. Cancel\n5. Quit\n"
        )
        print("Current State: {}".format(machine.state))
        try:
            action = int(
                input(
                    "What action would you like to take? (Enter the number): ")
            )

            if action < 1 or action > 5:
                print("Please enter a valid choice(1-5)")
                continue

            if action == 1:
                machine.refill()
            elif action == 2:
                machine.insert_coin()
            elif action == 3:
                machine.make_selection()
            elif action == 4:
                machine.cancel()
            elif action == 5:
                break

        except ValueError:
            print("Please enter a valid choice (1-4)")
 def initialize_vending_machine(self):
     max_quantity = None
     cost_of_each_item = None
     for line in self.all_commands:
         if len(line) > 0 and (max_quantity is None or cost_of_each_item is None):
             values = list(map(lambda x: x.strip(), line.split(',')))
             match values[0]:
                 case 'maxquantity': max_quantity = int(values[1])
                 case 'costofeachitem': cost_of_each_item = int(values[1])
                 case _: pass
     
     if max_quantity is not None and cost_of_each_item is not None:
         self.vending_machine = VendingMachine(max_quantity, cost_of_each_item)
     else:
         print('Unable to initialize vending machine')
         exit(0)
Esempio n. 14
0
def main():

    SORT_DICTIONARY = {
        'n': 'item_name',
        'p': 'percent_sold',
        's': 'stock_required'
    }

    vendingMachineFileNames = [
        './REID_1F_20171004.json', './REID_2F_20171004.json',
        './REID_3F_20171004.json'
    ]
    vendingMachines = []

    for fileName in vendingMachineFileNames:
        jsonFile = open(fileName, 'r')
        machineData = json.loads(jsonFile.read())
        vendingMachines.append(VendingMachine(machineData))

    vendingMachineMgr = VendingMachineMgr(vendingMachines, SORT_DICTIONARY)

    reportType = input(
        'Would you like the (m)achine report or the (i)nventory report? ')

    if reportType == 'i':
        mainLoop(vendingMachineMgr, SORT_DICTIONARY)
    else:
        vendingMachineMgr.printInventory()
Esempio n. 15
0
def test_get_balance_returns_sum_of_coins_minus_purchases():
    machine = VendingMachine()
    machine.insert_coin(coins.Toonie())
    machine.insert_coin(coins.Toonie())
    machine.buy_product(products.Candy)

    assert machine.get_balance() == 85
 def setUp(self):
     self.vendmachine = VendingMachine()
     self.quarter = Coin(weight=5.670, diameter=24.26, thickness=1.75)
     self.dime = Coin(weight=2.268, diameter=17.91, thickness=1.35)
     self.nickle = Coin(weight=5.000, diameter=21.21, thickness=1.95)
     self.penny = Coin(weight=2.500, diameter=19.05, thickness=1.52)
     # stock the machine
     for item in ["cola", "candy", "chips"]:
         map(self.vendmachine.inventory[item].append, repeat(item, 20))
Esempio n. 17
0
    def test_coin_over_product_can_change_ten(self):
        one = 3
        five = 0
        ten = 2
        product = 1

        result = VendingMachine(one, five, ten, product)
        self.assertEqual(result['one'], 0)
        self.assertEqual(result['five'], 0)
        self.assertEqual(result['ten'], 1)
        self.assertEqual(result['status'], 0)
Esempio n. 18
0
    def test_coin_less_product_not_change(self):
        one = 3
        five = 0
        ten = 0
        product = 1

        result = VendingMachine(one, five, ten, product)
        self.assertEqual(result['one'], 3)
        self.assertEqual(result['five'], 0)
        self.assertEqual(result['ten'], 0)
        self.assertEqual(result['status'], 1)
Esempio n. 19
0
    def test_not_product_not_change(self):
        one = 1
        five = 1
        ten = 1
        product = 4

        result = VendingMachine(one, five, ten, product)
        self.assertEqual(result['one'], 1)
        self.assertEqual(result['five'], 1)
        self.assertEqual(result['ten'], 1)
        self.assertEqual(result['status'], 1)
 def test_return_coins(self):
     vendmachine = VendingMachine()
     # check that the coin return is empty
     self.assertEqual(vendmachine.check_coin_return(), [])
     # insert coins
     my_coins = [self.quarter, self.quarter, self.dime]
     for coin in my_coins:
         vendmachine.insert_coin(coin)
     vendmachine.return_coins()
     change = vendmachine.take_out_coins_from_coin_return()
     self.assertEqual(self.count_change(my_coins), self.count_change(change))
     # check that the coin return is empty again
     self.assertEqual(vendmachine.check_coin_return(), [])
Esempio n. 21
0
class TestVendingMachine(unittest.TestCase):

    def setUp(self):
        self.vending = VendingMachine(156700)
        self.stock = {'root beer': 10, 'coca-cola': 10, 'sprite': 30}
        self.sorted_stock = sorted(self.stock.items(), key=lambda x: x[1])

    def get_stock_test (self):
		self.assertEqual(self.vending.get_stock(),{'coca-cola': 10,
		 'sprite': 10,'root beer': 10})

    def test_replenish_test(self):
        self.vending.replenish('sprite',20)
        self.assertEqual(self.sorted_stock,[('coca-cola', 10),
         ('root beer', 10), ('sprite', 30)])

    def test_sell(self):
        self.vending.sell('sprite')
        self.assertEqual(self.sorted_stock,[('coca-cola', 10),
         ('root beer', 10), ('sprite', 30)])
Esempio n. 22
0
 def test_half_dollar_and_quarter(self):
     fsm = VendingMachine()
     events = [Coin.half_dollar, Coin.quarter]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([fsm.start_state, fsm.dispensing], fsm.history)
     self.assertEqual(fsm.change, 0)
Esempio n. 23
0
 def test_dime_and_quarter(self):
     fsm = VendingMachine()
     events = [Coin.dime, Coin.quarter]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([fsm.start_state, fsm.got_10, fsm.dispensing],
                      fsm.history)
     self.assertEqual(fsm.change, 10)
 def test_inserted_penny_is_returned(self):
     vendmachine = VendingMachine()
     current_balance = vendmachine.get_current_balance()
     # penny should be returned when inserted
     vendmachine.insert_coin(self.penny)
     # check that the penny was placed in the coin return
     self.assertEqual(vendmachine.check_coin_return(), [self.penny])
     # current balance should not have changed
     self.assertEqual(vendmachine.get_current_balance(), current_balance)
Esempio n. 25
0
def test_inserted_coins_are_appended_to_coin_list():
    machine = VendingMachine()
    machine.insert_coin(coins.Loonie())
    machine.insert_coin(coins.Toonie())
    machine.insert_coin(coins.Quarter())

    assert machine.inserted_coins == [
        coins.Loonie(), coins.Toonie(),
        coins.Quarter()
    ]
Esempio n. 26
0
def main():
    seleccion = [3, 1, 4]

    producto1 = Producto(1, "Botella de Agua", 5, 1.00)
    producto2 = Producto(2, "Coca Cola", 10, 1.50)
    producto3 = Producto(3, "Papas Fritas", 7, 0.50)
    producto4 = Producto(4, "Chifles", 11, 1.25)
    producto5 = Producto(5, "Granola", 15, 2.50)

    productos = [producto1, producto2, producto3, producto4, producto5]

    vm1 = VendingMachine("Maquina Generica")
    cargaProductos(vm1, productos)
    verProductosDisponibles(vm1)

    venta(vm1, seleccion, 20.00)

    verProductosDisponibles(vm1)
Esempio n. 27
0
 def test_four_nickels_and_quarter(self):
     fsm = VendingMachine()
     events = [
         Coin.nickel, Coin.nickel, Coin.nickel, Coin.nickel, Coin.quarter
     ]
     fsm.start()
     for event in events:
         fsm.handle_event(event)
     self.assertEqual([
         fsm.start_state, fsm.got_5, fsm.got_10, fsm.got_15, fsm.got_20,
         fsm.dispensing
     ], fsm.history)
     self.assertEqual(fsm.change, 20)
Esempio n. 28
0
def main():
    # Prepare Inventory
    obj_inventory = Inventory.get_instance()
    all_item_with_qty = get_total_items_qty()
    for item,qty in all_item_with_qty.items():
        obj_inventory.add_ingredient_to_inventory(item, qty)
    all_beverages = get_all_beverages()
    beverages = list()
    outlets = get_total_outlets()
    vending_machine = VendingMachine.get_instance(outlets)
    for beverage,ingredient_with_qty in all_beverages.items():
        ingredients = list()
        for ingredient,qty in ingredient_with_qty.items():
            obj_ingredient = Ingredient(ingredient, qty)
            ingredients.append(obj_ingredient)
        beverage = Beverage(beverage, ingredients)
        vending_machine.add_new_beverage(beverage)
        beverages.append(beverage)
    for beverage in beverages:
        try:
            vending_machine.make_beverage(beverage)
        except Exception as e:
            print(e)
Esempio n. 29
0
 def setUp(self):
     self.vending = VendingMachine(156700)
     self.stock = {'root beer': 10, 'coca-cola': 10, 'sprite': 30}
     self.sorted_stock = sorted(self.stock.items(), key=lambda x: x[1])
Esempio n. 30
0
def main():
    vm = VendingMachine() 
    vm.add_product(Product("水", 100))
    vm.add_product(Product("ビール", 350))
    vm.add_product(Product("コーラ", 120))    

    for id, product in vm.products.items():
        print("%d) %s : %d 円" % (id, product.name, product.price))    
    id = int(input("購入する商品の番号を選んでください >> "))
    while(True):
        input_str = input("お金を入れてください(0で止まります) >> ")
        try:
            if(input_str == "0"):
                break
            currency = Currency(int(input_str))
        except ValueError as f:
            print("10, 50, 100, 500, 1000のどれかを指定してください。 ")
            continue
        vm.insert_money(currency)
        
    vm.buy(id)
    vm.return_change()
    print(f'現在の売り上げは{vm.profit}円です。')
Esempio n. 31
0
        try:
            action = int(
                input(
                    "What action would you like to take? (Enter the number): ")
            )

            if action < 1 or action > 5:
                print("Please enter a valid choice(1-5)")
                continue

            if action == 1:
                machine.refill()
            elif action == 2:
                machine.insert_coin()
            elif action == 3:
                machine.make_selection()
            elif action == 4:
                machine.cancel()
            elif action == 5:
                break

        except ValueError:
            print("Please enter a valid choice (1-4)")


if __name__ == '__main__':
    vending_machine = VendingMachine()
    vending_machine.refill()

    input_action(vending_machine)
Esempio n. 32
0
def index(request):
    vm = VendingMachine()
    vm.reset()
    return render(request, 'vending_machine/index.html', {'msg': vm.message})
 def setUp(self):
     self.machine = VendingMachine(0.5, 1.0, 0.65)
     pass
Esempio n. 34
0
 def test_compra_coca_com_1_dolar(self):
     maquina = VendingMachine()
     maquina.comprar("coca", 1.0) |should| equal_to (True)
Esempio n. 35
0
 def test_maquina_criada(self):
     maquina = VendingMachine()
     maquina.produtos.has_key('coca') |should| equal_to (True)
     maquina.produtos.has_key('fandangos') |should| equal_to (True)
     maquina.produtos.has_key('chetoos') |should_not| equal_to (True)
 def setUp(self):
     self.outlets = 3
     self.inventory = Inventory.get_instance(self.outlets)
     self.vending_machine = VendingMachine.get_instance()
Esempio n. 37
0
from vending_machine import VendingMachine
from drink import Drink

if __name__ == '__main__':
    print('# 200円を入れて 0: COKE を購入')

    money = 200
    drink_type = 0
    vending_machine = VendingMachine()
    my_drink = vending_machine.buy(money, drink_type)
    change = vending_machine.refund()

    print('Drink: {}'.format(my_drink))
    print('Change: {}'.format(change))
    print('->100円か500円しか受け付けないのでそのまま返ってくる')

    print('# 500円を入れて 1: DIET_COKE を購入')

    money = 500
    drink_type = 1
    vending_machine = VendingMachine()
    my_drink = vending_machine.buy(money, drink_type)
    change = vending_machine.refund()

    print('Drink: {}'.format(my_drink.get_kind()))
    print('Change: {}'.format(change))
    print('->DIET_COKEが出て400円返ってくる')
Esempio n. 38
0
            action = " ".join(s[:3])
            args = s[3:]

            try:
                self.actions[action](*args)
            except:
                print(f"Unknown command '{s}'")
                sys.exit(1)


if __name__ == '__main__':
    exampleSnackbar = Snackbar("Python's Snackbar")
    exampleSnackbar.run()

    # create Vending Machines
    vm1 = VendingMachine("Food")
    vm2 = VendingMachine("Drink")

    # create Snacks
    s1 = Snack("Chips", 200, 1.00, vm1.getId())
    s2 = Snack("Chocolate Bar", 200, 1.00, vm1.getId())
    s3 = Snack("Pretzels", 200, 1.00, vm1.getId())

    s4 = Snack("Soda", 200, 1.00, vm2.getId())
    s5 = Snack("Water", 200, 1.00, vm2.getId())

    # 1. Customer 1 buys 3 of snack 4. Print Customer 1 Cash on hand. Print quantity of snack 4.
    print("\n--#1-----------")
    print(f"{c1.getName()}'s initial cash: {c1.getCash()}")

    print(c1.buyTotal(s4, 3))
Esempio n. 39
0
 def test_maquina_tem_produto(self):
     maquina = VendingMachine()
     maquina.tem_produto("chocolate") |should| equal_to (False)
     maquina.tem_produto("coca") |should| equal_to (True)
Esempio n. 40
0
 def test_maquina_tem_chiclete(self):
     maquina = VendingMachine()
     maquina.tem_produto("chiclete") |should| equal_to (False)
Esempio n. 41
0
 def test_compra_chocolate_com_50_cents(self):
     maquina = VendingMachine()
     maquina.comprar("chocolate", 0.50) |should| equal_to (False)
Esempio n. 42
0
 def scope_function(self):
     self.vm = VendingMachine()
     yield
 def test_current_balance_in_machine_is_zero_on_startup(self):
     newmachine = VendingMachine()
     self.assertEqual(newmachine.get_current_balance(), 0)
Esempio n. 44
0
class Test:

    vm: VendingMachine

    @pytest.fixture(scope='function', autouse=True)
    def scope_function(self):
        self.vm = VendingMachine()
        yield

    def test_dispense_cola_beverage(self):

        self.vm.insert(Coin._100)
        beverage = self.vm.push_button('コーラ')

        assert beverage.name == 'コーラ'

    def test_dispense_beverage(self):
        self.vm.insert(Coin._100)
        beverage = self.vm.push_button('烏龍茶')

        assert isinstance(beverage, Beverage)

    def test_dispense_oolong_tea_beverage(self):
        self.vm.insert(Coin._100)
        beverage = self.vm.push_button('烏龍茶')

        assert beverage.name == '烏龍茶'

    def test_dispense_beverage_not_found_zavas(self):
        self.vm.insert(Coin._100)
        with pytest.raises(BeverageNotFoundError):
            beverage = self.vm.push_button('zavas')

    def test_dispense_cola_without_insert_coin(self):
        with pytest.raises(InsufficientAmountError):
            assert 'コーラ' == self.vm.push_button('コーラ')

    def test_insert_100_yen(self):
        self.vm.insert(Coin._100)

    def test_insert_10_yen(self):
        with pytest.raises(ValueError):
            self.vm.insert(Coin._10)

    def test_is_existing_cola(self):
        assert not self.vm.is_not_existing('コーラ')

    def test_is_existing_oolong_tea(self):
        assert not self.vm.is_not_existing('烏龍茶')

    def test_is_not_existing_zavas(self):
        assert self.vm.is_not_existing('zavas')
Esempio n. 45
0
 def test_compra_coca_com_2_dolares(self):
     maquina = VendingMachine()
     maquina.comprar("coca",2.0) |should| equal_to(True)
     maquina.troco |should| equal_to (1)
class VendingMachineTests(unittest.TestCase):
    def setUp(self):
        self.machine = VendingMachine(0.5, 1.0, 0.65)
        pass

    def test_sold_out(self):
        self.assertEqual(self.machine.has_product("CHIPS"), None)

    def test_show_zero_fifty_as_total_chip(self):
        self.assertEqual(self.machine.get_chips_price(), 0.50)

    def test_show_one_as_total_cola(self):
        self.assertEqual(self.machine.get_cola_price(), 1)

    def test_show_zero_sixty_five_as_total_candy(self):
        self.assertEqual(self.machine.get_candy_price(), 0.65)

    def test_coin_accepted(self):
        self.assertTrue(self.machine.insert_coin("NICKELS"))
        self.assertTrue(self.machine.insert_coin("DIMES"))
        self.assertTrue(self.machine.insert_coin("QUARTERS"))

    def test_coin_non_accepted(self):
        self.assertFalse(self.machine.insert_coin("PENNIES"))

    def test_display_insert_coin_when_zero_amount(self):
        self.assertEqual(self.machine.display(), "INSERT COIN")

    def test_display_quarter_credit(self):
        self.machine.insert_coin("QUARTERS")
        self.assertEqual(self.machine.display(), 0.25)

    def test_display_penny_credit(self):
        self.machine.insert_coin("PENNIES")
        self.assertEqual(self.machine.display(), "INSERT COIN")

    def test_display_two_quarters(self):
        self.machine.insert_coin("QUARTERS")
        self.machine.insert_coin("QUARTERS")
        self.assertEqual(self.machine.display(), 0.50)

    def test_display_one_pennie_two_quarters(self):
        self.machine.insert_coin("QUARTERS")
        self.machine.insert_coin("QUARTERS")
        self.machine.insert_coin("PENNIES")
        self.assertEqual(self.machine.display(), 0.50)

    def test_display_one_quarter_and_one_dime(self):
        self.machine.insert_coin("QUARTERS")
        self.machine.insert_coin("DIMES")
        self.assertEqual(self.machine.display(), 0.35)

    def test_display_one_quarter_and_one_nickel(self):
        self.machine.insert_coin("QUARTERS")
        self.machine.insert_coin("NICKELS")
        self.assertEqual(self.machine.display(), 0.30)
Esempio n. 47
0
from vending_machine import VendingMachine
from currency import Yen100Coin
from currency import Yen500Coin
from drink import Coke
from drink import DietCoke
from payment import Payment

if __name__ == '__main__':
    print('# 200円を入れて 0: COKE を購入')

    payment = Payment([Yen100Coin(), Yen100Coin()])
    drink_type = Coke
    vending_machine = VendingMachine()
    my_drink = vending_machine.buy(payment, drink_type)
    change = vending_machine.refund()

    print('Drink: {}'.format(my_drink))
    print('Change: {}'.format(change))
    print('->100円か500円しか受け付けないのでそのまま返ってくる')

    print('# 500円を入れて 1: DIET_COKE を購入')

    payment = Payment([Yen500Coin()])
    drink_type = DietCoke
    vending_machine = VendingMachine()
    my_drink = vending_machine.buy(payment, drink_type)
    change = vending_machine.refund()

    print('Drink: {}'.format(my_drink))
    print('Change: {}'.format(change))
    print('->DIET_COKEが出て400円返ってくる')
Esempio n. 48
0
import os
from flask import Flask, request

from vending_machine import VendingMachine

vm = VendingMachine()

app = Flask(__name__)


@app.route('/api/load_json', methods=['POST'])
def load_json():
    json_data = eval(request.json.get('json_data'))
    if vm.load_stock(json_data):
        return {"result": "success"}
    else:
        return {"result": "failed"}


@app.route('/api/items', methods=['GET'])
def get_items():
    return {"items": vm.get_items()}


@app.route('/api/insert_money', methods=['POST'])
def insert_money():
    print(request.json)
    money = request.json.get('money')
    if vm.insert_money(money):
        return {"result": "success"}
    else:
class TestVendingMachine(unittest.TestCase):
    def setUp(self):
        self.vendmachine = VendingMachine()
        self.quarter = Coin(weight=5.670, diameter=24.26, thickness=1.75)
        self.dime = Coin(weight=2.268, diameter=17.91, thickness=1.35)
        self.nickle = Coin(weight=5.000, diameter=21.21, thickness=1.95)
        self.penny = Coin(weight=2.500, diameter=19.05, thickness=1.52)
        # stock the machine
        for item in ["cola", "candy", "chips"]:
            map(self.vendmachine.inventory[item].append, repeat(item, 20))

    def test_product_price_is_int(self):
        self.assertTrue(isinstance(self.vendmachine.get_product_price("chips"), int))

    def test_product_to_dollar_string_price(self):
        self.assertEqual(self.vendmachine.product_to_dollar_string_price("candy"), "$0.65")
        self.assertEqual(self.vendmachine.product_to_dollar_string_price("cola"), "$1.00")
        self.assertEqual(self.vendmachine.product_to_dollar_string_price("chips"), "$0.50")

    def test_product_list_exists(self):
        self.assertTrue(isinstance(self.vendmachine.get_product_list(), list))

    def test_detect_coin_value(self):
        self.assertEqual(self.vendmachine.detect_coin_value(self.quarter), 25)
        self.assertEqual(self.vendmachine.detect_coin_value(self.dime), 10)
        self.assertEqual(self.vendmachine.detect_coin_value(self.nickle), 5)
        self.assertEqual(self.vendmachine.detect_coin_value(self.penny), None)

    def test_current_balance_in_machine_is_zero_on_startup(self):
        newmachine = VendingMachine()
        self.assertEqual(newmachine.get_current_balance(), 0)

    def test_inserted_coin_updates_current_balance(self):
        current_balance = self.vendmachine.get_current_balance()
        current_coin_return = self.vendmachine.check_coin_return()
        # insert the nickle and check that it is not returned
        self.vendmachine.insert_coin(self.nickle)
        # check that the coin return has not changed
        self.assertEqual(self.vendmachine.check_coin_return(), current_coin_return)
        self.assertEqual(self.vendmachine.get_current_balance(), current_balance + 5)

    def test_inserted_penny_is_returned(self):
        vendmachine = VendingMachine()
        current_balance = vendmachine.get_current_balance()
        # penny should be returned when inserted
        vendmachine.insert_coin(self.penny)
        # check that the penny was placed in the coin return
        self.assertEqual(vendmachine.check_coin_return(), [self.penny])
        # current balance should not have changed
        self.assertEqual(vendmachine.get_current_balance(), current_balance)

    def test_empty_out_coins_from_machine(self):
        coin_collection = self.vendmachine.take_out_coins()
        self.assertTrue(isinstance(coin_collection, list))
        updated_coin_collection = self.vendmachine.take_out_coins()
        self.assertEqual(updated_coin_collection, [])

    def test_inserted_coins_are_added_to_bank_after_purchase(self):
        _ = self.vendmachine.take_out_coins()
        # insert $0.50
        my_coins = [self.quarter, self.quarter]
        map(self.vendmachine.insert_coin, my_coins)
        # no coins should be in bank before purchase
        self.assertEqual(self.vendmachine.take_out_coins(), [])
        # purchase chips
        self.vendmachine.dispense_product("chips")
        # coins should now be in the coin bank
        self.assertEqual(self.vendmachine.take_out_coins(), my_coins)

    def test_display_shows_insert_coins(self):
        vendmachine = VendingMachine()
        # add coins to vending machine so that it does not display the exact change only message
        map(vendmachine.add_to_coin_bank, [self.dime, self.nickle])
        current_balance = vendmachine.get_current_balance()
        if current_balance < vendmachine.get_product_price("cola"):
            self.assertEqual(vendmachine.check_display(), "INSERT COINS")

    def test_dispense_product(self):
        # add coins to vending machine so that it does not display the exact change only message
        map(self.vendmachine.add_to_coin_bank, [self.dime, self.nickle])
        for i in range(2):
            my_product = self.vendmachine.dispense_product("chips")
            self.assertEqual(my_product, None)  # no coins inserted
            self.assertEqual(self.vendmachine.check_display(), "PRICE $0.50")
            self.assertEqual(self.vendmachine.check_display(), "INSERT COINS")
        # insert quarters
        value_inserted = 0
        for i in range(2):
            self.vendmachine.insert_coin(self.quarter)
            value_inserted += 25
            self.assertEqual(self.vendmachine.check_display(), "$0.{0}".format(value_inserted))
        my_product = self.vendmachine.dispense_product("chips")
        self.assertEqual(my_product, "chips")
        self.assertEqual(self.vendmachine.check_display(), "THANK YOU")
        self.assertEqual(self.vendmachine.current_balance, 0)
        self.assertEqual(self.vendmachine.check_display(), "INSERT COINS")

    def test_return_coins(self):
        vendmachine = VendingMachine()
        # check that the coin return is empty
        self.assertEqual(vendmachine.check_coin_return(), [])
        # insert coins
        my_coins = [self.quarter, self.quarter, self.dime]
        for coin in my_coins:
            vendmachine.insert_coin(coin)
        vendmachine.return_coins()
        change = vendmachine.take_out_coins_from_coin_return()
        self.assertEqual(self.count_change(my_coins), self.count_change(change))
        # check that the coin return is empty again
        self.assertEqual(vendmachine.check_coin_return(), [])

    def count_change(self, change_list):
        change_value = 0
        for coin in change_list:
            change_value += self.vendmachine.detect_coin_value(coin)
        return change_value

    def count_returned_change(self):
        # count returned change
        return self.count_change(self.vendmachine.take_out_coins_from_coin_return())

    def test_make_change(self):
        # make sure coin return is empty
        if not len(self.vendmachine.check_coin_return()) == 0:
            # take out all the coins
            _ = self.vendmachine.take_out_coins_from_coin_return()
        # insert $0.90
        map(self.vendmachine.insert_coin, [self.quarter, self.quarter, self.quarter, self.dime, self.nickle])
        # buy candy
        self.vendmachine.dispense_product("candy")
        # check coin return
        self.assertEqual(25, self.count_returned_change())
        # insert $0.75
        map(self.vendmachine.insert_coin, repeat(self.quarter, 3))
        # buy candy again
        self.vendmachine.dispense_product("candy")
        self.assertEqual(10, self.count_returned_change())

    def test_exact_change_only(self):
        # take out all the coins from the machine
        _ = self.vendmachine.take_out_coins()
        # test that the screen displays that the exact change is needed on each check of the display
        for i in range(5):
            self.assertEqual("EXACT CHANGE ONLY", self.vendmachine.check_display())

    def test_sold_out(self):
        # buy all the cola in the machine
        while len(self.vendmachine.inventory["cola"]) > 0:
            # insert $1.00
            map(self.vendmachine.insert_coin, repeat(self.quarter, 4))
            # buy cola
            self.assertEqual("cola", self.vendmachine.dispense_product("cola"))
        # insert $1.00
        map(self.vendmachine.insert_coin, repeat(self.quarter, 4))
        # try to buy cola
        self.assertEqual(None, self.vendmachine.dispense_product("cola"))
        # check that it displays that the item is sold out
        self.assertEqual("SOLD OUT", self.vendmachine.check_display())
def machine():
    return VendingMachine()
Esempio n. 51
0
def insert_coin(request):
    vm = VendingMachine()
    vm.insert_coin(1)
    return JsonResponse({'msg': vm.message})