def delete_customer(customer_id):
    """
        delete a customer by id
    """
    try:
        # open database
        DATABASE.connect()
        DATABASE.execute_sql('PRAGMA foreign_keys=ON;')
        LOGGER.info("connected to database")

        # remove customer by id
        Customer.get_by_id(customer_id).delete_instance()
        LOGGER.info("id %s customer deleted", customer_id)

    except OperationalError as err:
        LOGGER.info("conection to database failed")
        LOGGER.info(err)

    except IntegrityError as err:
        LOGGER.info("customer with id %s not found", customer_id)
        LOGGER.info(err)

    finally:
        # close database
        DATABASE.close()
        LOGGER.info("database closed")
 def test_delete_customer(self, mock_database):
     """Testing deleting a customer to the database via delete_customer function."""
     basic_operations.DATABASE_NAME = TEST_DATABASE
     self.assertTrue(delete_customer(1))
     with self.assertRaises(peewee.DoesNotExist):
         Customer.get_by_id(1)
     self.assertFalse(delete_customer(3))
示例#3
0
 def test_delete_customer(self):
     """ Tests that a customer can be deleted """
     set_up_db()
     add_customer(*self.test_customer)
     delete_customer(1)
     try:
         Customer.get_by_id(1)
     except DoesNotExist:
         LOGGER.info("Customer was deleted.")
示例#4
0
def delete_customer(customer_id):
    '''Deletes a specific customer from the database.'''
    try:
        LOGGER.info('Searching for customer ID %s to delete from the database', customer_id)
        Customer.get_by_id(customer_id)
        Customer.delete_by_id(customer_id)
        LOGGER.info('Customer %s is deleted from the database', customer_id)
    except peewee.DoesNotExist:
        LOGGER.info('Customer ID: %s is not available to delete from the database', customer_id)
        raise ValueError
示例#5
0
 def test_add_customers(self):
     """ Test adding a valid customer records to the DB """
     set_up_db()
     add_customers(self.test_customers)
     test_customer = Customer.get_by_id(1)
     self.assertEqual(self.test_customers[0][1], test_customer.name)
     test_customer = Customer.get_by_id(2)
     self.assertEqual(self.test_customers[1][1], test_customer.name)
     test_customer = Customer.get_by_id(3)
     self.assertEqual(self.test_customers[2][1], test_customer.name)
示例#6
0
 def test_add_customer(self):
     """ Test add_customer() """
     logging.info("test_add_customer()")
     # Initial database set up
     set_up()
     # Populate customers data into the database
     for person in CLIENTS:
         add_customer(**person)
         logging.info(Customer.get_by_id(person['customer_id']).phone_number)
         self.assertEqual(person['phone_number'], Customer.get_by_id(person['customer_id']).phone_number)
     # Remove data and exit database
     tear_down()
示例#7
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())
 def test_update_customer_credit(self, mock_database):
     """Testing updating customer credit via update_customer_credit function."""
     basic_operations.DATABASE_NAME = TEST_DATABASE
     self.assertTrue(update_customer_credit(5, 5000))
     self.assertEqual(Customer.get_by_id(5).credit_limit, 5000)
     with self.assertRaises(ValueError):
         update_customer_credit(4, 80000)
示例#9
0
def update_status(customer_id, new_status):
    """
        update customer status
    """
    try:
        # open database
        DATABASE.connect()
        DATABASE.execute_sql('PRAGMA foreign_keys=ON;')
        LOGGER.info("connected to database")

        # search customer by id
        searched_customer = Customer.get_by_id(customer_id)
        # check searched customer's status and update it if active or inactive
        if new_status in ("active", "inactive"):
            searched_customer.status = new_status
            LOGGER.info("status updated for customer id %s", customer_id)
            # save updated customer
            searched_customer.save()
        else:
            LOGGER.info("status neither active or inactive")
            LOGGER.info("status wasn't updated")

    except DoesNotExist as err:
        LOGGER.info("customer id %s not found", customer_id)
        LOGGER.info(err)

    finally:
        # close database
        DATABASE.close()
        LOGGER.info("database closed")
示例#10
0
def update_credit(customer_id, credit_limit):
    """
        search customer by id and update credit limit
    """
    try:
        # open database
        DATABASE.connect()
        DATABASE.execute_sql('PRAGMA foreign_keys=ON;')
        LOGGER.info("connected to database")

        # retrive customer by id
        searched_customer = Customer.get_by_id(customer_id)

        # update customer's credit limit
        searched_customer.credit_limit = credit_limit
        LOGGER.info("credit limit updated for customer id %s", customer_id)

        # save updated customer
        searched_customer.save()

    except DoesNotExist as err:
        LOGGER.info("customer id %s not found", customer_id)
        LOGGER.info("credit limit of %s for customer id %s not updated",
                    credit_limit, customer_id)
        LOGGER.info(err)

    finally:
        # close database
        DATABASE.close()
        LOGGER.info("database closed")
def delete_customer(customer_id):
    """ deletes customer from database"""
    print('Deleting customer with ID {}...'.format(customer_id))
    try:
        customer_delete = Customer.get_by_id(customer_id)
        customer_delete.delete_instance()
        LOGGER.info('Customer with Customer ID %s has been deleted',
                    customer_id)
    except Customer.DoesNotExist:
        print('No record of customer with Customer ID {}'.format(customer_id))
        print('No customer deleted')
def update_customer_credit(customer_id, new_credit_limit):
    """update credit limit"""
    print('Updating customer with ID {}...'.format(customer_id))
    try:
        customer_credit_update = Customer.get_by_id(customer_id)
        customer_credit_update.credit_limit = new_credit_limit
        customer_credit_update.save()
        LOGGER.info('Customer with ID %s has been updated', customer_id)
    except Customer.DoesNotExist:
        print('No record of customer with Customer ID {}'.format(customer_id))
        print('No customer updated')
示例#13
0
 def test_add_customer(self):
     """ Test add_customer() """
     logging.info("test_add_customer()")
     # Initial database set up
     set_up()
     # Populate customers data into the database
     for person in CLIENTS:
         add_customer(**person)
         self.assertEqual(person['phone_number'], Customer.get_by_id(person['customer_id']).phone_number)
         logging.critical(f"Add new customer to database: {person['name']} {person['lastname']} (id={person['customer_id']})")
     # Remove data and exit database
     tear_down()
示例#14
0
 def test_add_customer(self):
     """ Test adding a valid customer record to the DB """
     set_up_db()
     add_customer(*self.test_customer)
     test_customer = Customer.get_by_id(1)
     self.assertEqual("Bruce", test_customer.name)
     self.assertEqual("Wayne", test_customer.last_name)
     self.assertEqual("1007 Mountain Drive, Gotham",
                      test_customer.home_address)
     self.assertEqual("228-626-7699", test_customer.phone_number)
     self.assertEqual("*****@*****.**", test_customer.email)
     self.assertEqual(True, test_customer.status)
     self.assertEqual(200000.00, test_customer.credit_limit)
示例#15
0
 def test_update_customer_credit(self):
     """ Test update_customer_credit() """
     logging.info("test_update_customer_credit()")
     # Initial database set up
     set_up()
     # Populate customers data into the database
     for person in CLIENTS:
         add_customer(**person)
     # Update credit limit of customer id = 2
     update_customer_credit(2, 15000)
     self.assertEqual(15000, Customer.get_by_id(2).credit_limit)
     # Remove data and exit database
     tear_down()
def update_customer_credit(customer_id, credit_limit):
    """ Update an existing customer's credit limit in the database """
    logging.info("update_customer_credit()")
    try:
        with database.atomic():
            person = Customer.get_by_id(customer_id)
            person.credit_limit = credit_limit
            Customer.bulk_update([person], fields=[Customer.credit_limit])
    except DoesNotExist:
        logging.error(
            f"Can't find customer data with id = {customer_id} in the database."
        )
        raise ValueError
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()
示例#18
0
def delete_customer(customer_id):
    """
        delete a customer by id
    """
    try:
        # open database
        DATABASE.connect()
        DATABASE.execute_sql('PRAGMA foreign_keys=ON;')
        LOGGER.info("connected to database")

        # remove customer by id
        Customer.get_by_id(customer_id).delete_instance()
        LOGGER.info("id %s customer deleted", customer_id)

    except DoesNotExist as err:
        LOGGER.info("customer with id %s not deleted", customer_id)
        LOGGER.info(err)

    finally:
        # close database
        DATABASE.close()
        LOGGER.info("database closed")
示例#19
0
 def test_update_customer_credit(self):
     """ Test update_customer_credit() """
     logging.info("test_update_customer_credit()")
     # Initial database set up
     set_up()
     # Populate customers data into the database
     for person in CLIENTS:
         add_customer(**person)
     # Update credit limit of customer id = 2
     update_customer_credit(2, 15000)
     self.assertEqual(15000, Customer.get_by_id(2).credit_limit)
     logging.critical(f"Update credit limit of customer {CLIENTS[1]['name']} {CLIENTS[1]['lastname']} (id={CLIENTS[1]['customer_id']}) from ${CLIENTS[1]['credit_limit']} to $15000")
     # Remove data and exit database
     tear_down()
def add_customer(customer_id, first_name, last_name, home_address,
                 phone_number, email_address, status, credit_limit):
    """ adds customer to database"""
    print('Adding new customer, Customer ID {}...'.format(customer_id))
    try:
        Customer.get_by_id(customer_id)
        print('Customer ID {} is already in use'.format(customer_id))
    except Exception as ex:
        if "instance matching query does not exist" in str(ex):
            try:
                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,
                                               status=status,
                                               credit_limit=credit_limit)
                new_customer.save()
                LOGGER.info('Added new customer, Customer ID %s', customer_id)
            except IntegrityError:
                print('Incorrect format, customer {} not saved'
                      .format(customer_id))
示例#21
0
    def test_add_customer(self, mock_database):
        """Testing adding a customer to the database via add_customer function."""
        basic_operations.DATABASE_NAME = TEST_DATABASE
        add_customer(17, 'Bob', 'Testy', '111 Test St', 1234567890, '*****@*****.**', True, 70000)
        test_customer = Customer.get_by_id(17)
        self.assertEqual(test_customer.name, 'Bob')
        self.assertEqual(test_customer.lastname, 'Testy')
        self.assertEqual(test_customer.home_address, '111 Test St')
        self.assertEqual(test_customer.phone_number, '1234567890')
        self.assertEqual(test_customer.email_address, '*****@*****.**')
        self.assertEqual(test_customer.active_status, True)
        self.assertEqual(test_customer.credit_limit, 70000)

        self.assertFalse(add_customer(17, 'Bob', 'Testy', '111 Test St', 1234567890,
                                      '*****@*****.**', True, 70000))
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()
示例#23
0
 def test_add_customer_invalid_phone(self):
     """ Test add_customer() with an invalid phone number """
     CLIENTS_INVALID_PHONE = [
         {'customer_id': 1, 'name': 'Andrew', 'lastname': 'York', 'home_address': "This is Andrew's home address", 'phone_number': '425-111-1111-dummy', 'email_address': '*****@*****.**', 'status': True, 'credit_limit': 10000},
         {'customer_id': 2, 'name': 'Peter', 'lastname': 'Young', 'home_address': "This is Peter's home address", 'phone_number': '425-222-2222-extra', 'email_address': '*****@*****.**', 'status': False, 'credit_limit': 5000},
     ]
     logging.info("test_add_customer_invalid_phone()")
     # Initial database set up
     set_up()
     # Populate customers data into the database
     for person in CLIENTS_INVALID_PHONE:
         with self.assertRaises(IntegrityError):
             add_customer(**person)
             logging.info(Customer.get_by_id(person['customer_id']).phone_number)
     # Remove data and exit database
     tear_down()
示例#24
0
    def test_main_integration(self, mock_database):
        """Full integration testing of basic_operations.py functions."""
        basic_operations.DATABASE_NAME = TEST_DATABASE
        self.assertEqual(list_active_customers(), 2)
        add_customer(17, 'Bob1', 'Testy', '111 Test St', 1234567890,
                     '*****@*****.**', True, 70000)
        add_customer(18, 'Bob2', 'Testo', '112 Test St', 2234567890,
                     '*****@*****.**', True, 71000)
        add_customer(19, 'Bob3', 'Testi', '113 Test St', 3234567890,
                     '*****@*****.**', False, 72000)

        exp_dict = {
            'name': 'Bob2',
            'lastname': 'Testo',
            'email_address': '*****@*****.**',
            'phone_number': '2234567890'
        }
        self.assertDictEqual(search_customer(18), exp_dict)

        update_customer_credit(19, 50000)
        self.assertEqual(Customer.get_by_id(19).credit_limit, 50000)
        delete_customer(18)
        self.assertEqual(list_active_customers(), 3)

        ending_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),
                     (17, 'Bob1', 'Testy', '111 Test St', 1234567890,
                      '*****@*****.**', True, 70000),
                     (19, 'Bob3', 'Testi', '113 Test St', 3234567890,
                      '*****@*****.**', False, 50000)]
        table_columns = ('customer_id', 'name', 'lastname', 'home_address',
                         'phone_number', 'email_address', 'active_status',
                         'credit_limit')
        expected_print = ' | '.join(
            ('{:^20}'.format(column) for column in table_columns))
        for row in ending_db:
            expected_print += '\n' + ' | '.join(
                ('{:^20}'.format(str(x)) for x in row))
        with patch('sys.stdout', new=StringIO()) as captured_output:
            report_all_customers()
            self.assertEqual(captured_output.getvalue().rstrip('\n'),
                             expected_print)
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()
 def test_add_customer(self):
     """ tests add_customer"""
     TEST_DB.bind(MODELS, bind_refs=False, bind_backrefs=False)
     TEST_DB.create_tables(MODELS)
     add_customer(*CUSTOMERS[0])
     test_c1 = Customer.get_by_id('00001')
     self.assertEqual(test_c1.customer_ID, '00001')
     self.assertEqual(test_c1.first_name, 'Dorothy')
     self.assertEqual(test_c1.last_name, 'Zbornak')
     self.assertEqual(test_c1.home_address, 'Miami')
     self.assertEqual(test_c1.phone_number, '5551234567')
     self.assertEqual(test_c1.email_address, '*****@*****.**')
     self.assertEqual(test_c1.status, True)
     self.assertEqual(test_c1.credit_limit, 1000)
     add_customer(*CUSTOMERS[0])
     self.assertRaises(Exception)
     add_customer(*CUSTOMERS[4])
     self.assertRaises(Exception)
def search_customer(customer_id):
    """ Search for a customer in the database using customer_id """
    logging.info("search_customer()")
    result = {}
    try:
        with database.transaction():
            person = Customer.get_by_id(customer_id)
            result = {
                'name': person.name,
                'lastname': person.lastname,
                'email_address': person.email_address,
                'phone_number': person.phone_number
            }
    except DoesNotExist:
        logging.error(
            f"Can't find customer data with id = {customer_id} in the database."
        )
    finally:
        return result
def search_customer(customer_id):
    """
        search a customer by id
    """
    try:
        # open database
        DATABASE.connect()
        DATABASE.execute_sql('PRAGMA foreign_keys=ON;')
        LOGGER.info("connected to database")

        # search a customer by id
        searched_customer = Customer.get_by_id(customer_id)
        LOGGER.info("customer %s found", customer_id)

        # retrive full info for searched customer from database
        return {
            "customer_id": searched_customer.customer_id,
            "first_name": searched_customer.first_name,
            "last_name": searched_customer.last_name,
            "home_address": searched_customer.home_address,
            "email_address": searched_customer.email_address,
            "phone_number": searched_customer.phone_number,
            "status": searched_customer.status,
            "credit_limit": searched_customer.credit_limit,
            #-------------------------
            "join_date": searched_customer.join_date,
            "insertion_date": searched_customer.insertion_date,
            "time_stamp": searched_customer.time_stamp,
            "hobby": searched_customer.hobby
        }

    except OperationalError as err:
        LOGGER.info("conection to database failed")
        LOGGER.info(err)

    except IntegrityError as err:
        LOGGER.info("customer not found")

    finally:
        # close database
        DATABASE.close()
        LOGGER.info("database closed")
def search_customer(customer_id):
    """ returns customer information from database"""
    print('Searching for customer, Customer ID {}...'.format(customer_id))
    try:
        customer_search = Customer.get_by_id(customer_id)
        if customer_search.status is True:
            status = 'Active'
        else:
            status = 'Inactive'
        customer_dict = {'Customer ID': customer_id,
                         'First Name': customer_search.first_name,
                         'Last Name': customer_search.last_name,
                         'Home Address': customer_search.home_address,
                         'Phone Number': customer_search.phone_number,
                         'Email Address': customer_search.email_address,
                         'Status': status,
                         'Credit Limit': customer_search.credit_limit}
        print('Info for Customer ID {}'.format(customer_id))
        return customer_dict
    except Customer.DoesNotExist:
        print('No record of customer with Customer ID {}'.format(customer_id))
示例#30
0
def search_customer(customer_id):
    """
    Look up for a customer
    :param customer_id: Integer representing the customer ID
    :return: A dictionary object with name, last name, email address and phone number of a customer
    or an empty dictionary object if no customer was found.
    """
    LOGGER.info("Looking up customer ID %s:", customer_id)
    try:
        result_customer = Customer.get_by_id(customer_id)
        LOGGER.info("Found customer ID %s, %s %s", customer_id,
                    result_customer.name, result_customer.last_name)
        return {
            "name": result_customer.name,
            "last_name": result_customer.last_name,
            "email": result_customer.email,
            "phone_number": result_customer.phone_number
        }
    except DoesNotExist:
        LOGGER.info("Customer ID %s was not found.", customer_id)
        return {}