This repository has been archived by the owner on Aug 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cart_example1.py
78 lines (60 loc) · 1.72 KB
/
cart_example1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Inventory Code
import hypothesis.strategies as st
class Book(object):
def __init__(self, title, author, price):
self.title = title
self.author = author
if not price >= 0.00:
price = 0.00
self.price = price
def __unicode__(self):
return u"%s by %s ($%s)" % (self.title, self.author, self.price)
def __repr__(self):
return self.__unicode__().encode("utf-8")
books = st.builds(
Book,
title=st.text(),
author=st.text(),
price=st.floats(),
)
# Shopping Cart Code
class ShoppingCart(object):
def __init__(self):
self.cart = {}
self.total = 0.00
def add(self, item):
if item in self.cart:
self.cart[item] += 1
else:
self.cart[item] = 1
self.total += item.price
def remove(self, item):
if item in self.cart:
self.cart[item] -= 1
if self.cart[item] == 0:
del self.cart[item]
self.total -= item.price
# Property-based Test(s)
from hypothesis import given
import hypothesis.strategies as st
@given(st.lists(books))
def test_add(list_of_books):
cart = ShoppingCart()
for book in list_of_books:
cart.add(book)
assert cart.total == sum(book.price for book in list_of_books)
@given(st.lists(books))
def test_remove(list_of_books):
cart = ShoppingCart()
for book in list_of_books:
cart.remove(book)
assert cart.total == 0.00
@given(st.lists(books))
def test_add_remove(list_of_books):
cart = ShoppingCart()
for book in list_of_books:
cart.add(book)
cart.remove(book)
assert cart.total == 0.00