Skip to content

Instantly share code, notes, and snippets.

@brydavis
Last active August 3, 2019 08:30
Show Gist options
  • Save brydavis/8e37703225755d576025798ed4ef196d to your computer and use it in GitHub Desktop.
Save brydavis/8e37703225755d576025798ed4ef196d to your computer and use it in GitHub Desktop.
import peewee
database = peewee.SqliteDatabase('customers.db')
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
database.execute_sql('drop table if exists customer;')
class BaseModel(peewee.Model):
class Meta:
database = database
class Customer(BaseModel):
"""
This class defines Customer, which maintains details of someone
for whom we want to research consumer habits to date.
Customer ID
Name
Lastname
Home address
Phone number
Email address
Status (active or inactive customer)
Credit limit
"""
customer_id = peewee.CharField(primary_key = True, max_length=30)
name = peewee.CharField(max_length=50)
lastname = peewee.CharField(max_length=50, null=True)
homeaddress = peewee.CharField(max_length=75)
phone_number = peewee.CharField(max_length=15)
email = peewee.CharField(max_length=320) # based on max email address length search
status = peewee.CharField(max_length=10) # "inactive" or "active"
credit_limit = peewee.FloatField()
Customer.create_table()
def add_customer(customer_id, name, lastname, home_address, phone_number, email_address, status, credit_limit):
"""This function will add a new customer to the sqlite3 database."""
try:
with database.transaction():
customer = Customer.create(
customer_id = customer_id,
name = name,
lastname = lastname,
homeaddress = home_address,
phone_number = phone_number,
email = email_address,
status = status,
credit_limit = credit_limit,
)
customer.save()
print('Database add successful')
except Exception as e:
print(f'jError creating = {customer_id}')
print(e)
print('See how the database protects our data')
def search_customer(customer_id):
"""This function will return a dictionary object with name, lastname, email address and phone number of a customer or an empty dictionary object if no customer was found."""
try:
customer = Customer.get(Customer.customer_id == customer_id)
return {
"name": customer.name,
"lastname": customer.lastname,
"email": customer.email,
"phone_number": customer.phone_number,
}
except Exception as e:
print(f"Error retrieving customer {customer_id}")
print(e)
return {}
def delete_customer(customer_id):
"""This function will delete a customer from the sqlite3 database."""
try:
with database.transaction():
customer = Customer.get(Customer.customer_id == customer_id)
customer.delete_instance()
customer.save()
return True
except Exception as e:
print("transaction failed while deleting customer")
print(e)
return False
def update_customer_credit(customer_id, credit_limit):
"""This function will search an existing customer by customer_id and update their credit limit or raise a ValueError exception if the customer does not exist."""
try:
with database.transaction():
customer = Customer.get(Customer.customer_id == customer_id)
customer.credit_limit = credit_limit
customer.save()
except Exception as e:
raise ValueError("NoCustomer") # required to pass test
print("transaction failed while updating customer ({customer_id}) credit limit")
print(e)
def list_active_customers():
"""This function will return an integer with the number of customers whose status is currently active."""
try:
active_customers = Customer.select().where(Customer.status == "active")# .count()
for customer in active_customers:
print(f"{customer.name} {customer.lastname}'s status is {customer.status}")
return len(active_customers)
except Exception as e:
print("Retrieval of active customers failed")
print(e)
# if __name__ == "__main__":
# data = []
# (add_customer(c) for c in data)
"""
Autograde Lesson 3 assignment
Run pytest
Run cobverage and linitng using standard batch file
Student should submit an empty database
"""
import pytest
# import basic_ops as l
import basic_operations as l
@pytest.fixture
def _add_customers():
return [
("1","Tybalt","Heinsh","8 Lien Trail","876935123","[email protected]","active","2420"),
("2","Gwennie","Tennock","4608 Steensland Lane","134552899","[email protected]","active","2343"),
("3","Euell","Fidgeon","8 Lerdahl Park","009363240","[email protected]","inactive","1077"),
("4","Cairistiona","Ginnell","3 Harbort Drive","880717312","[email protected]","active","1484"),
("5","Mariel","Wolfarth","47 Loomis Hill","069169873","[email protected]","inactive","113"),
("6","Mallorie","Sammut","3614 Fisk Avenue","828591715","[email protected]","active","3255"),
("7","Seamus","Pittford","2136 Rigney Park","807689452","[email protected]","active","3468"),
("8","Piotr","Gauson","4145 Kensington Park","133398937","[email protected]","inactive","3625"),
("9","Teodora","Loxton","40829 Bartillon Crossing","194346240","[email protected]","inactive","444"),
("10","Nanine","Eadmeades","8691 Calypso Circle","367839372","[email protected]","inactive","2459"),
("11","Marieann","Calcutt","5678 Rutledge Point","245977057","[email protected]","inactive","2962"),
("12","Wandis","Dewdney","095 Packers Park","135126295","[email protected]","active","4742"),
("13","Tommy","Wannes","59889 Myrtle Avenue","969027317","[email protected]","inactive","4067"),
("14","Letti","Barkworth","7 Sundown Place","243310785","[email protected]","inactive","1697"),
("15","Danit","Fayerman","9107 Oakridge Point","596550663","[email protected]","active","2382"),
("16","Susanna","Grigaut","87 Cascade Avenue","839048392","[email protected]","inactive","3982"),
("17","Donal","Thraves","2048 Porter Place","303563873","[email protected]","inactive","3597"),
("18","Erina","Whightman","0 Columbus Park","380312722","[email protected]","active","2007"),
("19","Rogers","Dumbare","2 Shopko Hill","510504125","[email protected]","active","371"),
("20","Kayla","Coyte","4134 Atwood Pass","468104655","[email protected]","active","4400"),
]
@pytest.fixture
def _search_customers(): # needs to del with database
return [
[
("15","Danit","Fayerman","9107 Oakridge Point","596550663","[email protected]","active","2382"),
("16","Susanna","Grigaut","87 Cascade Avenue","839048392","[email protected]","inactive","3982"),
("17","Donal","Thraves","2048 Porter Place","303563873","[email protected]","inactive","3597"),
("18","Erina","Whightman","0 Columbus Park","380312722","[email protected]","active","2007"),
("19","Rogers","Dumbare","2 Shopko Hill","510504125","[email protected]","active","371"),
],
("16", "000")
]
@pytest.fixture
def _delete_customers(): # needs to del with database
return [
("3","Euell","Fidgeon","8 Lerdahl Park","009363240","[email protected]","inactive","1077"),
("4","Cairistiona","Ginnell","3 Harbort Drive","880717312","[email protected]","active","1484"),
("5","Mariel","Wolfarth","47 Loomis Hill","069169873","[email protected]","inactive","113"),
]
@pytest.fixture
def _update_customer_credit(): # needs to del with database
return [
("8","Piotr","Gauson","4145 Kensington Park","133398937","[email protected]","inactive","3625"),
("9","Teodora","Loxton","40829 Bartillon Crossing","194346240","[email protected]","inactive","444"),
("10","Nanine","Eadmeades","8691 Calypso Circle","367839372","[email protected]","inactive","2459"),
]
@pytest.fixture
def _list_active_customers():
return [
("1","Tybalt","Heinsh","8 Lien Trail","876935123","[email protected]","active","2420"),
("2","Gwennie","Tennock","4608 Steensland Lane","134552899","[email protected]","active","2343"),
("4","Cairistiona","Ginnell","3 Harbort Drive","880717312","[email protected]","active","1484"),
("6","Mallorie","Sammut","3614 Fisk Avenue","828591715","[email protected]","active","3255"),
("7","Seamus","Pittford","2136 Rigney Park","807689452","[email protected]","active","3468"),
("12","Wandis","Dewdney","095 Packers Park","135126295","[email protected]","active","4742"),
("15","Danit","Fayerman","9107 Oakridge Point","596550663","[email protected]","active","2382"),
]
def test_list_active_customers(_list_active_customers):
""" actives """
for customer in _list_active_customers:
l.add_customer(
customer[0],
customer[1],
customer[2],
customer[3],
customer[4],
customer[5],
customer[6],
customer[7],
)
actives = l.list_active_customers()
assert actives == 7
def test_add_customer(_add_customers):
""" additions """
print("type(_add_customers) == ", type(_add_customers))
for customer in _add_customers:
l.add_customer(
customer[0],
customer[1],
customer[2],
customer[3],
customer[4],
customer[5],
customer[6],
customer[7],
)
added = l.search_customer(customer[0])
assert added["name"] == customer[1]
assert added["lastname"] == customer[2]
assert added["email"] == customer[5]
assert added["phone_number"] == customer[4]
for customer in _add_customers:
l.delete_customer(customer[0])
def test_search_customer(_search_customers):
""" search """
for customer in _search_customers[0]:
l.add_customer(
customer[0],
customer[1],
customer[2],
customer[3],
customer[4],
customer[5],
customer[6],
customer[7]
)
result = l.search_customer(_search_customers[1][1])
assert result == {}
result = l.search_customer(_search_customers[1][0])
assert result["name"] == _search_customers[0][1][1]
assert result["lastname"] == _search_customers[0][1][2]
assert result["email"] == _search_customers[0][1][5]
assert result["phone_number"] == _search_customers[0][1][4]
for customer in _search_customers[0]:
l.delete_customer(customer[0])
def test_delete_customer(_delete_customers):
""" delete """
for customer in _delete_customers:
l.add_customer(customer[0],
customer[1],
customer[2],
customer[3],
customer[4],
customer[5],
customer[6],
customer[7]
)
response = l.delete_customer(customer[0])
assert response is True
deleted = l.search_customer(customer[0])
assert deleted == {}
def test_update_customer_credit(_update_customer_credit):
""" update """
for customer in _update_customer_credit:
l.add_customer(
customer[0],
customer[1],
customer[2],
customer[3],
customer[4],
customer[5],
customer[6],
customer[7]
)
l.update_customer_credit("8", 0)
l.update_customer_credit("9", 1000)
l.update_customer_credit("10", -42)
with pytest.raises(ValueError) as excinfo:
l.update_customer_credit("00100", 1000) # error
assert 'NoCustomer' in str(excinfo.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment