示例#1
0
 def setUpClass(cls):
     """
     Setup the test case
     """
     # print('setup method is called')
     DATABASE.drop_tables([Customer])
     DATABASE.create_tables([Customer])
示例#2
0
    def setUp(self):
        """ Ensure we start with a clean table """

        # Configure logging for test activity
        bo.configure_logger()

        logging.info("Dropping Customer table")
        DATABASE.drop_tables([Customer])
        logging.info("Creating Customer table")
        DATABASE.create_tables([Customer])
def update_customer_credit(customer_id, credit_limit):
    """Updates a customer's credit limit in the database."""
    init_database()
    try:
        customer = Customer.get_by_id(customer_id)
        customer.credit_limit = credit_limit
        customer.save()
        return True
    except peewee.DoesNotExist:
        logging.error("Customer ID %s doesn't exist in database.", customer_id)
        raise ValueError('Customer ID does not exist in database.')
    finally:
        database.close()
示例#4
0
    def test_basic_operations(self):
        """" Integration test for the basic operations """

        DATABASE.drop_tables([Customer])
        DATABASE.close()
        DATABASE.create_tables([Customer])
        DATABASE.close()

        # Add customers to the db
        add_customers(self.test_customer)

        cust_found = search_customer(2)
        self.assertEqual(self.test_customer[1][5], cust_found.get("email"))

        update_customer_credit(1, 500.00)
        self.assertEqual(500.00, Customer.get_by_id(1).credit_limit)

        # Find out how many customers are active
        active_cust = list_active_customers()
        self.assertEqual(2, active_cust)

        # Delete a customer then try to find it
        delete_customer(2)
        self.assertDictEqual({}, search_customer(2))

        # Find out how many customers are active and list their names
        self.assertEqual(1, list_active_customers())
        self.assertEqual(["Reed Richards"], list_active_customer_names())
示例#5
0
def add_customer(customer_id, name, last_name, home_address, phone_number,
                 email, status, credit_limit):
    """
    This function will add a new customer to the sqlite3 database.
    :param customer_id: integer representing a unique value that identifies a customer
    :param name: string containing the customer's first name
    :param last_name: string containing the customer's last name
    :param home_address: string containing the customer's address
    :param phone_number: string containing the customer's phone number
    :param email: string containing the customer's email address
    :param status: boolean representing the customer's status
    :param credit_limit: float containing the customer's credit limit
    """
    try:
        with DATABASE.transaction():
            new_customer = Customer.create(customer_id=customer_id,
                                           name=name,
                                           last_name=last_name,
                                           home_address=home_address,
                                           phone_number=phone_number,
                                           email=email,
                                           status=status,
                                           credit_limit=credit_limit)
            new_customer.save()
            LOGGER.info("A new customer record, %s %s, was added", name,
                        last_name)
    except IntegrityError as integrity_error:
        LOGGER.error("A IntegrityError occurred %s", integrity_error)
示例#6
0
def add_customer(customer_id, first_name, last_name, home_address,
                 phone_number, email_address, is_active, credit_limit):
    """
    add new customer to customer database
    :param customer_id:customer id
    :param first_name: customer first name
    :param last_name: customer last name
    :param home_address: customer address
    :param phone_number: customer cell phone number
    :param email_address: customer email address
    :param is_active: whether the customer is active
    :param credit_limit: customer credit limit
    :return: add a new customer to table
    """
    try:
        LOGGER.info('Successfully connected to the database')

        with DATABASE.transaction():
            new_customer = Customer.create(customer_id=customer_id,
                                           first_name=first_name,
                                           last_name=last_name,
                                           home_address=home_address,
                                           phone_number=phone_number,
                                           email_address=email_address,
                                           is_active=is_active,
                                           credit_limit=credit_limit)
            new_customer.save()
            LOGGER.info("Customer added successfully")

    except IntegrityError as error:
        LOGGER.info(error)
        LOGGER.info('Error occurred')
def delete_customer(customer_id):
    """Deletes a customer from the database."""
    init_database()
    try:
        with database.transaction():
            customer = Customer.get_by_id(customer_id)
            customer.delete_instance()
            logging.info('Customer with ID %s successfully deleted.',
                         customer_id)
            return True
    except peewee.DoesNotExist:
        logging.error('Customer delete with ID %s failed, not in database..',
                      customer_id)
        return False
    finally:
        database.close()
示例#8
0
def set_up_db():
    """
    Set up routine needed for all tests to make sure the db is in a
    known/empty state
    """
    DATABASE.drop_tables([Customer])
    DATABASE.close()
    DATABASE.create_tables([Customer])
    DATABASE.close()
def search_customer(customer_id):
    """Searches for a customer in the database, returning a dictionary of contact info if found."""
    init_database()
    try:
        customer = Customer.get_by_id(customer_id)
        customer_dict = {
            'name': customer.name,
            'lastname': customer.lastname,
            'email_address': customer.email_address,
            'phone_number': customer.phone_number
        }
        return customer_dict
    except peewee.DoesNotExist:
        logging.warning("Customer ID %s doesn't exist in database.",
                        customer_id)
        return {}
    finally:
        database.close()
示例#10
0
def print_customer_data(customers):
    """Prints all customer data, including header, to screen from query ModelObject customers."""
    if not customers:
        print('No records matching criteria found.')
    else:
        print(' | '.join(('{:^20}'.format(column.name))
                         for column in database.get_columns('Customer')))
        for customer in customers.tuples():
            print(' | '.join('{:^20}'.format(str(x)) for x in customer))
def update_customer_credit(customer_id, credit_limit):
    """ Update the credit limit for a customer via customer_id """

    try:
        customer_to_update = Customer.get(Customer.customer_id == customer_id)
        with DATABASE.transaction():
            logging.debug(
                f"Updating customer with customer_id:  {customer_id}")
            customer_to_update.credit_limit = credit_limit
            customer_to_update.save()
    except DoesNotExist:
        logging.error(f"Unable to find customer with id:  {customer_id}")
        raise DoesNotExist
def delete_customer(customer_id):
    """ Delete a customer from the databsse via customer_id """

    try:
        customer_to_delete = Customer.get(Customer.customer_id == customer_id)
        with DATABASE.transaction():
            logging.debug(
                f"Deleting customer with customer_id:  {customer_id}")
            customer_to_delete.delete_instance()
            customer_to_delete.save()
            logging.debug("Successfully deleted customer")
    except DoesNotExist:
        logging.error(f"Unable to find customer with id:  {customer_id}")
        raise DoesNotExist
def add_customer(customer_id, name, lastname, home_address, phone_number,
                 email_address, status, credit_limit):
    """Adds a new customer to the database."""
    init_database()
    try:
        with database.transaction():
            new_customer = Customer.create(customer_id=customer_id,
                                           name=name,
                                           lastname=lastname,
                                           home_address=home_address,
                                           phone_number=phone_number,
                                           email_address=email_address,
                                           active_status=status,
                                           credit_limit=credit_limit)
            new_customer.save()
            logging.info('New customer, ID %s, added successfully.',
                         customer_id)
            return True
    except peewee.IntegrityError as exc:
        logging.error('Error creating new customer with ID %s: %s.',
                      customer_id, exc)
        return False
    finally:
        database.close()
示例#14
0
def add_customer(name, lastname, home_address, phone_number, email_address,
                 status, credit_limit):
    """create a new customer object in the database table"""
    try:
        with DATABASE.transaction():
            new_customer = Customer.create(name=name,
                                           lastname=lastname,
                                           home_address=home_address,
                                           phone_number=phone_number,
                                           email_address=email_address,
                                           status=status,
                                           credit_limit=credit_limit)
            new_customer.save()
            LOGGER.info('Database add successful')
            return new_customer
    except pw.IntegrityError as exc:
        LOGGER.info("Error creating %s; Exception: %s", name, exc)
def add_customer(customer_id, name, lastname, home_address, phone_number,
                 email_address, status, credit_limit):
    """ Add a new customer to the database """

    try:
        logging.debug(f"Adding new customer: {name} {lastname}")
        with DATABASE.transaction():
            Customer.create(customer_id=customer_id,
                            name=name,
                            lastname=lastname,
                            home_address=home_address,
                            phone_number=phone_number,
                            email_address=email_address,
                            status=status,
                            credit_limit=credit_limit)
        logging.debug("Customer added successfully")
    except IntegrityError:
        logging.error(f"Error adding customer: {name} {lastname}")
        raise IntegrityError
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:
        # id is automatically created and incremented by 1
        with DATABASE.transaction():
            new_customer = Customer.create(
                id=customer_id, name=name, last_name=lastname,
                home_address=home_address, phone_number=phone_number,
                email=email_address, status=status, credit_limit=credit_limit)
            new_customer.save()
            LOGGER.info(f'Database add successful for customerId {name}')

    except (OperationalError,
            DoesNotExist) as exc:
        LOGGER.info(f'Error creating = {name}')
        LOGGER.info(exc)
示例#17
0
def update_customer_credit(customer_id, credit_limit):
    """
    Update customer credit limit by searching customer id.
    :param customer_id: ID of the customer
    :param credit_limit: Credit limit to be set for the customer
    :return: None
    """
    try:
        LOGGER.info('Update credit limit for customer.')
        with DATABASE.transaction():
            a_customer = Customer.get(Customer.customer_id == customer_id)
            a_customer.credit_limit = int(credit_limit)
            a_customer.save()
            LOGGER.info('customer credit limit has updated')

    except Customer.DoesNotExist as error:
        LOGGER.info('Updated failed.')
        LOGGER.info('Customer with id %s not found.', customer_id)
        LOGGER.info(error)
        raise ValueError
示例#18
0
def update_customer_credit(customer_id, credit_limit):
    """
    Search an existing customer by customer_id and update their credit limit or
    raise a ValueError exception if the customer does not exist
    :param customer_id: Integer representing the customer id
    :param credit_limit: Float representing the credit limit dollar amount
    :raise ValueError: Raised if the customer id does not exist
    """
    LOGGER.info("Updating credit limit for Customer ID %s", customer_id)
    try:
        result_customer = Customer.get_by_id(customer_id)
        with DATABASE.transaction():
            result_customer.credit_limit = credit_limit
            result_customer.save()
            LOGGER.info("Updating customer, %s %s's credit limit to %s",
                        result_customer.name, result_customer.last_name,
                        credit_limit)
    except DoesNotExist:
        LOGGER.info(
            "Can not modify credit limit because customer ID %s doesn't exist.",
            customer_id)
        raise ValueError
示例#19
0
def reset_db():
    '''Resets the database'''
    DATABASE.drop_tables([Customer])
    DATABASE.create_tables([Customer])
示例#20
0
        msg = f'Customer {customer_id} is not found in the database'
        LOGGER.error(msg)
        raise ValueError


def list_active_customer():
    """ Return the number of customers with the active status."""
    LOGGER.debug("Searching the total active users")
    active_members = Customer.select().where(Customer.status).count()
    msg = f'Active Customers = {active_members}'
    LOGGER.info(msg)
    return active_members


if __name__ == "__main__":

    DATABASE.create_tables([Customer])
    # add_customer(1, 'Muhammad', 'Khan',
    #              '9x9 xyzxy Dr. Apt # 529D xxxxxx SC. 29403',
    #              '202-755-3xx1', '*****@*****.**', True, 244.20)
    # add_customer(2, 'Kristina', 'Lawry',
    #              '8x8 xyzxy Dr. Apt # 200D xxxxxx WA. 60089',
    #              '747-900-4950', '*****@*****.**', True, 399)
    # # update_customer(3, 500.00)
    # print(search_customer(2))
    # delete_customer(2)
    # print(search_customer(2))
    # update_customer(3, 500.00)
#     # for data in Customer.select():
#     #     print(data.credit_limit)
def init_database():
    """This function checks to see if the database exists, and if not, generates the tables."""
    database.init(DATABASE_NAME)
    database.connect()
    database.execute_sql('PRAGMA foreign_keys = ON')
    if not database.table_exists([Customer]):
        database.create_tables([Customer])
    database.close()
示例#22
0
    def tearDown(self):
        """ Ensure we start with a clean table """

        DATABASE.drop_tables([Customer])
        DATABASE.create_tables([Customer])
示例#23
0
 def tearDownClass(cls):
     """
     close the database connection at the end of each test.
     """
     # print('teardown method is called')
     DATABASE.close()
示例#24
0
class OperationalTests(TestCase):
    """ Define a class for testing operations """

    def setUp(self):
        """ Ensure we start with a clean table """

    DATABASE.drop_tables([Customer])
    DATABASE.create_tables([Customer])

    def test_add_customer(self):
        """ Test adding customers """

        # Add a customer and ensure it is in the DB
        bo.add_customer(**TEST_USER1)
        test_customer = Customer.get(Customer.customer_id == TEST_USER1['customer_id'])
        self.assertEqual(test_customer.name, TEST_USER1['name'])

        # Ensure adding a non-unique customer_id fails
        with self.assertRaises(IntegrityError):
            bo.add_customer(**TEST_USER1)

        # Delete the test user
        bo.delete_customer(TEST_USER1['customer_id'])

    def test_search_customer(self):
        """ Test searching for a customer """

        # Add a customer and ensure it is in the DB
        bo.add_customer(**TEST_USER1)

        # Search for a valid user created in the first test
        test_customer = bo.search_customer(TEST_USER1['customer_id'])
        self.assertEqual(test_customer.name, TEST_USER1['name'])

        # Search for an invalid user
        with self.assertRaises(DoesNotExist):
            test_customer = bo.search_customer(50)

        # Delete the test user
        bo.delete_customer(TEST_USER1['customer_id'])

    def test_delete_customer(self):
        """ Test deleting customers """

        # Add a user to ensure we have something to delete
        bo.add_customer(**TEST_USER2)

        # Delete the test user
        bo.delete_customer(TEST_USER2['customer_id'])

        # Search for an invalid user
        with self.assertRaises(DoesNotExist):
            Customer.get(Customer.customer_id == TEST_USER2['customer_id'])

    def test_update_customer_credit(self):
        """ Test updating a customer's credit limit """

        # Add a user to ensure we have something to delete
        bo.add_customer(**TEST_USER1)

        # Update the limit for the first test user
        bo.update_customer_credit(TEST_USER1['customer_id'], 2500.00)
        test_customer = Customer.get(Customer.customer_id == TEST_USER1['customer_id'])
        self.assertEqual(test_customer.credit_limit, 2500.00)

        # Update the limit for a customer that doesn't exist
        with self.assertRaises(DoesNotExist):
            bo.update_customer_credit(50, 3000.00)

        # Delete the test user
        bo.delete_customer(TEST_USER1['customer_id'])

    def test_list_customers(self):
        """ Test listing all customers in the database """

        # Add an active customer
        bo.add_customer(**TEST_USER1)

        # Add an inactive customer
        bo.add_customer(**TEST_USER2)

        # Print the active customers
        active_customers = bo.list_active_customers()
        self.assertEqual(active_customers, 1)

    def tearDown(self):
        """ Ensure we start with a clean table """

        DATABASE.drop_tables([Customer])
        DATABASE.create_tables([Customer])
示例#25
0
 def setUp(self):
     """Defines starting test database used for function testing."""
     starting_db = [(1, 'Bob', 'Bobbo', '12 Green St', '1112223344',
                     '*****@*****.**', False, 85000),
                    (2, 'Jane', 'Janeo', '1550 Red Rd', '1118675309',
                     '*****@*****.**', True, 150000),
                    (5, 'Wilson', 'Volleyball', '1 Castaway Island',
                     '0000000000', '*****@*****.**', True, 0)]
     database.init(TEST_DATABASE)
     database.connect()
     database.execute_sql('PRAGMA foreign_keys = ON')
     database.create_tables([Customer])
     with database.transaction():
         Customer.delete().execute()
         Customer.insert_many(starting_db,
                              fields=[
                                  Customer.customer_id, Customer.name,
                                  Customer.lastname, Customer.home_address,
                                  Customer.phone_number,
                                  Customer.email_address,
                                  Customer.active_status,
                                  Customer.credit_limit
                              ]).execute()
     database.close()