Fixing python/nose2/bin/nose2: not found - python

I am taking a test in OOP, where I am expected to create a ShoppingCart.
I have written my code which passes all the test from unittest, but when I try to submit, I get this error/bug
/bin/sh: 1: python/nose2/bin/nose2: not found
Below I have shown my code and the unittest.
Unittiest
import unittest
class ShoppingCartTestCases(unittest.TestCase):
def setUp(self):
self.cart = ShoppingCart()
self.shop = Shop()
def test_cart_property_initialization(self):
self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct')
self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary')
def test_add_item(self):
self.cart.add_item('Mango', 3, 10)
self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items')
self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item')
def test_remove_item(self):
self.cart.add_item('Mango', 3, 10)
self.cart.remove_item('Mango', 2, 10)
self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item')
self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item')
def test_checkout_returns_correct_balance(self):
self.cart.add_item('Mango', 3, 10)
self.cart.add_item('Orange', 16, 10)
self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct')
self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct')
def test_shop_is_instance_of_shopping_cart(self):
self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart')
def test_shop_remove_item_method(self):
for i in range(15):
self.shop.remove_item()
self.assertEqual(self.shop.quantity, 85)
myCOde
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
if item_name and quantity >= 1:
self.items.update({item_name : quantity})
if quantity and price >= 1:
self.total += (quantity * price)
def remove_item(self, item_name, quantity, price):
self.total -= (quantity * price)
if quantity >= self.items[item_name]:
try:
del self.items[item_name]
except (KeyError, ValueError):
return None
self.items[item_name] -= quantity
def checkout(self, cash_paid):
balance = 0
if cash_paid < self.total:
return "Cash paid not enough"
balance = cash_paid - self.total
return balance
class Shop(ShoppingCart):
def __init__(self):
ShoppingCart.__init__(self)
self.quantity = 100
def remove_item(self):
self.quantity -= 1

The root cause of the issue lies in the setUp() method in the unittest class. So running the unittest class on a python development environment such as IDLE exposes the issue further.
The full error actually is something like this
" Desktop/practice python/shoppingcarttestcases.py", line 4, in setUp
self.cart = ShoppingCart()
NameError: global name 'ShoppingCart' is not defined"
The solution may lie around properly defining/inheriting/implementing the class Shopping Cart.
I hope this narrows it down.
If you find this helpful and you get a solution please post on the forum as well.

Related

How to assign subtotal from one function to another function?

I have to set the total_cost variable to be equal to the subtotal variable or the from the product class. However, when I try to derive the value from the class. It gives me an attribute error of AttributeError: 'Product' object has no attribute '_Product__total_price'. I am implementing where you apply the promo code then it will deduct the total price from the cart.
This is init.py and functions used.
#app.route('/applyPromo/<string:id>/', methods=['GET','POST'])
def apply_promo(id):
promotions_dict = {}
db = shelve.open('promotions.db','w')
promotions_dict = db['Promotions']
total_cost = 100
hidden = True
applied = True
click = True
get_from_class = False
print(promotions_dict)
promotions = promotions_dict.get(UUID(id))
db = shelve.open('storage.db', 'r')
product_dict = db['products']
for key in product_dict:
product = product_dict[key]
total_cost = product.get_total_price()
print(total_cost)
#when user apply promo, promo will get deleted from the list/dictionary of promos they have.
if promotions["type"] == 1:
total_cost = total_cost - 10
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 2:
total_cost = total_cost - 5
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 3:
total_cost = (70/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 4:
total_cost = (80/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 5:
total_cost = (85/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
else:
total_cost = (90/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
db['Promotions'] = promotions_dict
db.close()
db.close()
print(promotions_dict)
session['promotion_applied'] = promotions["id"]
return render_template("generatePromo.html", total_cost=total_cost,applied=applied, promotions_dict=promotions_dict,hidden=hidden,promotions=promotions,get_from_class=get_from_class, click=click)
#app.route('/shopping_cart')
def shopping_cart():
# session.clear()
error = None
cart_items = []
quantity_list = []
subtotal = 0
db = shelve.open('storage.db', 'r')
product_dict = db['products']
db.close()
for products in session:
item = product_dict.get(products)
cart_items.append(item)
if None in cart_items:
cart_items.remove(None)
quantity_list.append(session[products])
if products in quantity_list:
quantity_list.remove(products)
for i in range(len(cart_items)):
cart_items[i].set_purchased_quantity(quantity_list[i])
# set total price for single item
item_total = int(cart_items[i].get_price()) * int(cart_items[i].get_purchased_quantity())
cart_items[i].set_total_price(item_total)
# set total price of all items in cart
subtotal += item_total
print('QTY LIST', quantity_list)
print('CART', cart_items)
if not cart_items:
error = "Cart Is Empty"
return render_template('shoppingcart.html', products_list=cart_items, error=error, subtotal=subtotal)
This is the product class.
from uuid import uuid4
class Product:
def __init__(self, name, price, quantity, color, vase, remarks):
self.__product__id = str(uuid4())
self.__name = name
self.__price = price
self.__quantity = quantity
self.__color = color
self.__vase = vase
self.__remarks = remarks
self.__purchased_quantity = 0
self.__total_price = 0
def get_product_id(self):
return self.__product__id
def get_name(self):
return self.__name
def get_price(self):
return self.__price
def get_quantity(self):
return self.__quantity
def get_color(self):
return self.__color
def get_vase(self):
return self.__vase
def get_remarks(self):
return self.__remarks
def get_image(self):
return self.__image
def get_purchased_quantity(self):
return self.__purchased_quantity
def get_total_price(self):
return self.__total_price
def set_name(self, name):
self.__name = name
def set_price(self, price):
self.__price = price
def set_quantity(self, quantity):
self.__quantity = quantity
def set_color(self, color):
self.__color = color
def set_vase(self, vase):
self.__vase = vase
def set_remarks(self, remarks):
self.__remarks = remarks
def set_image(self, image):
self.__image = image
def set_purchased_quantity(self, purchased_quantity):
self.__purchased_quantity = purchased_quantity
def set_total_price(self, total_price):
self.__total_price = total_price
This is the traceback for the error.
Traceback
Leading double underscores should not be used as you are using them to define attributes of your class - single underscores is conventional. The problem with using leading double underscores is that the interpreter "mangles" the names of those attributes to avoid a subtle problem with inheritance, but leading to the problem, I believe, you are seeing. Here is a good read on the subject.

Product Inventory program that takes products with an ID, quantity, and price and uses an Inventory class to keep track of the products

The Product class seems to work fine but I'm trying to figure out how to get the Inventory class to separate each product into there specific categories. I feel like I'm close but whenever I try and print out the inventory it just shows where it's stored in memory and doesn't actually print anything out. The output i receive when running is at the bottom. I want it to print out the actual products and data, not the instance of it stored in memory.
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
OUTPUT = Inventory(products: [<main.Product instance at 0x10dbc8248>, <main.Product instance at 0x10dbc8290>], fishing_list: [<main.Product instance at 0x10dbc8248>], apparel_list: [], value: 0)
You need to specify how an object of the class Inventory should be printed.
To do this you need to implement at least one of the following functions in your class.
__repr__
__str__
This answer helps, which of both you should use: https://stackoverflow.com/a/2626364/8411228
An implementation could look something like this:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
Note that I used in the second example f strings, to format the output string.

Nosetests error in code where exception is manually raised

I wrote a simple program to practice but its test code keeps on failing. Here is the main code:
class Bank(object):
def __init__(self, name, deposit=0, withdraw=0, balance=0.0):
self.name = name
self.deposit = deposit
self.withdraw = withdraw
self.balance = balance
def deposited(self):
self.balance += self.deposit
return self.balance
def withdrawn(self):
if self.balance < self.withdraw:
raise ValueError("INSUFFICIENT BALANCE!")
else:
self.balance -= self.withdraw
return self.balance
This is its test code:
from nose.tools import *
from bank.account import Bank
def test_account():
Maria = Bank('Maria', None, None)
assert_equal(Maria.name, 'Maria')
` `assert_equal(Maria.balance, 0.0)
assert_equal(Maria.deposit, None)
assert_equal(Maria.withdraw, None)
Sam = Bank('Sam', 10, 1)
assert_equal(Sam.name, 'Sam')
assert_equal(Sam.balance, 0.0)
assert_equal(Sam.deposit, 10)
assert_equal(Sam.withdraw, 1)
def test_deposit():
Rotschild = Bank('Rotschild', 100, 0)
Rotschild.deposited()
assert_equal(Rotschild.balance, 100)
def test_withdaw():
Morgan = Bank('Morgan', 100, 50)
Morgan.deposited()
Morgan.withdrawn()
assert_equal(Morgan.balance, 50)
Bill = Bank('Bill', 5, 10)
Bill.deposited()
assert_raises(ValueError, Bill.withdrawn())
Upon running nosetests, it always shows Failed(error=1), i cannot figure out if it is a problem with the syntax or what.
I want the test to raise the exception when the account balance is less than the amount withdrawn.

Having issues with unit test in python

The code I wrote runs well without unit test. But fails when I unit test it.
Here is the source code
"""
shoppingcart.py
This program allows me to manage my shopping cart items
#autohor chuzksy
#version 2017-11-30
"""
class ShoppingCart(object):
"""This class manages shopping cart items in terms of
adding items, removing items and updating the cart list
"""
def __init__(self):
"""This is a constructor method belonging to the object of this ShoppingCart class"""
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
"""This method add items to the shopping cart dictionary"""
self.total = self.total + (quantity * price)
self.items.update({item_name: quantity})
def remove_item(self, item_name, quantity, price):
"""This method removes an item from the shopping cart and updates it"""
for name, qty in self.items.items():
if item_name == name:
if quantity < qty:
del self.items[item_name]
self.items.update({item_name: qty - quantity})
self.total -= (quantity * price)
else:
del self.items[item_name]
break
def checkout(self, cash_paid):
"""This method allows the user to pay for the items in the shopping cart"""
if cash_paid < self.total:
return "Cash paid not enough"
else:
return cash_paid - self.total
class Shop(ShoppingCart):
"""This is another class inheriting attributes and methods from the ShoppingCart class"""
def __init__(self):
super().__init__(self)
self.quantity = 100
def remove_item(self):
self.quantity -= 1
Here is the Unit test code:
import unittest
from shoppingcart import ShoppingCart
from shoppingcart import Shop
class ShoppingCartTestCases(unittest.TestCase):
def setUp(self):
self.cart = ShoppingCart()
self.shop = Shop()
def test_cart_property_initialization(self):
self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct')
self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary')
def test_add_item(self):
self.cart.add_item('Mango', 3, 10)
self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items')
self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item')
def test_remove_item(self):
self.cart.add_item('Mango', 3, 10)
self.cart.remove_item('Mango', 2, 10)
self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item')
self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item')
def test_checkout_returns_correct_balance(self):
self.cart.add_item('Mango', 3, 10)
self.cart.add_item('Orange', 16, 10)
self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct')
self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct')
def test_shop_is_instance_of_shopping_cart(self):
self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart')
def test_shop_remove_item_method(self):
for i in range(15):
self.shop.remove_item()
self.assertEqual(self.shop.quantity, 85)
if __name__ == '__main__':
unittest.main(exit = False)
print("test pass")
Here is the output I get after running the unit test program
Thank you so much in advance.
This should help solve the problem with your subclass:
class Shop(ShoppingCart):
def __init__(self):
self.quantity = 100
def remove_item(self):
self.quantity = self.quantity - 1
return self.quantity
The error is correct. The ShoppingCartTestCases has not atttribute called "shop" unless you call the setUp method first. Are you sure that's being done?

Python test andela

HST2: OBJECT ORIENTED PROGRAMMING LAB
Create a class called ShoppingCart.
Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.
Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.
Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly.
If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed.
Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough".
Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100.
Make sure Shop inherits from ShoppingCart.
In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.
# OOP Lab
class ShoppingCart(object):
def __init__(self):
total = 0
item = {}
self.total = total
self.item = item
def add_item(item_name, quantity, price):
cost = quantity * price
self.total += cost
self.item = {"item_name":quantity}
def remove_item(item_name,quantity,price):
cost = quantity * cost
self.total -= cost
for i in self.item:
if quantity > self.item[i]:
del self.item["item_name"]
def checkout(cash_paid):
if cash_paid < self.total:
return "Cash paid not enough"
class Shop(ShoppingCart):
def __init__(self):
quantity = 100
self.quantity = quantity
def remove_item():
self.quantity -= 1
#! Error State the following:
my add_item is having four argument instead of three each time i run this code:
Please i need help with this code, am new with python, i will appreciate any programming angel in python to rescue me now.
Try this, it should work out just fine:
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.total += quantity * price
if type(item_name) == str and quantity > 0:
self.items.update({item_name: quantity})
def remove_item(self, item_name, quantity, price):
if quantity >= self.items[item_name] and quantity >= 1:
items_cost = price * self.items[item_name]
self.total -= items_cost
del self.items[item_name]
else:
self.total -= quantity * price
self.items[item_name] -= quantity
def checkout(self, cash_paid):
balance = 0
if cash_paid < self.total:
return "Cash paid not enough"
balance = cash_paid - self.total
return balance
class Shop(ShoppingCart):
def __init__(self):
self.quantity = 100
def remove_item(self):
self.quantity -= 1
Class methods should accept self as the first argument so for example
def add_item(self, item_name, quantity, price):
Instead of
def add_item(item_name, quantity, price):
The "4th argument" being passed is implicitly self, that is why the number of arguments is one higher than you are expecting.

Categories

Resources