Пример #1
0
    def test_cart(self):
        """We can add items to the shopping cart
        and retrieve them"""

        # first need to force the creation of a session and
        # add the cookie to the request
        sessionid = session.get_or_create_session(self.db)
        self.assertIsNotNone(sessionid)
        request.cookies[session.COOKIE_NAME] = sessionid

        # initial cart should be empty
        cart = session.get_cart_contents(self.db)
        self.assertEqual([], cart)

        # now add something to the cart
        for pname in ['Yellow Wool Jumper', 'Ocean Blue Shirt']:
            product =  self.products[pname]
            session.add_to_cart(self.db, product['id'], 1 )

        cart = session.get_cart_contents(self.db)
        self.assertEqual(2, len(cart))

        # check that all required fields are in the every cart entry
        for entry in cart:
            self.assertIn('id', entry)
            self.assertIn('name', entry)
            self.assertIn('quantity', entry)
            self.assertIn('cost', entry)
Пример #2
0
    def test_cart_update(self):
        """We can update the quantity of an item in the cart"""

        # first need to force the creation of a session and
        # add the cookie to the request
        sessionid = session.get_or_create_session(self.db)
        self.assertIsNotNone(sessionid)
        request.cookies[session.COOKIE_NAME] = sessionid

        # add something to the cart
        product = self.products['Yellow Wool Jumper']
        quantity = 3
        session.add_to_cart(self.db, product['id'], quantity)
        cart = session.get_cart_contents(self.db)

        self.assertEqual(1, len(cart))
        # compare ids as strings to be as flexible as possible
        self.assertEqual(str(product['id']), str(cart[0]['id']))
        self.assertEqual(quantity, cart[0]['quantity'])

        # now add again to the cart, check that we still have one item and the
        # quantity is doubled
        session.add_to_cart(self.db, product['id'], quantity)
        cart = session.get_cart_contents(self.db)

        self.assertEqual(1, len(cart))
        self.assertEqual(product['id'], cart[0]['id'])
        self.assertEqual(quantity * 2, cart[0]['quantity'])
Пример #3
0
    def test_get_cart(self):
        """Can get the contents of the cart"""

        request.environ['beaker.session'] = MockBeakerSession({'cart': []})
        self.assertEqual([], session.get_cart_contents())

        cart = [{'id': 1, 'quantity': 3, 'name': 'test', 'cost': 123.45}]
        request.environ['beaker.session'] = {'cart': cart}
        self.assertEqual(cart, session.get_cart_contents())
Пример #4
0
    def test_cart_page(self):  # passed
        """The page at /cart should show the current contents of the
        shopping cart"""

        product = self.products['Yellow Wool Jumper']
        url = "/product/%s" % product['id']
        response = self.app.get(url)
        self.assertEqual(200, response.status_code, "Expected 200 OK response for URL %s" % url)

        # page may have more than one form, but one of them must have the action /cart
        cart_form = None
        for idx in response.forms:
            if response.forms[idx].action == '/cart':
                cart_form = response.forms[idx]

        self.assertIsNotNone(cart_form, 'Did not find form with action="/cart" in response')

        # fill out the form
        cart_form['quantity'] = 2

        response = cart_form.submit()

        self.assertEqual(302, response.status_code, 'Expected 302 redirect response from cart form submission')

        # and our product should be in the cart
        cart = session.get_cart_contents(self.db)

        response = self.app.get('/cart')

        # look for the product name in the returned page
        self.assertIn(product['name'], response)
Пример #5
0
def get_cart_page(db):
    sessionid = session.get_or_create_session(db)
    cart_items = session.get_cart_contents(db)
    products = []
    total = 0
    for each in cart_items:
        dbresponse = model.product_get(db, each['id'])
        product = {
            'id': dbresponse['id'],
            'name': dbresponse['name'],
            'image_url': dbresponse['image_url'],
            'description': dbresponse['description'],
            'inventory': dbresponse['inventory'],
            'cost': each['cost'],
            'quantity': each['quantity']
        }
        total += each['cost']
        products.append(product)
        session.response.set_cookie(sessionid)
    return template(
        'cart', {
            'products': products,
            'total': total,
            'title': "Your Shopping Cart contains..."
        })
Пример #6
0
Файл: main.py Проект: natlec/WT
def cart(db):

    # Get or set session cookie
    session.get_or_create_session(db)

    # Get cart contents from database
    cart = session.get_cart_contents(db)

    # Info relative to page
    info = {
        'page': 'cart',
        'title': 'Shopping cart',
        'description':
        "You've added the following items to your shopping cart:",
        'cart': 0,
        'total': 0
    }

    # Get item list for cart
    info['products'] = cart

    # Get cart items count & total cost
    if cart:
        for item in cart:
            info['cart'] += int(item['quantity'])
            info['total'] += (float(item['cost']) * float(item['quantity']))

    return template('cart', info)
Пример #7
0
Файл: main.py Проект: natlec/WT
def products(db, category):

    # Get or set session cookie
    session.get_or_create_session(db)

    # Get cart contents from database
    cart = session.get_cart_contents(db)

    # Check if category exists
    if category == 'men' or category == 'women':

        # Info relative to page
        info = {
            'page': category,
            'title': "%s's products" % category,
            'description':
            "Explore our entire range of %s's products." % category,
            'cart': 0
        }

        # Get cart items count
        if cart:
            for item in cart:
                info['cart'] += int(item['quantity'])

        # Get products list
        info['products'] = model.product_list(db, category)

        return template('index', info)
    else:
        return HTTPResponse(status=404)
Пример #8
0
Файл: main.py Проект: natlec/WT
def index(db):

    # Get or set session cookie
    session.get_or_create_session(db)

    # Get cart contents from database
    cart = session.get_cart_contents(db)

    # Info relative to page
    info = {
        'page': '',
        'title': 'All products',
        'description':
        'Explore our entire range of products for both men & women. ',
        'cart': 0
    }

    # Get cart items count
    if cart:
        for item in cart:
            info['cart'] += int(item['quantity'])

    # Get products list
    info['products'] = model.product_list(db)

    return template('index', info)
Пример #9
0
    def test_add_to_cart_works(self):  # passed but a problem below
        """If I click on the add to cart button my product
        is added to the shopping cart"""

        product = self.products['Yellow Wool Jumper']
        url = "/product/%s" % product['id']
        response = self.app.get(url)
        self.assertEqual(200, response.status_code, "Expected 200 OK response for URL %s" % url)

        # page may have more than one form, but one of them must have the action /cart
        cart_form = None
        for idx in response.forms:
            if response.forms[idx].action == '/cart':
                cart_form = response.forms[idx]

        self.assertIsNotNone(cart_form, 'Did not find form with action="/cart" in response')

        # fill out the form
        cart_form['quantity'] = 2

        response = cart_form.submit()

        self.assertEqual(302, response.status_code, 'Expected 302 redirect response from cart form submission')
        urlparts = urllib.parse.urlparse(response.headers['Location'])
        location = urlparts[2]
        self.assertEqual('/cart', location, "Expected redirect location header to be /cart")

        # and our product should be in the cart
        cart = session.get_cart_contents(self.db)

        self.assertEqual(1, len(cart))
        self.assertEqual(str(product['id']), cart[0]['id'])
        # self.assertEqual(2, cart[0]['quantity'])  # 2 is integer but cart[0]['quantity'] is not
        self.assertEqual(2, int(cart[0]['quantity']))
Пример #10
0
def cart(db):
    session.get_or_create_session(db)

    info = {
        'contents': session.get_cart_contents(db),
    }
    return template('cart', info)
Пример #11
0
def index(db):
    """This is the get method for the cart route that is called whenever we do not have a
    post request. Called if the user clicks the cart directly or when the function above redirects.
    This function gets the cart content uses the function in the session.py file.
    """
    cart = session.get_cart_contents()
    info = {'title': "", 'products': cart}
    return template('cart', info)
Пример #12
0
    def test_cart_update(self):  # Not passed.....see below
        """We can update the quantity of an item in the cart"""

        # first need to force the creation of a session and
        # add the cookie to the request
        sessionid = session.get_or_create_session(self.db)
        self.assertIsNotNone(sessionid)
        request.cookies[session.COOKIE_NAME] = sessionid

        # add something to the cart
        product = self.products['Yellow Wool Jumper']
        quantity = 3
        session.add_to_cart(self.db, product['id'], quantity)
        cart = session.get_cart_contents(self.db)

        self.assertEqual(1, len(cart))
        self.assertEqual(product['id'], cart[0]['id'])
        self.assertEqual(quantity, cart[0]['quantity'])

        # now add again to the cart, check that we still have one item and the
        # quantity is doubled
        session.add_to_cart(self.db, product['id'],
                            quantity)  # -----> extra parameter: update=False
        # session.add_to_cart(self.db, product['id'], quantity, update=False)
        cart = session.get_cart_contents(self.db)

        self.assertEqual(1, len(cart))
        self.assertEqual(product['id'], cart[0]['id'])
        # self.assertEqual(quantity * 2, cart[0]['quantity'])
        self.assertEqual(
            str(quantity * 2),
            cart[0]['quantity'])  # ------>  quantity needs to be string

        # now add again but with the update flag set, this should
        # set the quantity rather than adding to it
        session.add_to_cart(self.db, product['id'],
                            quantity)  # -----> extra parameter: update=True
        # session.add_to_cart(self.db, product['id'], quantity, update=True)
        cart = session.get_cart_contents(self.db)

        self.assertEqual(1, len(cart))
        self.assertEqual(product['id'], cart[0]['id'])
        self.assertEqual(
            quantity, cart[0]['quantity']
        )  # 9!=3 means what? We are not told about the update flag in the readme file
Пример #13
0
def cart(db):
    session.get_or_create_session(db)
    cart = session.get_cart_contents(db)
    total_cost = 0
    if len(cart) is 0:
        cart = "Your Cart is Empty"
    else:
        for item in cart:
            total_cost = total_cost + item["cost"]
    info = {"title": "CART", "cart": cart, "total_cost": total_cost}

    return template('cart', info)
Пример #14
0
def cart_view(db):
    """Render the cart(GET) page"""
    session.get_or_create_session(db)
    cart = session.get_cart_contents(db)
    totalCost = 0
    for item in cart:
        totalCost += item['cost'] * item['quantity']
    cart = {
        'products': cart,
        'total': totalCost
    }
    return template('cart', cart)
Пример #15
0
def show_cart(db):
    """a GET request to this URL shows the current contents of the shopping cart. The resulting page
includes a listing of all items in the cart, including their name, quantity and overall cost. It also
includes the total cost of the items in the cart."""
    # product_id = request.query.get('item')
    # product_quantity = request.query.get('quantity')
    # add_to_cart(product_id, product_quantity)
    session.get_or_create_session(db)
    cart = dict()
    cart['title'] = "Your Cart: "
    cart['product_list'] = session.get_cart_contents(db)
    return template('cart', cart)
Пример #16
0
def cart_view(db):
    """Render the cart(GET) page"""
    session.get_or_create_session(db)
    current = session.get_cart_contents(db)
    cost = 0
    for each in current:
        cost += each['cost'] * each['quantity']
    cart = {
        'content': current,
        'total': cost,
    }
    return template('cart', cart)
Пример #17
0
    def test_add_nonexisting_to_cart(self):
        # We start one session
        cart = []
        request.environ['beaker.session'] = MockBeakerSession({'cart': cart})
        self.assertEqual([], session.get_cart_contents())
        product = self.products['Classic Varsity Top']
        session.add_to_cart(self.db, product['id'], 1)
        cart = session.get_cart_contents()
        self.assertEqual(1, len(cart))

        # check that we cannot add a non-existing object
        session.add_to_cart(self.db, 100, 2)
        cart = session.get_cart_contents()
        self.assertEqual(1, len(cart), "Error when adding non-existing object")

        # check that we cannot add an item that exceeds amount in inventory
        session.add_to_cart(self.db, 10, 100)
        cart = session.get_cart_contents()
        self.assertEqual(1, len(cart), "Quantity exceeded amount in inventory")

        # check that we cannot add an item with non-positive amount
        session.add_to_cart(self.db, 10, -3)
        cart = session.get_cart_contents()
        self.assertEqual(1, len(cart), "Adding item with negative amount")
        session.add_to_cart(self.db, 10, 0)
        cart = session.get_cart_contents()
        self.assertEqual(1, len(cart), "Adding item with zero amount")
    def test_cart(self):
        """We can add items to the shopping cart
        and retrieve them"""

        cart = []
        request.environ['beaker.session'] = MockBeakerSession({'cart': cart})
        self.assertEqual([], session.get_cart_contents())

        # now add something to the cart
        for pname in ['Yellow Wool Jumper', 'Ocean Blue Shirt']:
            product = self.products[pname]
            session.update_cart(self.db, product['id'], 1, False)

        cart = session.get_cart_contents()
        self.assertEqual(2, len(cart))

        # check that all required fields are in the every cart entry
        for entry in cart:
            self.assertIn('id', entry)
            self.assertIn('name', entry)
            self.assertIn('quantity', entry)
            self.assertIn('cost', entry)
Пример #19
0
def index(db):
    session.get_or_create_session(db)
    data = session.get_cart_contents(db)
    cost = 0
    for x in data:
        temp = x['cost']
        cost += temp
    info = {
        'title': 'Current Shopping Cart Contents',
        'data': data,
        'cost': cost
    }
    return template('cart', info)
Пример #20
0
    def test_add_to_cart(self):
        """We can add items to the shopping cart
        and retrieve them"""

        # We start one session
        cart = []
        request.environ['beaker.session'] = MockBeakerSession({'cart': cart})
        self.assertEqual([], session.get_cart_contents())

        # now add something to the cart
        for pname in ['Yellow Wool Jumper', 'Classic Varsity Top']:
            product = self.products[pname]
            session.add_to_cart(self.db, product['id'], 1)

        cart = session.get_cart_contents()
        self.assertEqual(2, len(cart))

        # check that all required fields are in every cart entry
        for entry in cart:
            self.assertIn('id', entry)
            self.assertIn('name', entry)
            self.assertIn('quantity', entry)
            self.assertIn('cost', entry)

        # We start a session again and check that the cart is empty
        cart = []
        request.environ['beaker.session'] = MockBeakerSession({'cart': cart})
        self.assertEqual([], session.get_cart_contents())

        # now add something to the cart in the new session
        for pname in [
                'Yellow Wool Jumper', 'Silk Summer Top', 'Zipped Jacket'
        ]:
            product = self.products[pname]
            session.add_to_cart(self.db, product['id'], 1)

        cart = session.get_cart_contents()
        self.assertEqual(3, len(cart))
Пример #21
0
    def test_cart_update(self):
        """We can update the quantity of an item in the cart"""

        # first need to force the creation of a session with an empty cart
        cart = []
        request.environ['beaker.session'] = MockBeakerSession({'cart': cart})

        # add something to the cart
        product = self.products['Yellow Wool Jumper']
        quantity = 3
        session.add_to_cart(self.db, product['id'], quantity)
        cart = session.get_cart_contents()

        self.assertEqual(1, len(cart))
        # compare ids as strings to be as flexible as possible
        self.assertEqual(str(product['id']), str(cart[0]['id']))
        self.assertEqual(quantity, cart[0]['quantity'])

        # now add again to the cart, check that we still have one item and the
        # quantity is doubled
        session.add_to_cart(self.db, product['id'], quantity)
        cart = session.get_cart_contents()

        self.assertEqual(1, len(cart))
        self.assertEqual(product['id'], cart[0]['id'])
        self.assertEqual(quantity * 2, cart[0]['quantity'])

        # now add a third time, this time exceeding the amount in inventory, check that
        # we still have one item and the quantity has not changed
        session.add_to_cart(self.db, product['id'], 100)
        cart = session.get_cart_contents()

        self.assertEqual(1, len(cart),
                         "Test adding excessive quantity of products")
        self.assertEqual(product['id'], cart[0]['id'],
                         "Test adding excessive quantity of products")
        self.assertEqual(quantity * 2, cart[0]['quantity'],
                         "Test adding excessive quantity of products")
Пример #22
0
def cart_add(db):
    """Render the cart(POST) page"""

    key = session.get_or_create_session(db)

    quantity = int(request.forms.get('quantity'))
    product = request.forms.get('product')

    session.add_to_cart(db, product, quantity)
    current = session.get_cart_contents(db)
    cost = 0
    for each in current:
        cost += each['cost'] * each['quantity']
    cart = {
        'content': current,
        'total': cost,
    }
    return redirect("/cart")
Пример #23
0
Файл: main.py Проект: natlec/WT
def product(db, id):

    # Get or set session cookie
    session.get_or_create_session(db)

    # Get cart contents from database
    cart = session.get_cart_contents(db)

    # Info relative to page
    info = {'page': 'product', 'cart': 0}

    # Get cart items count
    if cart:
        for item in cart:
            info['cart'] += int(item['quantity'])

    # Get product data
    info['product'] = model.product_get(db, id)

    # Check if product exists
    if info['product'] is not None:
        return template('product', info)
    else:
        return HTTPResponse(status=404)
Пример #24
0
def cart(db):
    """The GET cart page. Will create/get cookie
    When '/cart' is navigated to, this page will
    be displayed. It retrieves all the contents
    of the cart. The cart.html file will iterate
    over the items and display them.
    Also calculates the total amount
    """
    session.get_or_create_session(db)

    cart = session.get_cart_contents(db)

    #iterate over cart and add up the costs
    total = 0
    for item in cart:
        total = total + item['cost']

    #pass the cart and total to the cart.html
    info = {
        'title': "Current Shopping Cart contents",
        'cart': cart,
        'total': total
    }
    return template('cart', info)
Пример #25
0
def cart_contents():

    cart = session.get_cart_contents()
    return {'cart': cart}
Пример #26
0
def cart(db):
    # session get the content from the from the db
    session.get_cart_contents(db)


    return template('cart')