Esempio n. 1
0
def remove_contact(phone_book: PhoneBook):
    name = input("Enter name")

    contact = phone_book.find_contact(name)

    if contact is not None:
        phone_book.remove_contact(contact)
        print("Contact successfully removed")
Esempio n. 2
0
def write_contacts(phone_book: PhoneBook):
    if phone_book.get_count() == 0:
        print("List is empty")
        return

    for contact in phone_book.get_contacts():
        print(
            f'Name: {contact.get_name()} PersonalPhone: {contact.get_personal_phone()} Phone {contact.get_phone()}'
            f' Description {contact.get_description()}')
Esempio n. 3
0
def add_contact(phone_book: PhoneBook):
    name = input("Enter name")
    contact = Contact(name)

    contact.personal_phone = input("Enter PersonalPhone")
    contact.phone = input("Enter Phone")
    contact.description = input("Enter Description")

    phone_book.add_contact(contact)

    print("Contact successfully added")
    def __init__(self):

        config = ConfigParameters()
        self.phone_book_file_db = config.get_phone_book_file_db()
        dict = self.phone_book_file_db.load_phone_book_from_file()
        self.book = PhoneBook()
        self.book.load_phone_book_from_dict(dict)

        self.controller = {
            1: self._create_phone_number,
            2: self._get_phone_by_name,
            3: self._get_customer_by_phone,
            4: self._delete_by_name,
            5: self._show_all
        }
Esempio n. 5
0
def main():

    _phone_book = PhoneBook()
    print("Phone Book is Open")

    phone_book_help()
    for line in sys.stdin:
        if (line.rstrip() == '1'):
            input_handler['1'](_phone_book)
        elif (line.rstrip() == '2'):
            input_handler['2'](_phone_book)
        elif (line.rstrip() == '3'):
            input_handler['3'](_phone_book)
        elif (line.rstrip() == '4'):
            input_handler['4'](_phone_book)
        elif (line.rstrip() == '5'):
            input_handler['5'](_phone_book)
        elif (line.rstrip() == '6'):
            input_handler['6'](_phone_book)
        elif (line.rstrip() == '7'):
            input_handler['7'](_phone_book)
        elif (line.rstrip() == '8'):
            input_handler['8'](_phone_book)
        elif (line.rstrip() == 'q'):
            break
        else:
            print("Unknown input")
        phone_book_help()
Esempio n. 6
0
def before_feature(context, feature):
    if feature.name == 'New numbers':
        phone_book = PhoneBook(phone_numbers=[333],
                               address_book={
                                   'name': 'mahshad',
                                   'last_name': 'esl'
                               })
        context.phone_book = phone_book
        logging.info(context.phone_book.phone_numbers)
Esempio n. 7
0
def main() -> bool:    
    """
    Docstring
    """
    print("Hello, dear User! I'm your pleasant programm to work with phone books.")

    global phone_book
    phone_book = PhoneBook()

    while True:
        user_input = get_user_input()

        if handle_user_input(user_input):
            continue
        else:
            break

    return phone_book.save_phone_book()
def processInput():
    phoneBook = PhoneBook()
    input = sys.stdin.readlines()
    n = int(input.pop(0))
    
    #process phone book entries
    for idx in range(n):
        entry = input[idx].rstrip()
        isEntryValid = PhoneBook.validateEntry(entry)
        if(isEntryValid):
            phoneBook.addEntry(entry)
        else:
            errorMsg = "Invalid entry: " + entry
            logging.error(errorMsg)
            
    del input[:n] #delete phone book entries and remain with queries only
        
    #process queries
    for idx in range(n):
        name = input[idx].rstrip()
        phoneBook.displayEntry(name)
Esempio n. 9
0
 def test_validate_entry(self):
     self.assertTrue(PhoneBook.validateEntry('brian 12345678'))
     self.assertFalse(PhoneBook.validateEntry('klaus4 1234567'))
     self.assertFalse(PhoneBook.validateEntry('thomas 1234567a'))
     self.assertFalse(PhoneBook.validateEntry('thomas4 1234567a'))
Esempio n. 10
0
from contact import Contact
from phone_book import PhoneBook

print("Phone book")

phoneBook = PhoneBook()


def write_contacts(phone_book: PhoneBook):
    if phone_book.get_count() == 0:
        print("List is empty")
        return

    for contact in phone_book.get_contacts():
        print(
            f'Name: {contact.get_name()} PersonalPhone: {contact.get_personal_phone()} Phone {contact.get_phone()}'
            f' Description {contact.get_description()}')


def add_contact(phone_book: PhoneBook):
    name = input("Enter name")
    contact = Contact(name)

    contact.personal_phone = input("Enter PersonalPhone")
    contact.phone = input("Enter Phone")
    contact.description = input("Enter Description")

    phone_book.add_contact(contact)

    print("Contact successfully added")
 def setUp(self):
     self.pb = PhoneBook(FILENAME)
class PhonebookTest(unittest.TestCase):
    def setUp(self):
        self.pb = PhoneBook(FILENAME)

    def load_some_data(self):
        self.pb.update("Sam", "222 333 4444")
        self.pb.update("Becky", "123 456 7890")
        self.pb.update("Trisquit", "999 888 4444")
        self.pb.update("Ralf", '444 333 2222')
    
    def test_query(self):
        self.load_some_data()
        self.assertEqual(self.pb.query("Sam"), "Sam => 222 333 4444")

    def test_delete(self):
        self.load_some_data()
        self.assertEqual(self.pb.query("Sam"), "Sam => 222 333 4444")
        self.pb.delete("Sam")
        self.assertEqual(self.pb.query("Sam"), "not found")
   
    def test_add(self):
        self.load_some_data()
        self.assertEqual(self.pb.query("Barnabus"), "not found")
        self.pb.update("Barnabus", "1234")
        self.assertEqual(self.pb.query("Barnabus"), "Barnabus => 1234") 
         
    def tearDown(self):
        os.unlink(FILENAME)
Esempio n. 13
0
 def setUp(self):
     '''initialization'''
     self.initPhoneBook = PhoneBook()
 def setUp(self) -> None:
     self.phone_book = PhoneBook()
class PhoneBookViewController(object):
    def __init__(self):

        config = ConfigParameters()
        self.phone_book_file_db = config.get_phone_book_file_db()
        dict = self.phone_book_file_db.load_phone_book_from_file()
        self.book = PhoneBook()
        self.book.load_phone_book_from_dict(dict)

        self.controller = {
            1: self._create_phone_number,
            2: self._get_phone_by_name,
            3: self._get_customer_by_phone,
            4: self._delete_by_name,
            5: self._show_all
        }

    def print_text(self, text):
        print text

    def print_to_socket(self, socket, text):
        socket.sendall(text)

    @staticmethod
    def print_menu():
        CRUD_DICT = {
            1: 'Create phone number',
            2: 'Get phone number by name',
            3: 'Get customer name by phone',
            4: 'Delete phone number by name',
            5: 'Show all phones on a book',
            0: 'Exit'
        }

        for i, text in CRUD_DICT.items():
            print str(i) + " : " + text

        try:
            choice = int(raw_input('Input your choice:'))
        except ValueError:
            print 'Wrong input!'
            choice = settings.DEFAULT_CHOICE

        return choice

    def catch_name_error(func):
        def wrapper(self, *args):
            try:
                return func(self, *args)
            except NameError as e:
                print e
            # except:
            #      print 'ERROR!'

        return wrapper

    @catch_name_error
    def start_action(self, choice):
        self.controller.get(choice, self._default_choice)()
        self.phone_book_file_db.save_phone_book_to_file(self.book)

    @staticmethod
    def _input_phone_number():
        phone_number = str(raw_input())

        while not phone_number.isdigit():
            print 'WARN Inocrrect msisdn. Please retry.'
            phone_number = str(raw_input())
        return phone_number

    def _default_choice(self):
        pass

    def _create_phone_number(self):
        print '1. Please input phone number: '
        phone_number = self._input_phone_number()
        print '2. Please input customer name: '
        customer = raw_input()
        phone_number_unicode = phone_number.decode('utf-8')
        customer_unicode = customer.decode('utf-8')
        self.book.add_new_subscriber(phone_number_unicode, customer_unicode)
        print "OK."

    def _get_phone_by_name(self):
        print '1. Please input customer name: '
        customer = raw_input()
        customer_unicode = customer.decode('utf-8')
        subscriber_item = self.book.get_phone_by_subscriber(customer_unicode)
        item_0_u = subscriber_item[0].center(
            settings.CENTER_WIDTH).encode('utf-8')
        item_1_u = subscriber_item[1].center(
            settings.CENTER_WIDTH).encode('utf-8')
        try:
            print '|------Subscriber------|-----Phone number-----|'
            print '| {}|{} |'.format(item_0_u, item_1_u)
            print '|----------------------|----------------------|'
        except TypeError:
            pass

    def _get_customer_by_phone(self):
        print '1. Please input msisdn: '
        phone_number = self._input_phone_number()
        phone_number_u = phone_number.decode('utf-8')
        try:
            subscriber = self.book.get_subscriber_by_phone(phone_number_u)
            phone_number_unicode = phone_number.center(
                settings.CENTER_WIDTH).decode('utf-8')
            subscriber_unicode = subscriber.center(
                settings.CENTER_WIDTH).decode('utf-8')
            print '|------Subscriber------|-----Phone number-----|'
            print '| {}|{} |'.format(subscriber_unicode, phone_number_unicode)
            print '|----------------------|----------------------|'
        except NameError:
            pass

    def _delete_by_name(self):
        print '1. Please input customer name to delete: '
        subscriber = raw_input()
        self.book.delete_customer_by_name(subscriber.decode('utf-8'))
        print 'Subscribers {} phone deleted'.format(subscriber)

    def _show_all(self):
        dic = self.book.get_phone_book_dict()
        print '|------Subscriber------|-----Phone number-----|'

        for phone, name in dic.items():
            name_pre_utf = name.center(settings.CENTER_WIDTH).encode('utf-8')
            phone_pre_utf = phone.center(settings.CENTER_WIDTH).encode('utf-8')
            print '| {}|{} |'.format(name_pre_utf, phone_pre_utf)
        print '|----------------------|----------------------|'
Esempio n. 16
0
 def setUp(self):
     self.pb = PhoneBook(FILENAME)
Esempio n. 17
0
class PhonebookTest(unittest.TestCase):
    def setUp(self):
        self.pb = PhoneBook(FILENAME)

    def load_some_data(self):
        self.pb.update("Sam", "222 333 4444")
        self.pb.update("Becky", "123 456 7890")
        self.pb.update("Trisquit", "999 888 4444")
        self.pb.update("Ralf", '444 333 2222')

    def test_query(self):
        self.load_some_data()
        self.assertEqual(self.pb.query("Sam"), "Sam => 222 333 4444")

    def test_delete(self):
        self.load_some_data()
        self.assertEqual(self.pb.query("Sam"), "Sam => 222 333 4444")
        self.pb.delete("Sam")
        self.assertEqual(self.pb.query("Sam"), "not found")

    def test_add(self):
        self.load_some_data()
        self.assertEqual(self.pb.query("Barnabus"), "not found")
        self.pb.update("Barnabus", "1234")
        self.assertEqual(self.pb.query("Barnabus"), "Barnabus => 1234")

    def tearDown(self):
        os.unlink(FILENAME)
Esempio n. 18
0
    def menu_entries():
        pb = PhoneBook(PHONE_BOOK_NAME)
        print(LINE)
        print('Телефонная книга 0.1')

        while True:
            print(LINE)
            print('Вводите команду, h - справка, q - выход')

            choose = input()

            if choose.lower() in ['a']:
                pb.add_contact()
            elif choose.lower() in ['e']:
                name = input('Какую запись вы хотите редактировать (ИМЯ): ').title()
                pb.edit_contact(name)
            elif choose.lower() in ['s']:
                name = input('Какую запись вы хотите найти (ИМЯ): ').title()
                pb.search_contact(name)
            elif choose.lower() in ['d']:
                name = input('Какую запись вы хотите удалить (ИМЯ): ').title()
                res = pb.del_contact(name)
                if res:
                    print(name, ' - запись была успешно удалена')
                else:
                    print('ОШИБКА: Имени нет в базе')
            elif choose.lower() in ['l']:
                pb.list()
            elif choose.lower() in ['h']:
                print('''\
                МЕНЮ КОМАНД:
    ======================================
    a(Add)      - Добавить запись в книгу
    e(Edit) -   - Редактирование записи
    s(Search)   - Поиск контакта
    d(Delete)   - Удаление контакта
    h(Help)     - Показать эту справку
    l(List)     - Отобразить все контакты отсортированные по алфавиту
    q(Quit)     - Выход из программы''')
            elif choose.lower() in ['q']:
                print('Завершение работы программы')
                pb.save()
                raise SystemExit
            else:
                print('Команда не распознана')
Esempio n. 19
0
class TestPhoneBook(unittest.TestCase):
    def setUp(self):
        '''initialization'''
        self.initPhoneBook = PhoneBook()

    def test_add_contact(self):
        '''Test if contact is added'''
        response = self.initPhoneBook.add_contact('Dalin', 712876245)
        self.assertEqual(response, 'contact added')

    def test_phone_number_exists(self):
        '''     
            Create new contact and see if number entries
        '''
        self.initPhoneBook.add_contact('Nancy', 712872452)

        response = self.initPhoneBook.phone_number_exists(712872452)
        self.assertTrue(response)

    def test_show_all_contacts(self):
        '''
            Test to see if all contacts are shown
            Create some contacts before we search for them
        '''
        self.initPhoneBook.add_contact('Nancy', 712872452)
        self.initPhoneBook.add_contact('Mwangi', 712876245)

        response = self.initPhoneBook.show_all_contacts()
        self.assertEqual(response, [{
            'phone': 712872452,
            'id': 1,
            'name': 'Nancy'
        }, {
            'phone': 712876245,
            'id': 2,
            'name': 'Mwangi'
        }])

    def test_check_phone_number_is_int(self):
        '''Test if phone number is integer'''
        response = self.initPhoneBook.add_contact('Dalin', 'adfi')
        self.assertEqual(response, 'not a number')

    def test_phone_number_length_is_not_nine(self):
        response = self.initPhoneBook.add_contact('Dalin', 3456789)
        self.assertEqual(response, 'number short or long')

    def test_search_contact_name(self):
        '''Create some contacts before we search for them'''
        self.initPhoneBook.add_contact('Mike', 712872452)
        self.initPhoneBook.add_contact('Mwangi', 712876245)

        response = self.initPhoneBook.search_contact_name('Mwangi')
        self.assertTrue(response)

    def test_search_contact_phone(self):
        '''Create some contacts before we search for them'''
        self.initPhoneBook.add_contact('Mike', 712872452)
        self.initPhoneBook.add_contact('Mwangi', 712876245)

        response = self.initPhoneBook.search_contact_phone(712876245)
        self.assertEqual(response, [{
            'id': 2,
            'name': 'Mwangi',
            'phone': 712876245
        }])

    def test_contact_does_not_exist(self):
        '''Create some contacts before we search for them'''
        self.initPhoneBook.add_contact('Mike', 712872452)
        self.initPhoneBook.add_contact('Mwangi', 712876245)

        response = self.initPhoneBook.search_contact_name('Nancy')
        self.assertFalse(response)

    def test_edit_phone_number(self):
        '''
            Create a contact before we can edit it
            Edit function takes in the name of the person and the new phone number
        '''
        self.initPhoneBook.add_contact('Ann', 712876245)

        response = self.initPhoneBook.edit_phone_number('Ann', 765356999)
        self.assertEqual(response, [{
            'id': 1,
            'name': 'Ann',
            'phone': 765356999
        }])

    def test_delete_contact(self):
        '''
            Create a contact that we will delete
        '''
        self.initPhoneBook.add_contact('Ann', 712676245)

        response = self.initPhoneBook.delete_contact('Ann')
        self.assertEqual(response, 'contact deleted')
Esempio n. 20
0
from phone_book import PhoneBook
from file_handler import FileHandler
import os
from constants import literatls, data_filename, query_filename, output_filename

if __name__ == '__main__':
    path = os.getcwd()

    phone_book = PhoneBook(path + data_filename)
    queries = FileHandler.read_file(path + query_filename, literatls["TXT"],
                                    "r")
    for lastname in queries.readlines():
        FileHandler.write_file(
            path + output_filename,
            lastname.rsplit()[0],
            phone_book.search_on_last_name(lastname.rstrip()))
class PhoneBookTest(unittest.TestCase):
    def setUp(self) -> None:
        self.phone_book = PhoneBook()

    def tearDown(self) -> None:
        pass

    # Test Case Name
    def test_lookup_by_name(self):
        # Arrange
        self.phone_book.add('Bob', '12345')

        # Act
        number = self.phone_book.lookup('Bob')

        # Assert
        self.assertEqual('12345', number)

    def test_is_consistent(self):
        self.assertTrue(self.phone_book.is_consistent())

    def test_is_consistent_with_diffirent_entries(self):
        self.phone_book.add('Bob', '12345')
        self.phone_book.add('Anna', '012345')
        self.assertTrue(self.phone_book.is_consistent())

    def test_inconsistent_with_duplicate_entries(self):
        self.phone_book.add('Bob', '12345')
        self.phone_book.add('Anna', '12345')
        self.assertFalse(self.phone_book.is_consistent())

    # WIP: Work In Progress
    # @unittest.skip('WIP')
    def test_inconsistent_with_duplicate_prefix(self):
        self.phone_book.add('Bob', '12345')
        self.phone_book.add('Anna', '123')
        self.assertFalse(self.phone_book.is_consistent())

    def test_missing_name(self):
        with self.assertRaises(KeyError):
            self.phone_book.lookup('missing')