Ejemplo n.º 1
0
 def setUp(self):
     '''
     Método executado antes de cada Test Case.
     O atributo phonebook ficará disponível 
     para todos os Test Cases.
     '''
     self.phonebook = Phonebook()
Ejemplo n.º 2
0
def add_new_record(phonebook: pb.Phonebook, new_record: rec.Record) -> pb.Phonebook or None:
    """
    Добавление новой записи в данную телефонную книгу. Функция работает в бесконечном цикле до тех пор, пока не
    выявится ошибка, либо не завершится успешно. В цикле происходит проверка на совпадение с существующей записью в
    данной телефонной книге

    :param phonebook: данная телефонная книга, в которую добавляется новая запись (pb.Phonebook)
    :param new_record: новая запись (rec.Record)
    :return: измененная телефонная книга (pb.Phonebook), либо, в случае какой-либо ошибки, None
    """
    while True:
        if pb.similar_record_in_phonebook(phonebook, new_record):
            print(ms.MENU_TO_SOLVE_SIMILAR_RECORD)
            choice, err = get_unambiguous_choice(2)
            if err:
                return

            if choice == 0:
                phonebook.delete_records(lambda x: x.firstname == new_record.firstname and
                                                   x.lastname == new_record.lastname)

            if choice == 1:
                new_record = edit_record(phonebook, new_record, edit_when_add=True)
                if new_record is None:
                    return
        else:
            phonebook.append(new_record)
            return phonebook
Ejemplo n.º 3
0
class PhonebookTest(unittest.TestCase):
    def setUp(self):
        self.phonebook = Phonebook()

    def test_lookup_entry(self):
        self.phonebook.add("Bob", "12345")
        self.assertEqual("12345", self.phonebook.lookup("Bob"))
Ejemplo n.º 4
0
 def __init__(self, fc,
              whitelist_pbids, blacklist_pbids, blocklist_pbid, blockname_prefix='',
              min_score=6, min_comments=3,
              block_abroad=False, block_illegal_prefix=True,
              logger=None):
     """ Provide a whitelist phonebook (normally first index 0) and where blocked numbers should go into. """
     self.whitelist_pbids = whitelist_pbids
     self.blacklist_pbids = blacklist_pbids
     self.blocklist_pbid = blocklist_pbid
     self.blockname_prefix = blockname_prefix
     self.min_score = int(min_score)
     self.min_comments = int(min_comments)
     # self.block_anon = block_anon  # How should that work? Impossible?
     self.block_abroad = block_abroad
     self.block_illegal_prefix = block_illegal_prefix
     self.logger = logger
     print("Retrieving data from Fritz!Box..")
     self.pb = Phonebook(fc=fc)
     fritz_model = self.pb.fc.modelname
     fritz_os = self.pb.fc.system_version
     self.cp = CallPrefix(fc=self.pb.fc)
     self.pb.ensure_pb_ids_valid(self.whitelist_pbids + self.blacklist_pbids + [self.blocklist_pbid])
     self.reload_phonebooks()
     if self.cp.country_code != '0049':
         log.warning('This script was developed for usage in Germany - please contact the author!')
     print(f'Call blocker initialized.. '
           f'model:{fritz_model} ({fritz_os}) '
           f'country:{self.cp.country_code_name} ({self.cp.country_code}) '
           f'area:{self.cp.area_code_name} ({self.cp.area_code}) '
           f'whitelisted:{len(self.whitelist)} blacklisted:{len(self.blacklist)} prefixes:{len(self.cp.prefix_dict)}')
     if TELEGRAM_BOT_URL:
         requests.get(TELEGRAM_BOT_URL + quote("CallBlocker: initialized"))
Ejemplo n.º 5
0
class PhonebookTest(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()

    def test_lookup_entry(self):
        self.phonebook.add("Bob", "12345")
        self.assertEqual("12345", self.phonebook.lookup("Bob"))
Ejemplo n.º 6
0
class PhonebookViewTestCase(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()
        self.contact = self.phonebook.add_contact("Redlion", "0715846586")

    def test_view_contact(self):
        resp = self.phonebook.view_contact("Redlion")
        self.assertEqual(resp, "0715846586")
Ejemplo n.º 7
0
 def __init__(self, port = 8080):
 
     self.testargs = " ".join(sys.argv[1:])
     self.publickey, self.privatekey = rsa.newkeys(512)
     self.host = ''   # <-- works on all available network interfaces
     self.port = port
     self.chain = blockchain.Blockchain()
     self.phonebook = Phonebook()
     self.uid = uuid.uuid1()
Ejemplo n.º 8
0
    def test_mock_up_thing(self):
        thing = Phonebook()

        #<MagicMock id='140115817358032'>
        thing.method = MagicMock(return_value=3)

        # It is going to return 3
        thing.method(3, 4, 5, key='value')
        thing.method.assert_called_with(3, 4, 5, key='value')
Ejemplo n.º 9
0
def main():
    phonebook = Phonebook()

    person1 = Contact("Maija", "Mehiläinen", "29392949", 1994)
    person2 = Contact("Matti", "Meikäläinen", "03846737", 1995)

    phonebook.AddContact(person1)
    phonebook.AddContact(person2)

    phonebook.PrintContacts()
Ejemplo n.º 10
0
def test_phonebook_gives_access_to_names_and_numbers():
    phonebook = Phonebook()
    phonebook.add('Alice', '12345')
    phonebook.add("Bob", "123")
    assert set(phonebook.names()) == {'Alice', 'Bob'}
    assert '12345' in phonebook.numbers()
    assert '123' in phonebook.numbers()
    def run(self):

        # This block was moved from server file to try and make it handled here instead
        phonebook = Phonebook()  # called from the phonebook.py
        filename = "AddressBook.txt"
        while True:
            try:
                file = open(filename, "r")  # opens in read only
                contents = file.readlines()
                for line in contents:
                    information = line.split(
                        " "
                    )  # This splits each line of the text file by spaces
                    phonebook.add(information[0], information[1])
                break
            except ReferenceError:
                print("File not found.")
                filename = input(
                    "Please enter the name of the phonebook to be loaded: ")
        # End of test block

        # create string of phonebook to send to client on connection
        start_book = phonebook.__str__()
        encrypt(start_book)
        self.client.send(bytes(encrypt(start_book.encode()))
                         )  # encrypts start_book for delivery to client

        self.client.send(bytes("Welcome to the phone book application!", ))
        while True:
            message = decode(self.client.recv(BUFSIZE), )
            decrypt(message)  # decrypts incoming message
            if not message:
                print("Client disconnected")
                self.client.close()
                break
            else:
                request = message.split()
                command = request[0]
                if command == "FIND":
                    number = self.phonebook.get(request[1])
                    if not number:
                        reply = "Number not found."
                    else:
                        reply = "The number is " + number
                else:
                    self.phonebook.add(request[1], request[2])

                    # write it to the file:
                    filename = "AddressBook.txt"
                    phonebook_file = open(filename, "a")  # opens in read only
                    phonebook_file.write(request[1] + " " + request[2] + "\n")
                    phonebook_file.close()

                    reply = "Name and number added to phone book and file.\nPress Update to update the table."
                self.client.send(bytes(reply, ))
Ejemplo n.º 12
0
    def test_less_than_2_pounds_stop_publishing(self):
        mock_phys = Mock(PhysicalDimensions())
        """
		`mock_phys.weight = 1` if commented out
		yields this error from unittest: TypeError: '<' not supported between instances of 'Mock' and 'int'
		if real Phys defaults to weight=0, why not the mock?
		why can we set the field only after instantiation?
		"""
        mock_phys.weight = 1
        pb = Phonebook(dimensions=mock_phys)
        self.assertEqual('stop publishing', pb.keep_publishing())
Ejemplo n.º 13
0
class PhonebookEditTestCase(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()
        self.contact = self.phonebook.add_contact("Redlion", "0715846586")

    def test_edit_contact_number(self):
        resp = self.phonebook.edit_contact("Redlion", "0754681222")
        self.assertNotEqual(resp, "0715846586")

    def test_edit_contact_name(self):
        resp = self.phonebook.edit_contact("Redlion", "Isaac")
        self.assertEqual(resp, None)
Ejemplo n.º 14
0
def main():
    import sys
    if len(sys.argv) == 1:
        print('Usage: app.py -list \n -find <name> \n -delete <name>')
        sys.exit(1)
    else:
        arguments = sys.argv[1:]
        print("Args: ", arguments)
        contacts = create_from_file()
        phonebook = Phonebook(contacts)
    if (arguments[0] == '-list'):
        phonebook.list()
    elif (arguments[0] == '-find'):
        phonebook.search_name(arguments[1])
    elif (arguments[0] == '-remove'):
        phonebook.remove_contact(arguments[1])
    else:
        print('Usage: app.py -list \n -find <name> \n -delete <name>')
        sys.exit(1)

    #no-args
    # contacts = create_from_file()
    # phonebook = Phonebook(contacts)
    # phonebook.list()
    # phonebook.search_name('jessica')
    # phonebook.remove_contact('jessica')
    # phonebook.search_name('Banjo')

    print('Done.')
Ejemplo n.º 15
0
class PhonebookDeleteTestCase(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()
        self.contact = self.phonebook.add_contact("Redlion", "0715846586")

    def test_delete_contact(self):
        resp = self.phonebook.delete_contact("Redlion")
        self.assertEqual(resp["message"], "Contact successfully deleted!!")

    def test_view_contact_deleted(self):
        self.phonebook.delete_contact("Redlion")
        resp = self.phonebook.view_contact("Redlion")
        self.assertEqual(resp["message"], "The contact is missing!!")
Ejemplo n.º 16
0
def phonebook(request):
	phonebook = Phonebook()
	# check documentation for newer cleanup syntax
	def cleanup_phonebook():
		phonebook.clear()
	request.addfinalizer(cleanup_phonebook)
	return phonebook
Ejemplo n.º 17
0
def main():
    main_frame = Tk()
    main_frame.title("Phonebook")
    main_frame.geometry("750x450+50+50")
    main_frame.resizable(False, False)
    app = Phonebook(main_frame)
    main_frame.mainloop()
Ejemplo n.º 18
0
def get_persons_birth_within_month(phonebook: pb.Phonebook) -> rec.SetRecords:
    """
    Вывод таблицы с записями, у которых день рождения в ближайший месяц.

    :param phonebook: телефонная книга, в которой происходит поиск нужных записей (pb.Phonebook)
    :return: набор найденых записей (rec.SetRecords)
    """
    records = phonebook.get_records(comparator=None)
    result = []

    today = date.today()
    after_month = today + timedelta(days=30)

    for record in records:
        if record.birthday_date:

            person_date = date(day=record.birthday_date.day, month=record.birthday_date.month, year=today.year)

            if today.year != after_month.year:
                if person_date.month == 1:
                    person_date = date(day=record.birthday_date.day, month=record.birthday_date.month,
                                       year=after_month.year)

            if today <= person_date <= after_month:
                result.append(record)

    return rec.SetRecords(result)
Ejemplo n.º 19
0
def phonebook(request):
    phonebook = Phonebook()

    def cleanup_phonebook():
        phonebook.clear()

    request.addfinalizer(cleanup_phonebook)
    return phonebook
Ejemplo n.º 20
0
 def setUp(self):
     self.contacts = dict()
     self.info0 = dict(name='ZuZu',
                       number='123',
                       address='1 Main',
                       note='hi')
     self.info1 = dict(name='Daisy',
                       number='456',
                       address='1 Dog',
                       note='bye')
     self.test_contact0 = Contact(**self.info0)
     self.test_contact1 = Contact(**self.info1)
     self.contacts[self.test_contact0.get_variable(
         'name')] = self.test_contact0
     self.contacts[self.test_contact1.get_variable(
         'name')] = self.test_contact1
     self.test_phonebook = Phonebook(self.contacts)
Ejemplo n.º 21
0
def phonebook(tmpdir):
    "Provide an empty phone book"
    phonebook = Phonebook()

    def cleanup_phonebook():
        phonebook.clear()

    request.addfinalizer(cleanup_phonebook)
    return phonebook
Ejemplo n.º 22
0
def save_phonebook(phonebook: pb.Phonebook, path2file: str) -> None:
    """
    Сохранение всех изменений в файл.

    :param phonebook: исходная телефонная книга
    :param path2file: путь к файлу, в который сохранить изменения
    :return: None
    """
    with open(path2file, "w") as file:
        dump(phonebook.conv2json_format(), file, indent=4)
Ejemplo n.º 23
0
 def __init__(self):
     try:
         HOME_DIR = os.path.join(os.environ['HOME'], ".o2texter")
     except KeyError:
         HOME_DIR = os.path.join(os.environ['HOMEPATH'], ".o2texter")
     try:
         os.mkdir(HOME_DIR)
     except OSError:
         pass
     try:
         self.tree = gtk.glade.XML("texter.glade")
     except:
         #find glade dir
         self.tree = gtk.glade.XML("/usr/share/02texter/texter.glade")
     self.tree.signal_autoconnect(self)
     
     self.phonebook = Phonebook(HOME_DIR + os.sep + "phonebook", self.tree)
     self.form = WebForm(HOME_DIR)
     self.tree.signal_autoconnect(self.phonebook)
     #self.tree.get_widget("texter").show()
     while gtk.events_pending():
         gtk.main_iteration(True)
     #create column for phonebook
     col = gtk.TreeViewColumn("Name")
     cell = gtk.CellRendererText()
     col.pack_start(cell, True)
     col.set_attributes(cell, text=0)
     self.tree.get_widget("phone_treeview").append_column(col)
     col = gtk.TreeViewColumn("Phone")
     cell = gtk.CellRendererText()
     col.pack_start(cell, True)
     col.set_attributes(cell, text=1)
     self.tree.get_widget("phone_treeview").append_column(col)
     
     self.free_texts = 0
     self.paid_texts = 0
     self.message_count = 0
     self.set_limits(self.tree.get_widget("free").get_active())
     
     #get username and password
     try:
         f = open(self.HOME_DIR + os.sep + "username", "r")
         self.username, self.password = cPickle.load(f)
         f.close()
         self.tree.get_widget("texter").show()
         self.tree.get_widget("main_info").set_text("Logging in...")
         if self.form.login(self.username, self.password):
             self.tree.get_widget("main_info").set_text("Retrieving account details...")
             self.form.get_compose_form(self)
             self.tree.get_widget("main_info").set_text("")
         else:
             self.tree.get_widget("main_info").set_text(self.form.error)
             #XXX set a retry timout
     except IOError:
         self.tree.get_widget("login_window").show()
Ejemplo n.º 24
0
def delete_record(phonebook: pb.Phonebook, set_records: rec.SetRecords) -> pb.Phonebook or None:
    """
    Удаление данного набора записей из данной телефонной книги. Перед удалением запрос на согласие действия. Если в
    наборе несколько записей, то предоставляется выбор записей, которые нужно удалить.

    :param phonebook: исходная телефонная книга (pb.Phonebook)
    :param set_records: набор записей для удаления (rec.SetRecords)
    :return: измененная телефонная книга (pb.Phonebook), если функция сработала без ошибок, иначе None
    """
    print(set_records)

    if set_records.length == 1:
        print(ms.MENU_BEFORE_DELETE_RECORD)

        choice_y_n, err = get_unambiguous_choice(1)
        if err:
            return

        if choice_y_n == 0:
            record = set_records[0]
            phonebook.delete_records(lambda x: x.firstname == record.firstname and x.lastname == record.lastname)

    else:

        print(ms.CHOOSE_INDEXES_BEFORE_DELETE_RECORD)

        indexes, err = get_indexes(set_records.length)
        if err:
            return

        print(ms.MENU_BEFORE_DELETE_RECORD)

        choice_y_n, err = get_unambiguous_choice(1)
        if err:
            return

        if choice_y_n == 0:
            for index in indexes:
                phonebook.delete_records(lambda x: x.firstname == set_records[index].firstname and
                                                   x.lastname == set_records[index].lastname)

    return phonebook
Ejemplo n.º 25
0
class TestPhonebook(unittest.TestCase):
    def setUp(self):
        self.contacts = dict()
        self.info0 = dict(name='ZuZu',
                          number='123',
                          address='1 Main',
                          note='hi')
        self.info1 = dict(name='Daisy',
                          number='456',
                          address='1 Dog',
                          note='bye')
        self.test_contact0 = Contact(**self.info0)
        self.test_contact1 = Contact(**self.info1)
        self.contacts[self.test_contact0.get_variable(
            'name')] = self.test_contact0
        self.contacts[self.test_contact1.get_variable(
            'name')] = self.test_contact1
        self.test_phonebook = Phonebook(self.contacts)

    def test_newContact(self):
        self.assertEqual(True, type(self.test_contact0) is Contact)

    def test_newContactKwargs(self):
        self.assertEqual('ZuZu', self.test_contact0.get_variable('name'))
        self.assertEqual('123', self.test_contact0.get_variable('number'))
        self.assertEqual('bye', self.test_contact1.get_variable('note'))
        self.assertEqual('1 Dog', self.test_contact1.get_variable('address'))

    def test_newPhonebook(self):
        self.assertEqual(True, type(self.test_phonebook) is Phonebook)

    def test_phonebookCanSearch(self):
        self.assertEqual(1, self.test_phonebook.search_name('ZuZu'))
        self.assertEqual(1, self.test_phonebook.search_name('zuzu'))
        self.assertEqual(0, self.test_phonebook.search_name('Joe'))

    def test_phonebookCanRemove(self):
        len0 = len(self.contacts)
        len1 = len(self.test_phonebook.remove_contact('ZuZu'))
        self.assertEqual(len0, len1 + 1)
        self.assertEqual(0, self.test_phonebook.search_name('ZuZu'))
Ejemplo n.º 26
0
class PhonebookTest(unittest.TestCase):

  def setUp(self):
    self.phonebook = Phonebook()


  def test_lookup_entry_by_name(self):
    self.phonebook.add('Bob', '12345')
    self.assertEqual('12345', self.phonebook.lookup('Bob'))


  # def test_missing_entry_raises_KeyError(self):
  #   phonebook = Phonebook()
  #   with self.assertRaises(KeyError):
  #     phonebook.lookup('jams')
  def test_missing_entry_return_none(self):
    self.assertEqual(None, self.phonebook.lookup('Bobjam'))


  def test_empty_phonebook_is_consistent(self):
    self.assertTrue(self.phonebook.is_consistent())
Ejemplo n.º 27
0
class PhonebookTest(unittest.TestCase):
    def setUp(self):
        self.phonebook = Phonebook()

    def test_create_phonebook(self):
        pass

    def test_lookup_entry_by_name(self):
        self.phonebook.add("Bob", "12345")
        self.assertEqual("12345", self.phonebook.lookup("Bob"))

    def test_missing_entry_raises_keyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup("missing")

    def test_empty_phonebook_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_adds_names_and_numbers(self):
        self.phonebook.add("Sue", "12345")
        self.assertIn("Sue", self.phonebook.get_names())
        self.assertIn("12345", self.phonebook.get_numbers())
Ejemplo n.º 28
0
class PhonebookTest(unittest.TestCase):
    def setUp(self):
        self.phonebook = Phonebook()

    def test_lookup_entry_by_name(self):
        self.phonebook.add("alice", "12345")
        self.assertEqual("12345", self.phonebook.lookup("alice"))

    def test_miss_entry_raises_KeyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup('missing')

    def test_less_than_2_pounds_stop_publishing(self):
        mock_phys = Mock(PhysicalDimensions())
        """
		`mock_phys.weight = 1` if commented out
		yields this error from unittest: TypeError: '<' not supported between instances of 'Mock' and 'int'
		if real Phys defaults to weight=0, why not the mock?
		why can we set the field only after instantiation?
		"""
        mock_phys.weight = 1
        pb = Phonebook(dimensions=mock_phys)
        self.assertEqual('stop publishing', pb.keep_publishing())
Ejemplo n.º 29
0
class PhonebookTest(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()
        
    def test_lookup_entry_by_name(self):
        phonebook = Phonebook()
        phonebook.add('Bob', '12345')
        self.assertEqual("12345", phonebook.lookup("Bob"))

    def test_missing_entry_raises_KeyError(self):
        phonebook = Phonebook()
        with self.assertRaises(KeyError):
            phonebook.lookup("missing")

    def test_phonebook_with_normal_entries_is_consistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "012345")
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_with_duplicate_entries_is_consistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "12345")
        self.assertTrue(self.phonebook.is_consistent())
Ejemplo n.º 30
0
def phonebook(tmpdir) -> Phonebook:
    """
    Provides an empty Phonebook object
    """
    # return Phonebook()

    # Use 'yield' and not 'return' so that we can run clear at the end of every test case
    # phonebook = Phonebook()
    # yield phonebook
    # phonebook.clear()

    # With the tmpdir built-in pytest fixture, you can revert to the return
    # You can run 'pytest --fixtures' to get a list of the pytest fixtures
    # and their docstrings
    return Phonebook(tmpdir)
Ejemplo n.º 31
0
 def test_list_records(self):
     """Check for right output when record created and listed"""
     capturedOutput = io.StringIO()
     sys.stdout = capturedOutput
     phonebook = Phonebook()
     phonebook.add_record("John Mayer", 12345)
     phonebook.list_records()
     sys.stdout = sys.__stdout__
     self.assertEqual(
         capturedOutput.getvalue(),
         "\nPhonebook has following entries:\n'John Mayer' => 12345\n")
Ejemplo n.º 32
0
class PhonebookTest(unittest.TestCase):
    def setUp(self):
        self.phonebook = Phonebook()

    def test_lookup_entry_by_name(self):
        self.phonebook.add("Bob", "12345")
        self.assertEquals("12345", self.phonebook.lookup("Bob"))

    def test_missing_entry_raises_KeyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup("missing")

    def test_empty_phonebook_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())
Ejemplo n.º 33
0
def test_phonebook_gives_access_to_names_and_numbers(phonebook):
    phonebook = Phonebook()
    phonebook.add("Alice", "12345")
    assert "Alice" in phonebook.names()
    assert "12345" in phonebook.numbers()
class PhonebookTest(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()

    def test_lookup_entry_by_name(self):
        self.phonebook.add('Bob', '12345')
        self.assertEqual('12345', self.phonebook.lookup_entry_by_name('Bob'))

    def test_missing_entry_raises_KeyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup_entry_by_name('missing')

    def test_empty_phonebook_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_with_normal_entries_is_consistent(self):
        self.phonebook.add('Bob', '12345')
        self.phonebook.add('Mary', '012345')
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_with_duplicate_entries_is_inconsistent(self):
        self.phonebook.add('Bob', '12345')
        self.phonebook.add('Mary', '12345')
        self.assertFalse(self.phonebook.is_consistent())

    def test_phonebook_with_numbers_that_prefix_one_another_is_inconsistent(self):
        self.phonebook.add('Bob', '12345')
        self.phonebook.add('Mary', '123')
        self.assertFalse(self.phonebook.is_consistent())

    def test_phonebook_adds_names_and_numbers(self):
        self.phonebook.add('Sue', '12345')
        self.assertIn('Sue', self.phonebook.get_names())
        self.assertIn('12345', self.phonebook.get_numbers())
Ejemplo n.º 35
0
def test_add_and_lookup_entry():
    pytest.skip("WIP")
    phonebook = Phonebook()
    phonebook.add("Bob", "123")
    assert "123" == phonebook.lookup("Bob")
Ejemplo n.º 36
0
def test_missing_entry_raises_KeyError():
    phonebook = Phonebook()
    with pytest.raises(KeyError):
        phonebook.lookup("missing")
Ejemplo n.º 37
0
def test_phonebook_gives_access_to_names_and_numbers():
    phonebook = Phonebook()
    phonebook.add("Alice", "12345")
    phonebook.add("Bob", "123")
    assert set(phonebook.names()) == {"Alice", "Bob"}
    assert "12345" in phonebook.numbers()
Ejemplo n.º 38
0
class PhonebookTest(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()

    # run after test to do clean-up
    def tearDown(self):
        pass

    def test_lookup_entry_by_name(self):
        self.phonebook.add("Bob", "12345")
        self.assertEqual("12345", self.phonebook.lookup("Bob"))

    def test_missing_entry_raises_KeyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup("missing")

    # mark a test to be skipped
    # @unittest.skip("WIP")
    def test_empty_phonebook_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())

    @unittest.skip("poor example")
    def test_is_consistent(self):
        """
        Example of bad testing:
        - if an assertion statement fails,
            rest of test is abandoned.
        """
        self.assertTrue(self.phonebook.is_consistent())
        self.phonebook.add("Bob", "12345")
        self.assertTrue(self.phonebook.is_consistent())
        self.phonebook.add("Mary", "012345")
        self.assertTrue(self.phonebook.is_consistent())
        self.phonebook.add("Sue", "12345")  # identical to Bob
        self.assertFalse(self.phonebook.is_consistent())
        self.phonebook.add("Bob", "123")  # prefix of Bob
        self.assertFalse(self.phonebook.is_consistent())

    def test_phonebook_with_several_compatible_entries_is_consistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "012345")
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_with_a_duplicate_number_is_inconsistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "12345")
        self.assertFalse(self.phonebook.is_consistent())

    def test_phonebook_with_numbers_that_prefix_one_another_is_consistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "123")
        self.assertFalse(self.phonebook.is_consistent())

    def test_phonebook_adds_names_and_numbers(self):
        """
        If the implementation of the `add` method is incorrect,
        the likelihood is that both of these `assert`s would fail.
        """
        self.phonebook.add("Sue", "12345")
        # assertIn - takes an iterable and check for membership
        self.assertIn("Sue", self.phonebook.get_names())
        self.assertIn("12345", self.phonebook.get_numbers())
Ejemplo n.º 39
0
class O2Texter(object):
    def __init__(self):
        try:
            HOME_DIR = os.path.join(os.environ['HOME'], ".o2texter")
        except KeyError:
            HOME_DIR = os.path.join(os.environ['HOMEPATH'], ".o2texter")
        try:
            os.mkdir(HOME_DIR)
        except OSError:
            pass
        try:
            self.tree = gtk.glade.XML("texter.glade")
        except:
            #find glade dir
            self.tree = gtk.glade.XML("/usr/share/02texter/texter.glade")
        self.tree.signal_autoconnect(self)
        
        self.phonebook = Phonebook(HOME_DIR + os.sep + "phonebook", self.tree)
        self.form = WebForm(HOME_DIR)
        self.tree.signal_autoconnect(self.phonebook)
        #self.tree.get_widget("texter").show()
        while gtk.events_pending():
            gtk.main_iteration(True)
        #create column for phonebook
        col = gtk.TreeViewColumn("Name")
        cell = gtk.CellRendererText()
        col.pack_start(cell, True)
        col.set_attributes(cell, text=0)
        self.tree.get_widget("phone_treeview").append_column(col)
        col = gtk.TreeViewColumn("Phone")
        cell = gtk.CellRendererText()
        col.pack_start(cell, True)
        col.set_attributes(cell, text=1)
        self.tree.get_widget("phone_treeview").append_column(col)
        
        self.free_texts = 0
        self.paid_texts = 0
        self.message_count = 0
        self.set_limits(self.tree.get_widget("free").get_active())
        
        #get username and password
        try:
            f = open(self.HOME_DIR + os.sep + "username", "r")
            self.username, self.password = cPickle.load(f)
            f.close()
            self.tree.get_widget("texter").show()
            self.tree.get_widget("main_info").set_text("Logging in...")
            if self.form.login(self.username, self.password):
                self.tree.get_widget("main_info").set_text("Retrieving account details...")
                self.form.get_compose_form(self)
                self.tree.get_widget("main_info").set_text("")
            else:
                self.tree.get_widget("main_info").set_text(self.form.error)
                #XXX set a retry timout
        except IOError:
            self.tree.get_widget("login_window").show()
    
    def login_clicked(self, *args):
        self.username = self.tree.get_widget("uname").get_text()
        self.password = self.tree.get_widget("pass").get_text()
        f = open(self.HOME_DIR + os.sep + "username", "w")
        cPickle.dump([self.username, self.password], f)
        f.close()
        self.tree.get_widget("login_window").hide()
        self.tree.get_widget("texter").show()
        if self.form.login():
            self.get_compose_form()
    
    def change_case(self, entry, *args):
        entry.set_text(entry.get_text().title())
        
    def textbody_changed(self, textbody, key):
        char_count = textbody.get_buffer().get_char_count()
        if char_count < 1:
            self.message_count = 0
        elif char_count < self.total_limit / 3:
            self.message_count = 1
        elif char_count < (self.total_limit / 3) * 2:
            self.message_count = 2
        else:
            self.message_count = 3
        self.tree.get_widget("character_count").set_text("%s/%s %s/3" % (
            char_count, self.total_limit, self.message_count))
        if char_count > self.total_limit:
            self.tree.get_widget("main_info").set_text("Maximum of %s characters allowed.  Please shorten your message" % self.total_limit)
            self.tree.get_widget("send").set_sensitive(False)
        elif char_count < 1:
            self.tree.get_widget("send").set_sensitive(False)
        else:
            self.tree.get_widget("main_info").set_text("")
            self.tree.get_widget("send").set_sensitive(True)
            
    def free_toggled(self, button):
        self.set_limits(button.get_active())
        self.textbody_changed(self.tree.get_widget("textbody"), None)
            
    def set_limits(self, free):
        if free:
            self.total_limit = 444
        else:
            self.total_limit = 480
            
    def set_radio_button(self, widgetname, counter, clean=False):
        if not clean:
            counter = int(counter.strip(";\r\n").split(" = ")[1])
        self.tree.get_widget(widgetname).set_label("%s %s texts remaining" % (
            counter, widgetname))
        self.tree.get_widget(widgetname).set_sensitive(counter)
        return counter
    
    
    def on_clear_clicked(self, button):
        pass
    
    def gtk_main_quit(self, *args):
        gtk.main_quit()
        
        
    def select_valid_radio_button(self):
        """return True if the user can send texts"""
        if self.free_texts > 0:
            self.tree.get_widget("free").set_active(True)
        elif self.paid_texts > 0:
            self.tree.get_widget("paid").set_active(True)
        else:
            self.tree.get_widget("main_info").set_text("You cannot send any texts")
            self.tree.get_widget("textbody").set_sensitive(False)
            self.tree.get_widget("send").set_sensitive(False)
        

    def open_phonebook(self, button):
        self.tree.get_widget("phonebook").show()
        
    def close_phonebook(self, window, *args):
        window.hide()
        return True
    
    def choose_from_phonebook(self, treeview, path, col):
        """When the user doubleclicks a name in the phonebook it will be placed
        in the reciever TextEntry box"""
        self.tree.get_widget("phonebook").hide()
        model = treeview.get_model()
        iter = model.get_iter(path)
        self.tree.get_widget("name").set_text(model.get_value(iter,0))
        self.tree.get_widget("textbody").grab_focus()
    
    def on_send_clicked(self, button):
        self.tree.get_widget("main_info").set_text("Sending message...")
        while gtk.events_pending():
            gtk.main_iteration(False)
        buffer = self.tree.get_widget("textbody").get_buffer()
        message = buffer.get_text(*buffer.get_bounds()).strip()
        #check this is a valid number or name in db
        number = self.phonebook.get_number(self.tree.get_widget("name").get_text())
        self.form.send_message(number, message, self.tree.get_widget("free").get_active())
        self.tree.get_widget("main_info").set_text("")
        buffer.set_text("")
        #deduct messages
        if self.tree.get_widget("free").get_active():
            self.free_texts -= self.message_count
            self.set_radio_button("free", self.free_texts, clean=True)
        else:
            self.paid_texts -= self.message_count
            self.set_radio_button("paid", self.paid_texts, clean=True)
Ejemplo n.º 40
0
class PhonebookTest(unittest.TestCase):
    
    def setUp(self):
        self.phonebook = Phonebook()
    
    def test_lookup_entry_by_name(self):
        self.phonebook.add("Bob", "12345")
        self.assertEqual("12345", self.phonebook.lookup("Bob"))
        
    def test_missing_entry_raises_KeyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup("missing")
            
    def test_empty_phonebook_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())
        
    @unittest.skip("poor example")
    def test_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())
        self.phonebook.add("Bob", "12345")
        self.assertTrue(self.phonebook.is_consistent())
        self.phonebook.add("Mary", "012345")
        self.assertTrue(self.phonebook.is_consistent())
        self.phonebook.add("Sue", "12345") # identical to Bob
        self.assertFalse(self.phonebook.is_consistent())
        self.phonebook.add("Sue", "123") # prefix of Bob
        self.assertFalse(self.phonebook.is_consistent())
        
    def test_phonebook_with_normal_entries_is_consistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "012345")
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_with_duplicate_entries_is_inconsistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "12345")
        self.assertFalse(self.phonebook.is_consistent())
        
    def test_phonebook_with_numbers_that_prefix_one_another_is_inconsistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "123")
        self.assertFalse(self.phonebook.is_consistent())
        
    def test_phonebook_adds_names_and_numbers(self):
        self.phonebook.add("Sue", "12345")
        self.assertIn("Sue", phonebook.get_names())
        self.assertIn("12345", phonebook.get_numbers())
class PhonebookTest(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()
    
    #used to clean up depenencies    
    def tearDown(self):
        pass
   
    def test_lookup_entry_by_name(self):
        self.phonebook.add("Bob", "12345")
        self.assertEqual("12345", self.phonebook.lookup("Bob"))
        
    def test_missing_entry_raises_KeyError(self):
        with self.assertRaises(KeyError):
            self.phonebook.lookup("foobar")
    
    def test_empty_phonebook_is_consistent(self):
        self.assertTrue(self.phonebook.is_consistent())
    
    def test_phonebook_with_normal_entries_is_consistent(self):
        self.phonebook.add("foo", "12345")
        self.phonebook.add("bar", "012345")
        self.assertTrue(self.phonebook.is_consistent())
        
    def test_phonebook_with_duplicate_entries_is_inconsistent(self):
        self.phonebook.add("foo", "12345")
        self.phonebook.add("bar", "12345")
        self.assertFalse(self.phonebook.is_consistent())
    
    def test_phonebook_with_numbers_that_prefix_another(self):
        self.phonebook.add("foo", "1234")
        self.phonebook.add("bar", "123")
        self.assertFalse(self.phonebook.is_consistent())
        
    def test_phonebook_adds_names_and_numbers(self):
        self.phonebook.add("foo", "12345")
        self.assertIn("foo", self.phonebook.get_names())
        self.assertIn("12345", self.phonebook.get_numbers())
        
        
Ejemplo n.º 42
0
 def setUp(self):
     self.phonebook = Phonebook()
Ejemplo n.º 43
0
class TestPhonebook(unittest.TestCase):

	def setUp(self):
		self.new = Phonebook()

	def test_create(self):
		self.new.create()
		self.assertEqual(self.new.create_flag, True)

	def test_add(self):
		self.new.add("James Ray", "123456789")
		self.new.add("Laura Rose", "23456")
		self.new.add("Ambulance", "911")

		self.assertEqual(len(set(self.new.database.hashkeys)), 4)
		self.assertEqual(self.new.database["Laura Rose"], "23456")

	def test_remove(self):
		self.new.create()
		self.new.add("James Ray", "123456789")
		self.new.add("Laura Rose", "23456")
		self.new.add("Ambulance", "911")
		self.new.remove("James Ray")
		self.assertRaises(KeyError)

	def test_change(self):
		self.new.create()
		self.new.add("James Ray", "123456789")
		self.new.add("Laura Rose", "23456")
		self.new.add("Ambulance", "911")
		self.new.change("Laura Rose", "9999999")
		self.assertEqual(self.new.database["Laura Rose"], "9999999")

	def test_lookup(self):
		self.new.create()
		self.new.add("Laura Rose", "23456")
		self.assertEqual(self.new.lookup("Laura Rose"), "23456")

	def test_reverse_lookup(self):
		self.new.create()
		self.new.add("Laura Rose", "23456")
		self.assertEqual(self.new.reverse_lookup("23456"), "Laura Rose")

	def test_save(self):
		self.new.create()
		self.new.add("James Ray", "123456789")
		self.new.add("Laura Rose", "23456")
		self.new.add("Ambulance", "911")
		self.new.save()
		self.new2 = Phonebook()
		self.assertEqual(self.new.reverse_lookup("23456"), "Laura Rose")
Ejemplo n.º 44
0
def test_lookup_entry():
    phonebook = Phonebook()
    phonebook.add("Bob", "12345")
    assert "12345" == phonebook.lookup("Bob")
Ejemplo n.º 45
0
	def setUp(self):
		self.new = Phonebook()