class AddressBookTest(unittest.TestCase): def setUp(self): self.ab = AddressBook() with open('address_book.json', 'w'): pass def test_file_non_exist(self): os.remove('address_book.json') self.ab.add('test', 'test', 'test', 'test') assert os.path.isfile('address_book.json') @parameterized.expand([ ('test', 'test', 'test', 'test', "{'test': {'address': 'test', 'phone': 'test', 'email': 'test'}}"), ('', '', '', '', "{'': {'address': '', 'phone': '', 'email': ''}}"), ('тест', 'тест', 'тест', 'тест', "{'тест': {'address': 'тест', 'phone': 'тест', 'email': 'тест'}}") ]) def test_add_write(self, name, address, phone, email, expected_result): self.ab.add(name, address, phone, email) with open('address_book.json', 'r') as f: address_book_file = json.load(f) self.assertEqual(str(address_book_file), expected_result) def tearDown(self): os.remove('address_book.json')
def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'], ['*****@*****.**'] ) address_book.add_person(person) self.assertIn(person, address_book)
def setUp(self): self.address_book = AddressBook() self.person1 = Person(first_name='p1fn', last_name='p1ln', emails=['p1em1@com', 'p1em2@com']) self.person2 = Person(first_name='p2fn', last_name='p2ln', emails=['p2em1@com', 'p2em2@com']) self.person3 = Person(first_name='p3fn', last_name='p3ln', emails=['p3em1@com', 'p3em2@com']) self.group1 = Group(name='Group1', persons=self.person1) self.group2 = Group(name='Group2', persons=[self.person3, self.person1])
def test_find_by_first_name(self): book = AddressBook() book.add_person(Person('John', 'Doe', Address('New York'), Email('*****@*****.**'), PhoneNumber('88005553535'))) entries = book.find_by_name('John') self.assertEqual(len(entries), 1) entry = entries[0] self.assertEqual(entry.first_name, 'John') self.assertEqual(entry.last_name, 'Doe') self.assertEqual(entry.street_addresses[0].address, 'New York') self.assertEqual(entry.emails[0].email, '*****@*****.**') self.assertEqual(entry.phone_numbers[0].number, '88005553535') self.assertEqual(entry.groups, [])
def test_get_address(self): address = Address(id=0, name="Toto", address="Tata", email="*****@*****.**", phone_numbers=["555 555-5555"]) book = AddressBook([address]) a = book.get_address(0) assert a.id == 0 assert a.name == "Toto" assert a.address == "Tata" assert a.email == "*****@*****.**" assert a.phone_numbers == ["555 555-5555"]
def read_address_book_from_file(): file_name = "address_book.txt" if os.path.exists(file_name): file_address_book = open(file_name, 'rb') is_file_empty = os.path.getsize(file_name) == 0 if is_file_empty: book = AddressBook() else: book = pickle.load(file_address_book) file_address_book.close() else: book = AddressBook() file_address_book = open(file_name, 'tw') file_address_book.close() return book
def test_find_person_by_email(self): address_book = AddressBook() john_person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'], ['*****@*****.**'] ) ivan_person = Person( 'Ivan', 'Sidorov', ['Russian Federation, Kemerovo region, Belovo, Kirova street 42, apt. 13'], ['+79834771122'], ['*****@*****.**'] ) address_book.add_person(john_person) address_book.add_person(ivan_person) found_person = address_book.find(email='*****@*****.**') self.assertEqual(found_person, ivan_person)
class ContactApp(ZeroApp): def __init__(self, i, o): super(ContactApp, self).__init__(i, o) self.menu_name = "Contacts" self.address_book = AddressBook() self.menu = None def on_start(self): self.address_book.load_from_file() self.menu = NumberedMenu(self.create_menu_content(), self.i, self.o, prepend_numbers=False) self.menu.activate() def create_menu_content(self): all_contacts = self.address_book.contacts return [[c.short_name(), lambda x=c: self.create_contact_page(x)] for c in all_contacts] def create_contact_page(self, contact): # type: (Contact) -> None contact_attrs = [getattr(contact, a) for a in contact.get_filled_attributes()] Listbox(i=self.i, o=self.o, contents=contact_attrs).activate()
def load_vcf(folder): # type: (str) -> None contact_card_files = find_contact_files(folder) contacts = VCardContactConverter.from_vcards(contact_card_files) address_book = AddressBook() for contact in contacts: address_book.add_contact(contact) address_book.save_to_file() logger.info("Saved to {}".format(address_book.get_save_file_path()))
def test_find_by_last_name(self): book = AddressBook() book.add_person(Person('John', 'Doe', Address('New York'), Email('*****@*****.**'), PhoneNumber('88005553535'))) book.add_person(Person('Jane', 'Doe', Address('Chicago'), Email('*****@*****.**'), PhoneNumber('2128506'))) entries = book.find_by_name('Doe') self.assertEqual(len(entries), 2) self.assertEqual(entries[0].last_name, 'Doe') self.assertEqual(entries[1].last_name, 'Doe') self.assertEqual(len(book.find_by_name('Ivanov')), 0)
def test_step24_save_to_csv(self): from address_book import AddressBook book_name = "book_name" book = AddressBook.create_from_csv("book_name", "addresses.csv") # remove old file so that we have a guarantee that a file is generated try: os.remove(book.name + ".csv") except: pass book.save_to_csv() with open("addresses.csv") as org, open(book.name + ".csv") as copy: are_equal = org.readlines() == copy.readlines() self.assertTrue(are_equal, msg="Loaded and saved files are not equal")
def sort_packages(unsorted_package_list): # Create variables to store our references sorted_package_list = [] first_truck_load = [] second_truck_load = [] third_truck_load = [] first_truck_addresses = [] second_truck_addresses = [] addresses = AddressBook.address_reference() # Find each item's destination ID to match the distance table # Complexity of O(n^2) for item in unsorted_package_list: for index in range(len(addresses)): if item.address == addresses[index][2]: item.address_id = int(addresses[index][0]) # Assign each package to the correct truck # Complexity of O(n) for package in unsorted_package_list: if 'Must' in package.notes or '09:00 AM' in package.deadline: first_truck_load.append(package) if package.address_id not in first_truck_addresses: first_truck_addresses.append(package.address_id) elif 'Can only' in package.notes or 'Delayed' in package.notes or '10:30 AM' in package.deadline: if package.address_id not in second_truck_addresses: second_truck_addresses.append(package.address_id) second_truck_load.append(package) elif 'Wrong' in package.notes: third_truck_load.append(package) for package in unsorted_package_list: if 'EOD' in package.deadline and 'N/A' in package.notes: if len(first_truck_load ) < 16 and package.address_id in first_truck_addresses: first_truck_load.append(package) elif len( second_truck_load ) < 16 and package.address_id in second_truck_addresses: second_truck_load.append(package) else: third_truck_load.append(package) sorted_package_list.insert(0, first_truck_load) sorted_package_list.insert(1, second_truck_load) sorted_package_list.insert(2, third_truck_load) return sorted_package_list
def test_find_person_by_full_name(self): address_book = AddressBook() ivan_popov_person = Person( 'Ivan', 'Popov', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'], ['*****@*****.**'] ) ivan_sidorov_person = Person( 'Ivan', 'Sidorov', ['Russian Federation, Kemerovo region, Belovo, Kirova street 42, apt. 13'], ['+79834771122'], ['*****@*****.**'] ) address_book.add_person(ivan_popov_person) address_book.add_person(ivan_sidorov_person) found_person = address_book.find(first_name='Ivan', last_name='Sidorov') self.assertEqual(found_person, ivan_sidorov_person)
def sort_by_distance(unsorted_list): distances = AddressBook.distance_reference() current_loc = 0 closest_package = None sorted_list = [] while len(unsorted_list) > 0: smallest_distance = math.inf for item in unsorted_list: distance = float(distances[current_loc][item.address_id]) if distance <= smallest_distance: smallest_distance = distance closest_package = item # Once found, place package in priority queue using distance # Update current location to package's destination # Remove package from unorganized load if closest_package is not None: sorted_list.append(closest_package) current_loc = closest_package.address_id unsorted_list.remove(closest_package) else: print('ERROR IN SORT_BY_DISTANCE') return sorted_list
def test_find_person_by_set_of_emails_prefix(self): address_book = AddressBook() john_person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'], ['*****@*****.**'] ) ivan_person = Person( 'Ivan', 'Sidorov', ['Russian Federation, Kemerovo region, Belovo, Kirova street 42, apt. 13'], ['+79834771122'], ['*****@*****.**'] ) address_book.add_person(john_person) address_book.add_person(ivan_person) found_person = address_book.find(emails=['*****@*****.**', '*****@*****.**']) self.assertIsNone(found_person) ivan_person.add_email('*****@*****.**') found_person = address_book.find(emails=['sn0', 'iv']) self.assertEqual(found_person, ivan_person)
#!/usr/bin/python from __future__ import print_function from flask import Flask, request from address_book import AddressBook from person import Person app = Flask('addressbook') book = AddressBook() book.load("newpeople.txt") @app.route('/') def index(): page = "This is my address book\n" for person in book: page += "{1},{0}: {2}\n".format(person.first(), person.last(), person.phone()) return page @app.route('/browse/<letter>'): def browse(letter): pass app.run()
from address_book import AddressBook def check_entry(entry, expected_name, expected_number, expected_email): if entry.name == expected_name and entry.phone_number == expected_number and entry.email == expected_email: return True else: return False # start of tests print("=" * 25 + "\nSTART OF TESTS" + "\n" + "=" * 25) errors = 0 book = AddressBook() print("Entries = 0") if len(book.entries) == 0: print("SUCCESS") else: print("FAIL") errors += 1 print("\nEntries = 1") book.add_entry('Jon Doe', '012.345.5789', '*****@*****.**') if len(book.entries) == 1: print("SUCCESS") else: print("FAIL") errors += 1
def __init__(self): self.config = None self.address_book_list = [] self.uid_dict = {} # load config file xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or \ os.path.expanduser("~/.config") config_file = os.environ.get("KHARD_CONFIG") or \ os.path.join(xdg_config_home, "khard", "khard.conf") if os.path.exists(config_file) == False: print("Config file %s not available" % config_file) sys.exit(2) self.config = ConfigObj(config_file, interpolation=False) # general settings if self.config.has_key("general") == False: print("Error in config file\nMissing main section \"[general]\".") sys.exit(2) # editor self.config['general']['editor'] = self.config['general'].get("editor") \ or os.environ.get("EDITOR") if self.config['general']['editor'] is None: print("Error in config file\n" \ "Set path to your preferred text editor in khard's config file or the $EDITOR shell variable\n" \ "Example for khard.conf: editor = vim") sys.exit(2) self.config['general']['editor'] = find_executable( os.path.expanduser(self.config['general']['editor'])) if self.config['general']['editor'] is None: print("Error in config file\nInvalid editor path or executable not found.") sys.exit(2) # merge editor self.config['general']['merge_editor'] = self.config['general'].get("merge_editor") \ or os.environ.get("MERGE_EDITOR") if self.config['general']['merge_editor'] is None: print("Error in config file\n" \ "Set path to your preferred text merge editor in khard's config file or the $MERGE_EDITOR shell variable\n" \ "Example for khard.conf: merge_editor = vimdiff") sys.exit(2) self.config['general']['merge_editor'] = find_executable( os.path.expanduser(self.config['general']['merge_editor'])) if self.config['general']['merge_editor'] is None: print("Error in config file\nInvalid merge editor path or executable not found.") sys.exit(2) # default action if self.config['general'].has_key("default_action") == False: print("Error in config file\nMissing default action parameter.") sys.exit(2) elif self.config['general']['default_action'] not in self.get_list_of_actions(): print("Error in config file\n" \ "Invalid value for default_action parameter\n" \ "Possible values: %s" % ', '.join(self.get_list_of_actions())) sys.exit(2) # contact table settings if self.config.has_key("contact table") == False: self.config['contact table'] = {} # sort contacts table by first or last name if self.config['contact table'].has_key("sort") == False: self.config['contact table']['sort'] = "first_name" elif self.config['contact table']['sort'] not in ["first_name", "last_name"]: print("Error in config file\n" \ "Invalid value for sort parameter\n" \ "Possible values: first_name, last_name") sys.exit(2) # reverse contact table if self.config['contact table'].has_key("reverse") == False: self.config['contact table']['reverse'] = False elif self.config['contact table']['reverse'] == "yes": self.config['contact table']['reverse'] = True elif self.config['contact table']['reverse'] == "no": self.config['contact table']['reverse'] = False else: print("Error in config file\n" \ "Invalid value for reverse parameter\n" \ "Possible values: yes, no") sys.exit(2) # group contact table by address book if self.config['contact table'].has_key("group_by_addressbook") == False: self.config['contact table']['group_by_addressbook'] = False elif self.config['contact table']['group_by_addressbook'] == "yes": self.config['contact table']['group_by_addressbook'] = True elif self.config['contact table']['group_by_addressbook'] == "no": self.config['contact table']['group_by_addressbook'] = False else: print("Error in config file\n" \ "Invalid value for group_by_addressbook parameter\n" \ "Possible values: yes, no") sys.exit(2) # nickname if self.config['contact table'].has_key("show_nicknames") == False: self.config['contact table']['show_nicknames'] = False elif self.config['contact table']['show_nicknames'] == "yes": self.config['contact table']['show_nicknames'] = True elif self.config['contact table']['show_nicknames'] == "no": self.config['contact table']['show_nicknames'] = False else: print("Error in config file\n" \ "Invalid value for show_nicknames parameter\n" \ "Possible values: yes, no") sys.exit(2) # show uids if self.config['contact table'].has_key("show_uids") == False: self.config['contact table']['show_uids'] = True elif self.config['contact table']['show_uids'] == "yes": self.config['contact table']['show_uids'] = True elif self.config['contact table']['show_uids'] == "no": self.config['contact table']['show_uids'] = False else: print("Error in config file\n" \ "Invalid value for show_uids parameter\n" \ "Possible values: yes, no") sys.exit(2) # load address books and contacts error_counter = 0 number_of_contacts = 0 if self.config.has_key("addressbooks") == False: print("Error in config file\nMissing main section \"[addressbooks]\".") sys.exit(2) if len(self.config['addressbooks'].keys()) == 0: print("Error in config file\nNo address book entries available.") sys.exit(2) for name in self.config['addressbooks'].keys(): # create address book object try: address_book = AddressBook(name, self.config['addressbooks'][name]['path']) except KeyError as e: print("Error in config file\nMissing path to the \"%s\" address book." % name) sys.exit(2) except IOError as e: print("Error in config file\n%s" % e) sys.exit(2) # load all vcard files for filename in glob.glob(os.path.join(address_book.get_path(), "*.vcf")): try: address_book.add_contact( CarddavObject.from_file(address_book, filename)) number_of_contacts += 1 except IOError as e: print("Error: Could not open file %s\n%s" % (filename, e)) error_counter += 1 except vobject.base.ParseError as e: print("Error: Could not parse file %s\n%s" % (filename, e)) error_counter += 1 # add address book to list self.address_book_list.append(address_book) # check if one or more contacts could not be parsed if error_counter > 0: print("\n%d of %d vcard files could not be parsed" % (error_counter, number_of_contacts)) sys.exit(2) # check uniqueness of vcard uids and create short uid dictionary # that can be disabled with the show_uids option in the config file, if desired if self.config['contact table']['show_uids']: # check, if multiple contacts have the same uid flat_contact_list = [] for address_book in self.address_book_list: for contact in address_book.get_contact_list(): uid = contact.get_uid() if bool(uid): matching_contact = self.uid_dict.get(uid) if matching_contact is None: self.uid_dict[uid] = contact else: print("The contact %s from address book %s" \ " and the contact %s from address book %s have the same uid %s" \ % (matching_contact.get_full_name(), matching_contact.get_address_book().get_name(), contact.get_full_name(), contact.get_address_book().get_name(), contact.get_uid()) ) sys.exit(2) # add to flat contact list flat_contact_list.append(contact) # now we can be sure, that all uid's are unique but we don't want to enter # the whole uid, if we choose a contact by the -u / --uid option # so clear previously filled uid_dict and recreate with the shortest possible uid, so # that it's still unique and easier to enter # with around 100 contacts that short id should not be longer then two or three characters self.uid_dict.clear() flat_contact_list.sort(key = lambda x: x.get_uid()) if len(flat_contact_list) == 1: current = flat_contact_list[0] self.uid_dict[current.get_uid()[:1]] = current elif len(flat_contact_list) > 1: # first list element current = flat_contact_list[0] next = flat_contact_list[1] same = helpers.compare_uids(current.get_uid(), next.get_uid()) self.uid_dict[current.get_uid()[:same+1]] = current # list elements 1 to len(flat_contact_list)-1 for index in range(1, len(flat_contact_list)-1): prev = flat_contact_list[index-1] current = flat_contact_list[index] next = flat_contact_list[index+1] same = max( helpers.compare_uids(prev.get_uid(), current.get_uid()), helpers.compare_uids(current.get_uid(), next.get_uid())) self.uid_dict[current.get_uid()[:same+1]] = current # last list element prev = flat_contact_list[-2] current = flat_contact_list[-1] same = helpers.compare_uids(prev.get_uid(), current.get_uid()) self.uid_dict[current.get_uid()[:same+1]] = current
city=input('City? '), state=input('State? '), zipcode=input('Zipcode? ')) def get_contact_from_user(): ''' Returns a Address class with the data entered from user ''' contact = Contact(name=get_name_from_user()) if input('Do you want to enter your home address (y/n): ').lower() == 'y': contact.set_home_address(get_address_from_user()) if input('Do you want to enter your work address (y/n): ').lower() == 'y': contact.set_work_address(get_address_from_user()) return contact ADDRESS_BOOK = AddressBook() while True: ACTION = input( 'What do you want to do (list/search/add/edit/delete/exit)? ').lower() if ACTION == 'add': ADDRESS_BOOK.add_contact(get_contact_from_user()) elif ACTION == 'edit': print('Editing') elif ACTION == 'list': ADDRESS_BOOK.display() elif ACTION == 'search': CONTACT = ADDRESS_BOOK.get_by_name(get_name_from_user()) if CONTACT: CONTACT.display() else:
def test_step13_address_book_type_error(self): from address_book import AddressBook book = AddressBook("Test") with self.assertRaises(TypeError, msg="Test dupy się nie powiódł ;("): book.add_address("dupa")
def test_step11_address_book_name(self): from address_book import AddressBook self.my_book = AddressBook("friends") self.assertEqual("friends", self.my_book.name)
def __init__(self): self.config = None self.address_book_list = [] self.uid_dict = {} # load config file xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or \ os.path.expanduser("~/.config") config_file = os.environ.get("KHARD_CONFIG") or \ os.path.join(xdg_config_home, "khard", "khard.conf") if os.path.exists(config_file) == False: print("Config file %s not available" % config_file) sys.exit(2) self.config = ConfigObj(config_file, interpolation=False) # general settings if self.config.has_key("general") == False: print("Error in config file\nMissing main section \"[general]\".") sys.exit(2) # editor self.config['general']['editor'] = self.config['general'].get("editor") \ or os.environ.get("EDITOR") if self.config['general']['editor'] is None: print("Error in config file\n" \ "Set path to your preferred text editor in khard's config file or the $EDITOR shell variable\n" \ "Example for khard.conf: editor = vim") sys.exit(2) self.config['general']['editor'] = find_executable( os.path.expanduser(self.config['general']['editor'])) if self.config['general']['editor'] is None: print("Error in config file\nInvalid editor path or executable not found.") sys.exit(2) # merge editor self.config['general']['merge_editor'] = self.config['general'].get("merge_editor") \ or os.environ.get("MERGE_EDITOR") if self.config['general']['merge_editor'] is None: print("Error in config file\n" \ "Set path to your preferred text merge editor in khard's config file or the $MERGE_EDITOR shell variable\n" \ "Example for khard.conf: merge_editor = vimdiff") sys.exit(2) self.config['general']['merge_editor'] = find_executable( os.path.expanduser(self.config['general']['merge_editor'])) if self.config['general']['merge_editor'] is None: print("Error in config file\nInvalid merge editor path or executable not found.") sys.exit(2) # default values for action and nickname settings if self.config['general'].has_key("default_action") == False: print("Error in config file\nMissing default action parameter.") sys.exit(2) elif self.config['general']['default_action'] not in self.get_list_of_actions(): print("Error in config file\n" \ "Non existing value for default action parameter\n" \ "Possible values are: %s" % ', '.join(self.get_list_of_actions())) sys.exit(2) if self.config['general'].has_key("show_nicknames") == False: self.config['general']['show_nicknames'] = False elif self.config['general']['show_nicknames'] == "yes": self.config['general']['show_nicknames'] = True elif self.config['general']['show_nicknames'] == "no": self.config['general']['show_nicknames'] = False else: print("Error in config file\nshow_nicknames parameter must be yes or no.") sys.exit(2) # load address books and contacts error_counter = 0 number_of_contacts = 0 if self.config.has_key("addressbooks") == False: print("Error in config file\nMissing main section \"[addressbooks]\".") sys.exit(2) if len(self.config['addressbooks'].keys()) == 0: print("Error in config file\nNo address book entries available.") sys.exit(2) for name in self.config['addressbooks'].keys(): # create address book object try: address_book = AddressBook(name, self.config['addressbooks'][name]['path']) except KeyError as e: print("Error in config file\nMissing path to the \"%s\" address book." % name) sys.exit(2) except IOError as e: print("Error in config file\n%s" % e) sys.exit(2) # load all vcard files for filename in glob.glob(os.path.join(address_book.get_path(), "*.vcf")): try: address_book.add_contact( CarddavObject.from_file(address_book, filename)) number_of_contacts += 1 except IOError as e: print("Error: Could not open file %s\n%s" % (filename, e)) error_counter += 1 except vobject.base.ParseError as e: print("Error: Could not parse file %s\n%s" % (filename, e)) error_counter += 1 # add address book to list self.address_book_list.append(address_book) # check if one or more contacts could not be parsed if error_counter > 0: print("\n%d of %d vcard files could not be parsed" % (error_counter, number_of_contacts)) sys.exit(2) # check, if multiple contacts have the same uid length_of_shortest_uid = 100 number_of_contacts_with_uid = 0 for address_book in self.address_book_list: for contact in address_book.get_contact_list(): uid = contact.get_uid() if uid != "": matching_contact = self.uid_dict.get(uid) if matching_contact is None: self.uid_dict[uid] = contact number_of_contacts_with_uid += 1 if len(uid) < length_of_shortest_uid: length_of_shortest_uid = len(uid) else: print("The contact %s from address book %s" \ " and the contact %s from address book %s have the same uid %s" \ % (matching_contact.get_full_name(), matching_contact.get_address_book().get_name(), contact.get_full_name(), contact.get_address_book().get_name(), contact.get_uid()) ) sys.exit(2) # now we can be sure, that all uid's are unique but we don't want to enter # the whole uid, if we choose a contact by the -u / --uid option # so clear previously filled uid_dict and recreate with the shortest possible uid, so # that it's still unique and easier to enter # with around 100 contacts that short id should not be longer then two or three characters length_of_uid = 1 while True: self.uid_dict.clear() for address_book in self.address_book_list: for contact in address_book.get_contact_list(): uid = contact.get_uid()[:length_of_uid] if uid != "": self.uid_dict[uid] = contact if len(self.uid_dict.keys()) != number_of_contacts_with_uid: length_of_uid += 1 else: break if length_of_uid == length_of_shortest_uid: # prevent infinit loop, # should not be necessary, cause we checked the uid uniqueness in the previous step # so it's just a precaution print("Could not create the dictionary of the short uid's") sys.exit(2)
def create_address_book(self): from address_book import AddressBook from address import Address from work_address import WorkAddress expected = AddressBook("expected") expected.add_address( Address("Jane Weaver", "Tugusirna", "Rowland", "1877/2")) expected.add_address( Address("Rebecca Cunningham", "Murzuq", "Heffernan", "2/3")) expected.add_address( Address("Steven Pierce", "Matsena", "Mariners Cove", "153/4")) expected.add_address( WorkAddress("Jerzy Mardaus", "Kraków", "Ślusarska", "9/1", "Codecool Poland Sp. z o.o.")) expected.add_address( Address("Betty Jenkins", "Tirmiz", "Hollow Ridge", "011/5")) return expected
def add_addresses_to_book(self): from address_book import AddressBook self.my_book = AddressBook("friends") self.my_book.add_address(self.get_address()) self.my_book.add_address(self.get_work_address())
def test_step23_create_from_csv_addresses(self): from address_book import AddressBook expected = self.create_address_book().addresses book = AddressBook.create_from_csv("book_name", "addresses.csv") actual = book.addresses self.assertListEqual(expected, actual)
def test_step22_create_from_csv_name(self): from address_book import AddressBook book_name = "book_name" book = AddressBook.create_from_csv("book_name", "addresses.csv") self.assertEqual("book_name", book.name)
def test_add_group(self): address_book = AddressBook() group = Group('Brozzz') address_book.add_group(group) self.assertIn(group, address_book)
def __init__(self): self.config = None self.address_book_list = [] # load config file xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or \ os.path.expanduser("~/.config") config_file = os.environ.get("KHARD_CONFIG") or \ os.path.join(xdg_config_home, "khard", "khard.conf") if os.path.exists(config_file) == False: print("Config file %s not available" % config_file) sys.exit(2) self.config = ConfigObj(config_file, interpolation=False) # general settings if self.config.has_key("general") == False: print( "Error in config file\nMissing main section \"[general]\"." ) sys.exit(2) # editor self.config['general']['editor'] = self.config['general'].get("editor") \ or os.environ.get("EDITOR") if self.config['general']['editor'] is None: print("Error in config file\n" \ "Set path to your preferred text editor in khard's config file or the $EDITOR shell variable\n" \ "Example for khard.conf: editor = vim") sys.exit(2) self.config['general']['editor'] = find_executable( os.path.expanduser(self.config['general']['editor'])) if self.config['general']['editor'] is None: print( "Error in config file\nInvalid editor path or executable not found." ) sys.exit(2) # merge editor self.config['general']['merge_editor'] = self.config['general'].get("merge_editor") \ or os.environ.get("MERGE_EDITOR") if self.config['general']['merge_editor'] is None: print("Error in config file\n" \ "Set path to your preferred text merge editor in khard's config file or the $MERGE_EDITOR shell variable\n" \ "Example for khard.conf: merge_editor = vimdiff") sys.exit(2) self.config['general']['merge_editor'] = find_executable( os.path.expanduser(self.config['general']['merge_editor'])) if self.config['general']['merge_editor'] is None: print( "Error in config file\nInvalid merge editor path or executable not found." ) sys.exit(2) # default values for action and nickname settings if self.config['general'].has_key("default_action") == False: print( "Error in config file\nMissing default action parameter.") sys.exit(2) elif self.config['general'][ 'default_action'] not in self.get_list_of_actions(): print("Error in config file\n" \ "Non existing value for default action parameter\n" \ "Possible values are: %s" % ', '.join(self.get_list_of_actions())) sys.exit(2) if self.config['general'].has_key("show_nicknames") == False: self.config['general']['show_nicknames'] = False elif self.config['general']['show_nicknames'] == "yes": self.config['general']['show_nicknames'] = True elif self.config['general']['show_nicknames'] == "no": self.config['general']['show_nicknames'] = False else: print( "Error in config file\nshow_nicknames parameter must be yes or no." ) sys.exit(2) # load address books error_counter = 0 if self.config.has_key("addressbooks") == False: print( "Error in config file\nMissing main section \"[addressbooks]\"." ) sys.exit(2) if len(self.config['addressbooks'].keys()) == 0: print( "Error in config file\nNo address book entries available.") sys.exit(2) for name in self.config['addressbooks'].keys(): # create address book object try: address_book = AddressBook( name, self.config['addressbooks'][name]['path']) except KeyError as e: print( "Error in config file\nMissing path to the \"%s\" address book." % name) sys.exit(2) except IOError as e: print("Error in config file\n%s" % e) sys.exit(2) # load all vcard files for filename in glob.glob( os.path.join(address_book.get_path(), "*.vcf")): try: address_book.add_contact( CarddavObject.from_file(address_book, filename)) except IOError as e: print("Error: Could not open file %s\n%s" % (filename, e)) error_counter += 1 except vobject.base.ParseError as e: print("Error: Could not parse file %s\n%s" % (filename, e)) error_counter += 1 # add address book to list self.address_book_list.append(address_book) # check if one or more contacts could not be parsed if error_counter > 0: if error_counter == 1: print("\n1 vcard file could not be parsed") elif error_counter > 1: print("\n%d vcard files could not be parsed" % error_counter) sys.exit(2)
class TestCheckpointExcersise(unittest.TestCase): # Addreses tests def test_step01_address_person(self): self.assertEqual("Jan Kowalski", self.get_address().person) def test_step02_get_full_address(self): self.assertEqual('Jan Kowalski, Kraków, ul. Daszyńskiego 15/31', self.get_address().get_full_address()) def test_step03_address_eq(self): from address import Address first = Address("Jan Kowalski", "Kraków", "ul. Daszyńskiego", "15/31") second = Address("Jan Kowalski", "Kraków", "ul. Daszyńskiego", "15/31") self.assertEqual(first, second) def test_step04_address_not_eq(self): from address import Address first = Address("Jan Kowalski", "Kraków", "ul. Daszyńskiego", "15/31") second = Address("Jan Kowalski", "Kraków", "ul. Daszyńskiego", "16/31") self.assertNotEqual(first, second) def test_step05_work_address_person(self): self.assertEqual("Adam Adamski", self.get_work_address().person) def test_step06_company(self): self.assertEqual("Mordor sp. z o.o.", self.get_work_address().company) def test_step07_get_full_work_address(self): self.assertEqual( 'Adam Adamski, Warszawa, ul.' + ' Domaniewska 6/66, Mordor sp. z o.o.', self.get_work_address().get_full_address()) def test_step08_work_address_eq(self): from work_address import WorkAddress first = WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66", "Mordor sp. z o.o.") second = WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66", "Mordor sp. z o.o.") self.assertEqual(first, second) def test_step09_work_address_not_eq(self): from work_address import WorkAddress first = WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66", "Mordor sp. z o.o.") second = WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66", "Hobbit sp. z o.o.") self.assertNotEqual(first, second) def test_step10_work_and_address_not_eq(self): from address import Address from work_address import WorkAddress first = Address("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66") second = WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66", "Hobbit sp. z o.o.") self.assertNotEqual(first, second) # AddressBook def test_step11_address_book_name(self): from address_book import AddressBook self.my_book = AddressBook("friends") self.assertEqual("friends", self.my_book.name) def test_step12_address_book_add_address(self): self.add_addresses_to_book() self.assertEqual(2, len(self.my_book.addresses)) def test_step13_address_book_type_error(self): from address_book import AddressBook book = AddressBook("Test") with self.assertRaises(TypeError, msg="Test dupy się nie powiódł ;("): book.add_address("dupa") def test_step14_address_book_find_returns_empty(self): self.add_addresses_to_book() self.assertListEqual([], self.my_book.find("XXX"), msg="Should return empty list") def test_step15_address_book_find_returns_one(self): self.add_addresses_to_book() expected = [self.my_book.addresses[0]] actual = self.my_book.find("Kraków") self.assertListEqual(expected, actual) def test_step16_address_book_find_returns_many(self): self.add_addresses_to_book() expected = self.my_book.addresses actual = self.my_book.find("ski") self.assertListEqual(expected, actual) def test_step17_address_book_find_case_insensitive(self): self.add_addresses_to_book() expected = [self.my_book.addresses[1]] actual = self.my_book.find("adam") self.assertListEqual(expected, actual, msg="Search should be case insensitive") def test_step18_sort(self): import address_book address_book.sorted = None # remove sorted function self.add_addresses_to_book() expected = [self.get_work_address(), self.get_address()] self.my_book.sort() self.assertListEqual(expected, self.my_book.addresses) def test_step19_sort_2(self): import address_book address_book.sorted = None # remove sorted function expected = self.create_address_book() actual = copy.deepcopy(expected) actual.sort() expected.sort() self.assertListEqual(expected.addresses, actual.addresses) def test_step20_builtin_sort(self): with open("address_book.py", "r") as f: content = f.read() self.assertEqual(content.find("addresses.sort"), -1, msg="Don't use built in sort function!") # 2nd part tests def test_step21_create_from_csv_length(self): from address_book import AddressBook book = AddressBook.create_from_csv("book_name", "addresses.csv") self.assertIsInstance(book, AddressBook) self.assertEqual(5, len(book.addresses)) def test_step22_create_from_csv_name(self): from address_book import AddressBook book_name = "book_name" book = AddressBook.create_from_csv("book_name", "addresses.csv") self.assertEqual("book_name", book.name) def test_step23_create_from_csv_addresses(self): from address_book import AddressBook expected = self.create_address_book().addresses book = AddressBook.create_from_csv("book_name", "addresses.csv") actual = book.addresses self.assertListEqual(expected, actual) def test_step24_save_to_csv(self): from address_book import AddressBook book_name = "book_name" book = AddressBook.create_from_csv("book_name", "addresses.csv") # remove old file so that we have a guarantee that a file is generated try: os.remove(book.name + ".csv") except: pass book.save_to_csv() with open("addresses.csv") as org, open(book.name + ".csv") as copy: are_equal = org.readlines() == copy.readlines() self.assertTrue(are_equal, msg="Loaded and saved files are not equal") # helper methods def get_address(self): from address import Address return Address("Jan Kowalski", "Kraków", "ul. Daszyńskiego", "15/31") def get_work_address(self): from work_address import WorkAddress return WorkAddress("Adam Adamski", "Warszawa", "ul. Domaniewska", "6/66", "Mordor sp. z o.o.") def add_addresses_to_book(self): from address_book import AddressBook self.my_book = AddressBook("friends") self.my_book.add_address(self.get_address()) self.my_book.add_address(self.get_work_address()) def create_address_book(self): from address_book import AddressBook from address import Address from work_address import WorkAddress expected = AddressBook("expected") expected.add_address( Address("Jane Weaver", "Tugusirna", "Rowland", "1877/2")) expected.add_address( Address("Rebecca Cunningham", "Murzuq", "Heffernan", "2/3")) expected.add_address( Address("Steven Pierce", "Matsena", "Mariners Cove", "153/4")) expected.add_address( WorkAddress("Jerzy Mardaus", "Kraków", "Ślusarska", "9/1", "Codecool Poland Sp. z o.o.")) expected.add_address( Address("Betty Jenkins", "Tirmiz", "Hollow Ridge", "011/5")) return expected
def __init__(self): self.config = None self.address_book_list = [] # load config file xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or \ os.path.expanduser("~/.config") config_file = os.environ.get("KHARD_CONFIG") or \ os.path.join(xdg_config_home, "khard", "khard.conf") if os.path.exists(config_file) == False: print("Config file %s not available" % config_file) sys.exit(2) self.config = ConfigObj(config_file, interpolation=False) # general settings if self.config.has_key("general") == False: print("Error in config file\nMissing main section \"[general]\".") sys.exit(2) # editor self.config['general']['editor'] = self.config['general'].get("editor") \ or os.environ.get("EDITOR") if self.config['general']['editor'] is None: print("Error in config file\n" \ "Set path to your preferred text editor in khard's config file or the $EDITOR shell variable\n" \ "Example for khard.conf: editor = vim") sys.exit(2) self.config['general']['editor'] = find_executable( os.path.expanduser(self.config['general']['editor'])) if self.config['general']['editor'] is None: print("Error in config file\nInvalid editor path or executable not found.") sys.exit(2) # merge editor self.config['general']['merge_editor'] = self.config['general'].get("merge_editor") \ or os.environ.get("MERGE_EDITOR") if self.config['general']['merge_editor'] is None: print("Error in config file\n" \ "Set path to your preferred text merge editor in khard's config file or the $MERGE_EDITOR shell variable\n" \ "Example for khard.conf: merge_editor = vimdiff") sys.exit(2) self.config['general']['merge_editor'] = find_executable( os.path.expanduser(self.config['general']['merge_editor'])) if self.config['general']['merge_editor'] is None: print("Error in config file\nInvalid merge editor path or executable not found.") sys.exit(2) # default values for action and nickname settings if self.config['general'].has_key("default_action") == False: print("Error in config file\nMissing default action parameter.") sys.exit(2) elif self.config['general']['default_action'] not in self.get_list_of_actions(): print("Error in config file\n" \ "Non existing value for default action parameter\n" \ "Possible values are: %s" % ', '.join(self.get_list_of_actions())) sys.exit(2) if self.config['general'].has_key("show_nicknames") == False: self.config['general']['show_nicknames'] = False elif self.config['general']['show_nicknames'] == "yes": self.config['general']['show_nicknames'] = True elif self.config['general']['show_nicknames'] == "no": self.config['general']['show_nicknames'] = False else: print("Error in config file\nshow_nicknames parameter must be yes or no.") sys.exit(2) # load address books error_counter = 0 if self.config.has_key("addressbooks") == False: print("Error in config file\nMissing main section \"[addressbooks]\".") sys.exit(2) if len(self.config['addressbooks'].keys()) == 0: print("Error in config file\nNo address book entries available.") sys.exit(2) for name in self.config['addressbooks'].keys(): # create address book object try: address_book = AddressBook(name, self.config['addressbooks'][name]['path']) except KeyError as e: print("Error in config file\nMissing path to the \"%s\" address book." % name) sys.exit(2) except IOError as e: print("Error in config file\n%s" % e) sys.exit(2) # load all vcard files for filename in glob.glob(os.path.join(address_book.get_path(), "*.vcf")): try: address_book.add_contact( CarddavObject.from_file(address_book, filename)) except IOError as e: print("Error: Could not open file %s\n%s" % (filename, e)) error_counter += 1 except vobject.base.ParseError as e: print("Error: Could not parse file %s\n%s" % (filename, e)) error_counter += 1 # add address book to list self.address_book_list.append(address_book) # check if one or more contacts could not be parsed if error_counter > 0: if error_counter == 1: print("\n1 vcard file could not be parsed") elif error_counter > 1: print("\n%d vcard files could not be parsed" % error_counter) sys.exit(2)
def choose_option(self, user_input): ab = AddressBook() if user_input == 1: ab.show() elif user_input == 2: name = input('input name: ') address = input('input address: ') phone = input('input phone: ') email = input('input email: ') ab.add(name, address, phone, email) elif user_input == 3: ab.show() name = input('input name for change: ') field = input('input field for change: ') new_info = input('input new info: ') ab.change(name, field, new_info) ab.show() elif user_input == 4: name = input('input name for delete: ') ab.delete(name) elif user_input == 5: name = input('input name: ') ab.search(name) elif user_input == 0: print('good bye!') else: return
from address_book import AddressBook from commands import list, add, delete, search, exit, remind from errors import NotExistError, AlreadyExistError, ValidationError available_commands = { 'list': list, 'add': add, 'delete': delete, 'search': search, 'exit': exit } book = AddressBook() print "Hello, this is your address book!" remind(book) print "Enter the one of commands below" while True: input = raw_input("{}\n".format(', '.join(available_commands.keys()))) command = input.lower() if command not in available_commands.keys(): print "I don\'t understand your command. Sorry!\n" else: try: available_commands[command](book) except (NotExistError, AlreadyExistError, ValidationError) as e: print(e)
def test_step21_create_from_csv_length(self): from address_book import AddressBook book = AddressBook.create_from_csv("book_name", "addresses.csv") self.assertIsInstance(book, AddressBook) self.assertEqual(5, len(book.addresses))