Beispiel #1
0
class TestChangeNick(TFCTestCase):
    def setUp(self):
        self.c_queue = Queue()
        self.group_list = GroupList()
        self.settings = Settings()
        self.contact_list = ContactList(nicks=['Alice'])

    def tearDown(self):
        while not self.c_queue.empty():
            self.c_queue.get()
        time.sleep(0.1)
        self.c_queue.close()

    def test_active_group_raises_fr(self):
        # Setup
        window = TxWindow(type=WIN_TYPE_GROUP)

        # Test
        self.assertFR("Error: Group is selected.", change_nick, None, window,
                      None, None, None, None)

    def test_missing_nick_raises_fr(self):
        # Setup
        user_input = UserInput("nick ")
        window = TxWindow(type=WIN_TYPE_CONTACT)

        # Test
        self.assertFR("Error: No nick specified.", change_nick, user_input,
                      window, None, None, None, None)

    def test_invalid_nick_raises_fr(self):
        # Setup
        user_input = UserInput("nick Alice\x01")
        window = TxWindow(type=WIN_TYPE_CONTACT, contact=create_contact('Bob'))

        # Test
        self.assertFR("Nick must be printable.", change_nick, user_input,
                      window, self.contact_list, self.group_list, None, None)

    def test_successful_nick_change(self):
        # Setup
        user_input = UserInput("nick Alice_")
        window = TxWindow(name='Alice',
                          type=WIN_TYPE_CONTACT,
                          contact=self.contact_list.get_contact('Alice'))

        # Test
        self.assertIsNone(
            change_nick(user_input, window, self.contact_list, self.group_list,
                        self.settings, self.c_queue))
        self.assertEqual(
            self.contact_list.get_contact('*****@*****.**').nick, 'Alice_')
Beispiel #2
0
    def test_successful_removal_of_contact(self):
        # Setup
        o_input = builtins.input
        builtins.input = lambda x: 'Yes'
        user_input = UserInput('rm Alice')
        contact_list = ContactList(nicks=['Alice'])
        window = Window(window_contacts=[contact_list.get_contact('Alice')],
                        type='contact')
        group_list = GroupList(groups=['testgroup'])
        settings = Settings()
        queues = {KEY_MANAGEMENT_QUEUE: Queue(), COMMAND_PACKET_QUEUE: Queue()}

        # Test
        for g in group_list:
            self.assertIsInstance(g, Group)
            self.assertTrue(g.has_member('*****@*****.**'))

        self.assertIsNone(
            remove_contact(user_input, window, contact_list, group_list,
                           settings, queues))
        self.assertEqual(queues[COMMAND_PACKET_QUEUE].qsize(), 1)

        km_data = queues[KEY_MANAGEMENT_QUEUE].get()
        self.assertEqual(km_data, ('REM', '*****@*****.**'))
        self.assertFalse(contact_list.has_contact('*****@*****.**'))

        for g in group_list:
            self.assertIsInstance(g, Group)
            self.assertFalse(g.has_member('*****@*****.**'))

        # Teardown
        builtins.input = o_input
Beispiel #3
0
class TestAddPSKTxKeys(unittest.TestCase):

    def setUp(self):
        self.ts           = datetime.datetime.now()
        self.window_list  = WindowList(nicks=[LOCAL_ID])
        self.contact_list = ContactList()
        self.key_list     = KeyList()
        self.settings     = Settings()
        self.pubkey_buf   = {'*****@*****.**' : KEY_LENGTH*b'a'}
        self.packet       = KEY_LENGTH * b'\x01' + KEY_LENGTH * b'\x02' + b'*****@*****.**' + US_BYTE + b'Alice'

    def test_add_psk_tx_keys(self):
        self.assertIsNone(add_psk_tx_keys(self.packet, self.ts, self.window_list, self.contact_list,
                                          self.key_list, self.settings, self.pubkey_buf))

        keyset = self.key_list.get_keyset('*****@*****.**')
        self.assertIsInstance(keyset, KeySet)
        self.assertEqual(keyset.rx_account, '*****@*****.**')
        self.assertEqual(keyset.tx_key, KEY_LENGTH * b'\x01')
        self.assertEqual(keyset.tx_hek, KEY_LENGTH * b'\x02')
        self.assertEqual(keyset.rx_key, bytes(KEY_LENGTH))
        self.assertEqual(keyset.rx_hek, bytes(KEY_LENGTH))

        contact = self.contact_list.get_contact('*****@*****.**')
        self.assertIsInstance(contact, Contact)

        self.assertEqual(contact.rx_account, '*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertEqual(contact.rx_fingerprint, bytes(FINGERPRINT_LEN))
        self.assertEqual(contact.tx_fingerprint, bytes(FINGERPRINT_LEN))

        self.assertFalse('*****@*****.**' in self.pubkey_buf)
Beispiel #4
0
    def test_autonick_ecdhe_kex(self):
        # Setup
        input_list = [
            '*****@*****.**', '*****@*****.**', '', '',
            '2QJL5gVSPEjMTaxWPfYkzG9UJxzZDNSx6PPeVWdzS5CFN7knZy', 'Yes'
        ]
        gen = iter(input_list)

        def mock_input(_):
            return str(next(gen))

        builtins.input = mock_input

        contact_list = ContactList()
        group_list = GroupList()
        gateway = Gateway()
        settings = Settings()
        queues = {COMMAND_PACKET_QUEUE: Queue(), KEY_MANAGEMENT_QUEUE: Queue()}

        # Test
        self.assertIsNone(
            add_new_contact(contact_list, group_list, settings, queues,
                            gateway))

        contact = contact_list.get_contact('*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertNotEqual(
            contact.tx_fingerprint,
            bytes(32))  # Indicates that PSK function was not called
Beispiel #5
0
    def test_disable_file_reception_for_all_users(self):
        # Setup
        user_input = UserInput('store off all')
        contact_list = ContactList(nicks=['Alice', 'Bob'])
        group_list = GroupList()
        contact = contact_list.get_contact('*****@*****.**')
        settings = Settings()
        c_queue = Queue()
        window = Window(uid='*****@*****.**',
                        type='contact',
                        contact=contact,
                        window_contacts=[contact])
        for c in contact_list:
            c.file_reception = True
        for g in group_list:
            g.file_reception = True

        # Test
        for c in contact_list:
            self.assertTrue(c.file_reception)
        for g in group_list:
            self.assertTrue(g.log_messages)
        self.assertIsNone(
            contact_setting(user_input, window, contact_list, group_list,
                            settings, c_queue))
        time.sleep(0.2)
        for c in contact_list:
            self.assertFalse(c.file_reception)
        for g in group_list:
            self.assertFalse(g.log_messages)
Beispiel #6
0
    def test_standard_nick_psk_kex(self):
        # Setup
        o_getpass = getpass.getpass
        getpass.getpass = lambda x: 'test_password'
        input_list = [
            '*****@*****.**', '*****@*****.**', 'Alice_', 'psk', '.'
        ]
        gen = iter(input_list)

        def mock_input(_):
            return str(next(gen))

        builtins.input = mock_input

        contact_list = ContactList()
        group_list = GroupList()
        gateway = Gateway()
        settings = Settings(disable_gui_dialog=True)
        queues = {COMMAND_PACKET_QUEUE: Queue(), KEY_MANAGEMENT_QUEUE: Queue()}

        # Test
        self.assertIsNone(
            add_new_contact(contact_list, group_list, settings, queues,
                            gateway))
        contact = contact_list.get_contact('*****@*****.**')
        self.assertEqual(contact.nick, 'Alice_')
        self.assertEqual(contact.tx_fingerprint,
                         bytes(32))  # Indicates that PSK function was called

        # Teardown
        getpass.getpass = o_getpass
        os.remove('[email protected] - Give to [email protected]')
Beispiel #7
0
    def test_disable_notifications_for_all_users(self):
        # Setup
        user_input = UserInput('notify off all')
        contact_list = ContactList(nicks=['Alice', 'Bob'])
        group_list = GroupList(groups=['testgroup'])
        contact = contact_list.get_contact('*****@*****.**')
        settings = Settings()
        c_queue = Queue()
        window = Window(uid='*****@*****.**',
                        type='contact',
                        contact=contact,
                        window_contacts=[contact])
        for c in contact_list:
            c.notifications = True
        for g in group_list:
            g.notifications = True

        # Test
        for c in contact_list:
            self.assertTrue(c.notifications)
        for g in group_list:
            self.assertTrue(g.notifications)
        self.assertIsNone(
            contact_setting(user_input, window, contact_list, group_list,
                            settings, c_queue))
        time.sleep(0.2)
        for c in contact_list:
            self.assertFalse(c.notifications)
        for g in group_list:
            self.assertFalse(g.notifications)
Beispiel #8
0
class TestPacketList(unittest.TestCase):

    def setUp(self):
        self.contact_list = ContactList(nicks=['Alice', 'Bob'])
        self.settings     = Settings()
        packet            = Packet('*****@*****.**', self.contact_list.get_contact('Alice'),
                                   ORIGIN_CONTACT_HEADER, MESSAGE, self.settings)

        self.packet_list         = PacketList(self.settings, self.contact_list)
        self.packet_list.packets = [packet]

    def test_packet_list_iterates_over_contact_objects(self):
        for p in self.packet_list:
            self.assertIsInstance(p, Packet)

    def test_len_returns_number_of_contacts(self):
        self.assertEqual(len(self.packet_list), 1)

    def test_has_packet(self):
        self.assertTrue(self.packet_list.has_packet('*****@*****.**', ORIGIN_CONTACT_HEADER, MESSAGE))
        self.assertFalse(self.packet_list.has_packet('*****@*****.**', ORIGIN_USER_HEADER, MESSAGE))

    def test_get_packet(self):
        packet = self.packet_list.get_packet('*****@*****.**', ORIGIN_CONTACT_HEADER, MESSAGE)
        self.assertEqual(packet.account, '*****@*****.**')
        self.assertEqual(packet.origin, ORIGIN_CONTACT_HEADER)
        self.assertEqual(packet.type, MESSAGE)
Beispiel #9
0
    def test_contact_not_present_on_txm(self):
        # Setup
        o_input = builtins.input
        builtins.input = lambda x: 'Yes'
        user_input = UserInput('rm [email protected]')
        contact_list = ContactList(nicks=['Bob'])
        window = Window(window_contact=[contact_list.get_contact('Bob')],
                        type='group')
        group_list = GroupList(groups=[])
        settings = Settings()
        queues = {KEY_MANAGEMENT_QUEUE: Queue(), COMMAND_PACKET_QUEUE: Queue()}

        # Test
        self.assertIsNone(
            remove_contact(user_input, window, contact_list, group_list,
                           settings, queues))
        self.assertEqual(queues[COMMAND_PACKET_QUEUE].qsize(), 1)

        command_packet, settings_ = queues[COMMAND_PACKET_QUEUE].get()
        self.assertIsInstance(command_packet, bytes)
        self.assertIsInstance(settings_, Settings)

        # Teardown
        builtins.input = o_input

        queues[KEY_MANAGEMENT_QUEUE].close()
        queues[COMMAND_PACKET_QUEUE].close()
Beispiel #10
0
    def test_function(self):
        # Setup
        packet       = 32 * b'\x01' + 32 * b'\x02' + b'*****@*****.**' + US_BYTE + b'Alice'
        ts           = datetime.datetime.now()
        window_list  = WindowList(nicks=['local'])
        settings     = Settings()
        pubkey_buf   = dict()
        contact_list = ContactList()
        key_list     = KeyList()

        # Test
        self.assertIsNone(psk_command(packet, ts, window_list, contact_list, key_list, settings, pubkey_buf))

        keyset = key_list.get_keyset('*****@*****.**')
        self.assertIsInstance(keyset, KeySet)
        self.assertEqual(keyset.rx_account, '*****@*****.**')
        self.assertEqual(keyset.tx_key, 32 * b'\x01')
        self.assertEqual(keyset.tx_hek, 32 * b'\x02')
        self.assertEqual(keyset.rx_key, bytes(32))
        self.assertEqual(keyset.rx_hek, bytes(32))

        contact = contact_list.get_contact('*****@*****.**')
        self.assertIsInstance(contact, Contact)

        self.assertEqual(contact.rx_account, '*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertEqual(contact.rx_fingerprint, bytes(32))
        self.assertEqual(contact.tx_fingerprint, bytes(32))
Beispiel #11
0
    def test_successful_nick_change(self):
        # Setup
        user_input = UserInput("nick Alice_")
        contact_list = ContactList(nicks=['Alice'])
        window = Window(name='Alice',
                        type='contact',
                        contact=contact_list.get_contact('Alice'))
        group_list = GroupList()
        settings = Settings()
        c_queue = Queue()

        # Test
        self.assertIsNone(
            change_nick(user_input, window, contact_list, group_list, settings,
                        c_queue))
        contact = contact_list.get_contact('*****@*****.**')
        self.assertEqual(contact.nick, 'Alice_')
Beispiel #12
0
    def test_successful_exchange(self):
        # Setup
        contact_list = ContactList()
        settings = Settings()
        queues = {COMMAND_PACKET_QUEUE: Queue(), KEY_MANAGEMENT_QUEUE: Queue()}
        gateway = Gateway()
        o_input = builtins.input
        input_list = [
            '2QJL5gVSPEjMTaxWPfYkzG9UJxzZDNSx6PPeVWdzS5CFN7knZy',  # Correct key
            'Yes'
        ]  # Fingerprint match

        gen = iter(input_list)

        def mock_input(_):
            return str(next(gen))

        builtins.input = mock_input

        # Test
        self.assertIsNone(
            start_key_exchange('*****@*****.**', '*****@*****.**', 'Alice',
                               contact_list, settings, queues, gateway))

        contact = contact_list.get_contact('*****@*****.**')

        self.assertEqual(contact.rx_account, '*****@*****.**')
        self.assertEqual(contact.tx_account, '*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertIsInstance(contact.tx_fingerprint, bytes)
        self.assertIsInstance(contact.rx_fingerprint, bytes)
        self.assertEqual(len(contact.tx_fingerprint), 32)
        self.assertEqual(len(contact.rx_fingerprint), 32)
        self.assertFalse(contact.log_messages)
        self.assertFalse(contact.file_reception)
        self.assertFalse(contact.notifications)

        time.sleep(0.2)
        cmd, account, txkey, rxkey, txhek, rxhek = queues[
            KEY_MANAGEMENT_QUEUE].get()

        self.assertEqual(cmd, 'ADD')
        self.assertEqual(account, '*****@*****.**')
        self.assertEqual(len(txkey), 32)
        self.assertIsInstance(txkey, bytes)
        self.assertEqual(len(txhek), 32)
        self.assertIsInstance(txhek, bytes)
        self.assertEqual(rxkey, bytes(32))
        self.assertEqual(rxhek, bytes(32))

        self.assertEqual(queues[COMMAND_PACKET_QUEUE].qsize(), 1)

        # Teardown
        builtins.input = o_input
Beispiel #13
0
    def test_enable_logging_contact(self):
        # Setup
        cmd_data = b'e' + US_BYTE + b'*****@*****.**'
        ts = datetime.datetime.now()
        contact_list = ContactList(nicks=['Bob'])
        window_list = WindowList(windows=[
            RxMWindow(type='contact', name='Bob', uid='*****@*****.**')
        ])
        group_list = GroupList()
        setting_type = 'L'

        # Test
        contact_list.get_contact('*****@*****.**').log_messages = False
        self.assertFalse(
            contact_list.get_contact('*****@*****.**').log_messages)
        self.assertIsNone(
            contact_setting(cmd_data, ts, window_list, contact_list,
                            group_list, setting_type))
        self.assertTrue(
            contact_list.get_contact('*****@*****.**').log_messages)
Beispiel #14
0
    def test_function(self):
        # Setup
        contact_list = ContactList()
        settings = Settings(disable_gui_dialog=True)
        queues = {COMMAND_PACKET_QUEUE: Queue(), KEY_MANAGEMENT_QUEUE: Queue()}
        o_urandom = os.urandom
        os.urandom = lambda x: x * b'\x00'
        o_input = builtins.input
        o_getpass = getpass.getpass
        getpass.getpass = lambda x: 'test_password'
        builtins.input = lambda x: '.'

        # Test
        self.assertIsNone(
            new_psk('*****@*****.**', '*****@*****.**', 'Alice',
                    contact_list, settings, queues))

        contact = contact_list.get_contact('*****@*****.**')

        self.assertEqual(contact.rx_account, '*****@*****.**')
        self.assertEqual(contact.tx_account, '*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertEqual(contact.tx_fingerprint, bytes(32))
        self.assertEqual(contact.rx_fingerprint, bytes(32))
        self.assertFalse(contact.log_messages)
        self.assertFalse(contact.file_reception)
        self.assertFalse(contact.notifications)

        time.sleep(0.2)
        cmd, account, txkey, rxkey, txhek, rxhek = queues[
            KEY_MANAGEMENT_QUEUE].get()

        self.assertEqual(cmd, 'ADD')
        self.assertEqual(account, '*****@*****.**')
        self.assertEqual(len(txkey), 32)
        self.assertIsInstance(txkey, bytes)
        self.assertEqual(len(txhek), 32)
        self.assertIsInstance(txhek, bytes)
        self.assertEqual(rxkey, bytes(32))
        self.assertEqual(rxhek, bytes(32))

        self.assertEqual(queues[COMMAND_PACKET_QUEUE].qsize(), 1)
        print(os.path.curdir)
        self.assertTrue(
            os.path.isfile('[email protected] - Give to [email protected]'))

        # Teardown
        os.remove('[email protected] - Give to [email protected]')
        builtins.input = o_input
        os.urandom = o_urandom
        getpass.getpass = o_getpass
Beispiel #15
0
    def test_new_local_key(self):
        # Setup
        contact_list = ContactList()
        settings = Settings(nh_bypass_messages=False)
        queues = {COMMAND_PACKET_QUEUE: Queue(), KEY_MANAGEMENT_QUEUE: Queue()}
        gateway = Gateway()
        o_urandom = os.urandom
        os.urandom = lambda x: x * b'\xff'
        o_input = builtins.input
        input_list = ['bad', 'resend', 'ff']
        gen = iter(input_list)

        def mock_input(_):
            return str(next(gen))

        builtins.input = mock_input

        # Test
        self.assertIsNone(
            new_local_key(contact_list, settings, queues, gateway))

        local_contact = contact_list.get_contact('local')

        self.assertEqual(local_contact.rx_account, 'local')
        self.assertEqual(local_contact.tx_account, 'local')
        self.assertEqual(local_contact.nick, 'local')
        self.assertEqual(local_contact.tx_fingerprint, bytes(32))
        self.assertEqual(local_contact.rx_fingerprint, bytes(32))
        self.assertFalse(local_contact.log_messages)
        self.assertFalse(local_contact.file_reception)
        self.assertFalse(local_contact.notifications)

        time.sleep(0.2)
        cmd, account, txkey, rxkey, txhek, rxhek = queues[
            KEY_MANAGEMENT_QUEUE].get()

        self.assertEqual(cmd, 'ADD')
        self.assertEqual(account, 'local')
        self.assertEqual(len(txkey), 32)
        self.assertIsInstance(txkey, bytes)
        self.assertEqual(len(txhek), 32)
        self.assertIsInstance(txhek, bytes)
        self.assertEqual(rxkey, bytes(32))
        self.assertEqual(rxhek, bytes(32))

        self.assertEqual(queues[COMMAND_PACKET_QUEUE].qsize(), 1)

        # Teardown
        os.urandom = o_urandom
        builtins.input = o_input
Beispiel #16
0
    def test_successful_removal(self):
        # Setup
        contact_list = ContactList(nicks=['Alice', 'Bob'])
        contact = contact_list.get_contact('*****@*****.**')
        group_list = GroupList(groups=['testgroup', 'testgroup2'])
        key_list = KeyList(nicks=['Alice', 'Bob'])
        self.window_list.windows = [RxWindow(type=WIN_TYPE_GROUP)]

        # Test
        self.assertIsNone(
            remove_contact(self.cmd_data, self.ts, self.window_list,
                           contact_list, group_list, key_list))
        self.assertFalse(contact_list.has_contact('*****@*****.**'))
        self.assertFalse(key_list.has_keyset('*****@*****.**'))
        for g in group_list:
            self.assertFalse(contact in g.members)
Beispiel #17
0
    def test_successful_removal(self):
        # Setup
        cmd_data = b'*****@*****.**'
        ts = datetime.datetime.now()
        contact_list = ContactList(nicks=['Alice', 'Bob'])
        contact = contact_list.get_contact('*****@*****.**')
        group_list = GroupList(groups=['testgroup', 'testgroup2'])
        key_list = KeyList(nicks=['Alice', 'Bob'])
        window_list = WindowList()

        # Test
        self.assertIsNone(
            remove_contact(cmd_data, ts, window_list, contact_list, group_list,
                           key_list))
        self.assertFalse(contact_list.has_contact('*****@*****.**'))
        self.assertFalse(key_list.has_keyset('*****@*****.**'))
        for g in group_list:
            self.assertFalse(contact in g.members)
Beispiel #18
0
    def test_class(self):
        # Setup
        contact_list          = ContactList(nicks=['Alice', 'Bob', 'local'])
        contact               = contact_list.get_contact('Alice')
        contact.notifications = True
        group_list            = GroupList(groups=['testgroup'], contact_list=contact_list)
        settings              = Settings()

        window1 = Window('*****@*****.**', contact_list, group_list, settings)
        window2 = Window('local',            contact_list, group_list, settings)
        window3 = Window('testgroup',        contact_list, group_list, settings)

        # Test
        with self.assertRaises(ValueError):
            Window('charlie', contact_list, group_list, settings)

        self.assertEqual(len(window1), 0)

        window1.message_log = ['a', 'b']
        for m in window1:
            self.assertIsInstance(m, str)

        window3.remove_contacts(['*****@*****.**'])
        self.assertEqual(len(window3.window_contacts), 1)
        self.assertFalse(window3.has_contact('*****@*****.**'))
        window3.add_contacts(['*****@*****.**'])
        self.assertEqual(len(window3.window_contacts), 2)
        self.assertTrue(window3.has_contact('*****@*****.**'))

        self.assertIsNone(window1.clear_window())
        self.assertEqual(len(window1), 2)
        self.assertIsNone(window1.reset_window())
        self.assertEqual(len(window1), 0)

        ts = datetime.datetime.now()
        window3.previous_msg_ts = datetime.datetime.strptime('01/01/2017', '%d/%m/%Y')
        self.assertIsNone(window3.print_new(ts, 20 * 'test message', '*****@*****.**', print_=True))
        self.assertIsNone(window3.print_new(ts, 'test message', '*****@*****.**', print_=True))

        window2.is_active = True
        self.assertIsNone(window2.print_new(ts, 'test message', print_=True))
        window3.message_log = []
        self.assertIsNone(window2.redraw())
        self.assertIsNone(window3.redraw())
Beispiel #19
0
    def test_no_contact_found_on_txm(self):
        # Setup
        builtins.input = lambda _: 'Yes'
        user_input = UserInput('rm [email protected]')
        contact_list = ContactList(nicks=['Bob'])
        window = TxWindow(window_contact=[contact_list.get_contact('Bob')],
                          type=WIN_TYPE_GROUP)

        # Test
        self.assertIsNone(
            remove_contact(user_input, window, self.contact_list,
                           self.group_list, self.settings, self.queues,
                           self.master_key))
        time.sleep(0.1)

        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 2)
        command_packet, settings_ = self.queues[COMMAND_PACKET_QUEUE].get()
        self.assertIsInstance(command_packet, bytes)
        self.assertIsInstance(settings_, Settings)
Beispiel #20
0
class TestChangeNick(TFCTestCase):
    def setUp(self):
        self.ts = datetime.now()
        self.contact_list = ContactList(nicks=['Alice'])
        self.window_list = WindowList(contact_list=self.contact_list)
        self.group_list = GroupList()

    def test_nick_change(self):
        # Setup
        cmd_data = b'*****@*****.**' + US_BYTE + b'Alice_'

        # Test
        self.assertIsNone(
            change_nick(cmd_data, self.ts, self.window_list,
                        self.contact_list))
        self.assertEqual(
            self.contact_list.get_contact('*****@*****.**').nick, 'Alice_')
        self.assertEqual(
            self.window_list.get_window('*****@*****.**').name, 'Alice_')
Beispiel #21
0
 def test_enable_notifications_for_user(self):
     # Setup
     user_input = UserInput('notify on')
     contact_list = ContactList(nicks=['Alice'])
     group_list = GroupList()
     settings = Settings()
     c_queue = Queue()
     contact = contact_list.get_contact('Alice')
     contact.notifications = False
     window = Window(uid='*****@*****.**',
                     type='contact',
                     contact=contact)
     # Test
     self.assertFalse(contact.notifications)
     self.assertIsNone(
         contact_setting(user_input, window, contact_list, group_list,
                         settings, c_queue))
     time.sleep(0.2)
     self.assertTrue(contact.notifications)
Beispiel #22
0
 def test_disable_file_reception_for_user(self):
     # Setup
     user_input = UserInput('store off')
     contact_list = ContactList(nicks=['Alice'])
     group_list = GroupList()
     settings = Settings()
     c_queue = Queue()
     contact = contact_list.get_contact('Alice')
     contact.file_reception = True
     window = Window(uid='*****@*****.**',
                     type='contact',
                     contact=contact,
                     window_contacts=[contact])
     # Test
     self.assertTrue(contact.file_reception)
     self.assertIsNone(
         contact_setting(user_input, window, contact_list, group_list,
                         settings, c_queue))
     time.sleep(0.2)
     self.assertFalse(contact.file_reception)
Beispiel #23
0
class TestContactSetting(TFCTestCase):
    def setUp(self):
        self.c_queue = Queue()
        self.contact_list = ContactList(nicks=['Alice', 'Bob'])
        self.settings = Settings()
        self.group_list = GroupList(groups=['testgroup'])

    def tearDown(self):
        while not self.c_queue.empty():
            self.c_queue.get()
        time.sleep(0.1)
        self.c_queue.close()

    def test_invalid_command_raises_fr(self):
        # Setup
        user_input = UserInput('loging on')

        # Test
        self.assertFR("Error: Invalid command.", contact_setting, user_input,
                      None, None, None, None, None)

    def test_missing_parameter_raises_fr(self):
        # Setup
        user_input = UserInput('')

        # Test
        self.assertFR("Error: Invalid command.", contact_setting, user_input,
                      None, None, None, None, None)

    def test_invalid_extra_parameter_raises_fr(self):
        # Setup
        user_input = UserInput('logging on al')

        # Test
        self.assertFR("Error: Invalid command.", contact_setting, user_input,
                      None, None, None, None, None)

    def test_enable_logging_for_user(self):
        # Setup
        user_input = UserInput('logging on')
        contact = self.contact_list.get_contact('Alice')
        contact.log_messages = False
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact)

        # Test
        self.assertFalse(contact.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertTrue(contact.log_messages)

    def test_enable_logging_for_user_during_traffic_masking(self):
        # Setup
        user_input = UserInput('logging on')
        contact = self.contact_list.get_contact('Alice')
        contact.log_messages = False
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          log_messages=False)
        self.settings.session_traffic_masking = True

        # Test
        self.assertFalse(contact.log_messages)
        self.assertFalse(window.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertEqual(self.c_queue.qsize(), 1)
        self.assertTrue(window.log_messages)
        self.assertTrue(contact.log_messages)

    def test_enable_logging_for_group(self):
        # Setup
        user_input = UserInput('logging on')
        group = self.group_list.get_group('testgroup')
        group.log_messages = False
        window = TxWindow(uid='testgroup',
                          type=WIN_TYPE_GROUP,
                          group=group,
                          window_contacts=group.members)

        # Test
        self.assertFalse(group.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertTrue(group.log_messages)

    def test_enable_logging_for_all_users(self):
        # Setup
        user_input = UserInput('logging on all')
        contact = self.contact_list.get_contact('*****@*****.**')
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        for c in self.contact_list:
            c.log_messages = False
        for g in self.group_list:
            g.log_messages = False

        # Test
        for c in self.contact_list:
            self.assertFalse(c.log_messages)
        for g in self.group_list:
            self.assertFalse(g.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for c in self.contact_list:
            self.assertTrue(c.log_messages)
        for g in self.group_list:
            self.assertTrue(g.log_messages)

    def test_disable_logging_for_user(self):
        # Setup
        user_input = UserInput('logging off')
        contact = self.contact_list.get_contact('Alice')
        contact.log_messages = True
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        # Test
        self.assertTrue(contact.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertFalse(contact.log_messages)

    def test_disable_logging_for_group(self):
        # Setup
        user_input = UserInput('logging off')
        group = self.group_list.get_group('testgroup')
        group.log_messages = True
        window = TxWindow(uid='testgroup',
                          type=WIN_TYPE_GROUP,
                          group=group,
                          window_contacts=group.members)

        # Test
        self.assertTrue(group.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertFalse(group.log_messages)

    def test_disable_logging_for_all_users(self):
        # Setup
        user_input = UserInput('logging off all')
        contact = self.contact_list.get_contact('*****@*****.**')
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        for c in self.contact_list:
            c.log_messages = True
        for g in self.group_list:
            g.log_messages = True

        # Test
        for c in self.contact_list:
            self.assertTrue(c.log_messages)
        for g in self.group_list:
            self.assertTrue(g.log_messages)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for c in self.contact_list:
            self.assertFalse(c.log_messages)
        for g in self.group_list:
            self.assertFalse(g.log_messages)

    def test_enable_file_reception_for_user(self):
        # Setup
        user_input = UserInput('store on')
        contact = self.contact_list.get_contact('Alice')
        contact.file_reception = False
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        # Test
        self.assertFalse(contact.file_reception)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertTrue(contact.file_reception)

    def test_enable_file_reception_for_group(self):
        # Setup
        user_input = UserInput('store on')
        group = self.group_list.get_group('testgroup')
        window = TxWindow(uid='testgroup',
                          type=WIN_TYPE_GROUP,
                          group=group,
                          window_contacts=group.members)

        for m in group:
            m.file_reception = False

        # Test
        for m in group:
            self.assertFalse(m.file_reception)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for m in group:
            self.assertTrue(m.file_reception)

    def test_enable_file_reception_for_all_users(self):
        # Setup
        user_input = UserInput('store on all')
        contact = self.contact_list.get_contact('*****@*****.**')
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        for c in self.contact_list:
            c.file_reception = False

        # Test
        for c in self.contact_list:
            self.assertFalse(c.file_reception)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for c in self.contact_list:
            self.assertTrue(c.file_reception)

    def test_disable_file_reception_for_user(self):
        # Setup
        user_input = UserInput('store off')
        contact = self.contact_list.get_contact('Alice')
        contact.file_reception = True
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        # Test
        self.assertTrue(contact.file_reception)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertFalse(contact.file_reception)

    def test_disable_file_reception_for_group(self):
        # Setup
        user_input = UserInput('store off')
        group = self.group_list.get_group('testgroup')
        window = TxWindow(uid='testgroup',
                          type=WIN_TYPE_GROUP,
                          group=group,
                          window_contacts=group.members)

        for m in group:
            m.file_reception = True

        # Test
        for m in group:
            self.assertTrue(m.file_reception)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for m in group:
            self.assertFalse(m.file_reception)

    def test_disable_file_reception_for_all_users(self):
        # Setup
        user_input = UserInput('store off all')
        contact = self.contact_list.get_contact('*****@*****.**')
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        for c in self.contact_list:
            c.file_reception = True

        # Test
        for c in self.contact_list:
            self.assertTrue(c.file_reception)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for c in self.contact_list:
            self.assertFalse(c.file_reception)

    def test_enable_notifications_for_user(self):
        # Setup
        user_input = UserInput('notify on')
        contact = self.contact_list.get_contact('Alice')
        contact.notifications = False
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact)

        # Test
        self.assertFalse(contact.notifications)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertTrue(contact.notifications)

    def test_enable_notifications_for_group(self):
        # Setup
        user_input = UserInput('notify on')
        group = self.group_list.get_group('testgroup')
        group.notifications = False
        window = TxWindow(uid='testgroup',
                          type=WIN_TYPE_GROUP,
                          group=group,
                          window_contacts=group.members)

        # Test
        self.assertFalse(group.notifications)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertTrue(group.notifications)

    def test_enable_notifications_for_all_users(self):
        # Setup
        user_input = UserInput('notify on all')
        contact = self.contact_list.get_contact('*****@*****.**')
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        for c in self.contact_list:
            c.notifications = False
        for g in self.group_list:
            g.notifications = False

        # Test
        for c in self.contact_list:
            self.assertFalse(c.notifications)
        for g in self.group_list:
            self.assertFalse(g.notifications)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for c in self.contact_list:
            self.assertTrue(c.notifications)
        for g in self.group_list:
            self.assertTrue(g.notifications)

    def test_disable_notifications_for_user(self):
        # Setup
        user_input = UserInput('notify off')
        contact = self.contact_list.get_contact('Alice')
        contact.notifications = True
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        # Test
        self.assertTrue(contact.notifications)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertFalse(contact.notifications)

    def test_disable_notifications_for_group(self):
        # Setup
        user_input = UserInput('notify off')
        group = self.group_list.get_group('testgroup')
        group.notifications = True
        window = TxWindow(uid='testgroup',
                          type=WIN_TYPE_GROUP,
                          group=group,
                          window_contacts=group.members)

        # Test
        self.assertTrue(group.notifications)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        self.assertFalse(group.notifications)

    def test_disable_notifications_for_all_users(self):
        # Setup
        user_input = UserInput('notify off all')
        contact = self.contact_list.get_contact('*****@*****.**')
        window = TxWindow(uid='*****@*****.**',
                          type=WIN_TYPE_CONTACT,
                          contact=contact,
                          window_contacts=[contact])

        for c in self.contact_list:
            c.notifications = True
        for g in self.group_list:
            g.notifications = True

        # Test
        for c in self.contact_list:
            self.assertTrue(c.notifications)
        for g in self.group_list:
            self.assertTrue(g.notifications)

        self.assertIsNone(
            contact_setting(user_input, window, self.contact_list,
                            self.group_list, self.settings, self.c_queue))
        time.sleep(0.1)

        for c in self.contact_list:
            self.assertFalse(c.notifications)
        for g in self.group_list:
            self.assertFalse(g.notifications)
Beispiel #24
0
class TestRxWindow(TFCTestCase):
    def setUp(self):
        self.contact_list = ContactList(
            nicks=['Alice', 'Bob', 'Charlie', LOCAL_ID])
        self.group_list = GroupList(groups=['test_group', 'test_group2'])
        self.settings = Settings()
        self.packet_list = PacketList()
        self.ts = datetime.fromtimestamp(1502750000)
        self.time = self.ts.strftime('%H:%M')

        group = self.group_list.get_group('test_group')
        group.members = list(
            map(self.contact_list.get_contact, ['Alice', 'Bob', 'Charlie']))

    def create_window(self, uid):
        return RxWindow(uid, self.contact_list, self.group_list, self.settings,
                        self.packet_list)

    def test_command_window_creation(self):
        window = self.create_window(LOCAL_ID)
        self.assertEqual(window.type, WIN_TYPE_COMMAND)
        self.assertEqual(window.window_contacts[0].rx_account, LOCAL_ID)
        self.assertEqual(window.type_print, 'system messages')
        self.assertEqual(window.name, 'system messages')

    def test_file_window_creation(self):
        window = self.create_window(WIN_TYPE_FILE)
        self.assertEqual(window.type, WIN_TYPE_FILE)

    def test_contact_window_creation(self):
        window = self.create_window('*****@*****.**')
        self.assertEqual(window.type, WIN_TYPE_CONTACT)
        self.assertEqual(window.window_contacts[0].rx_account,
                         '*****@*****.**')
        self.assertEqual(window.type_print, 'contact')
        self.assertEqual(window.name, 'Alice')

    def test_group_window_creation(self):
        window = self.create_window('test_group')
        self.assertEqual(window.type, WIN_TYPE_GROUP)
        self.assertEqual(window.window_contacts[0].rx_account,
                         '*****@*****.**')
        self.assertEqual(window.type_print, 'group')
        self.assertEqual(window.name, 'test_group')

    def test_invalid_uid_raises_fr(self):
        self.assertFR("Invalid window 'bad_uid'", self.create_window,
                      'bad_uid')

    def test_len_returns_number_of_messages_in_window(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.message_log = 5 * [
            (datetime.now(), "Lorem ipsum", '*****@*****.**',
             ORIGIN_CONTACT_HEADER, False)
        ]

        # Test
        self.assertEqual(len(window), 5)

    def test_window_iterates_over_message_tuples(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.message_log = 5 * [
            (datetime.now(), 'Lorem ipsum', '*****@*****.**',
             ORIGIN_CONTACT_HEADER, False)
        ]

        # Test
        for mt in window:
            self.assertEqual(mt[1:], ("Lorem ipsum", '*****@*****.**',
                                      ORIGIN_CONTACT_HEADER, False))

    def test_remove_contacts(self):
        # Setup
        window = self.create_window('test_group')

        # Test
        self.assertEqual(len(window.window_contacts), 3)
        self.assertIsNone(
            window.remove_contacts([
                '*****@*****.**', '*****@*****.**', '*****@*****.**'
            ]))
        self.assertEqual(len(window.window_contacts), 1)

    def test_add_contacts(self):
        # Setup
        window = self.create_window('test_group')
        window.window_contacts = [self.contact_list.get_contact('Alice')]

        # Test
        self.assertIsNone(
            window.add_contacts([
                '*****@*****.**', '*****@*****.**', '*****@*****.**'
            ]))
        self.assertEqual(len(window.window_contacts), 2)

    def test_reset_window(self):
        # Setup
        window = self.create_window('test_group')
        window.message_log = [(datetime.now(), "Hi everybody",
                               '*****@*****.**', ORIGIN_USER_HEADER, False),
                              (datetime.now(), "Hi David", '*****@*****.**',
                               ORIGIN_CONTACT_HEADER, False),
                              (datetime.now(), "Hi David", '*****@*****.**',
                               ORIGIN_CONTACT_HEADER, False)]

        # Test
        self.assertIsNone(window.reset_window())
        self.assertEqual(len(window), 0)

    def test_has_contact(self):
        window = self.create_window('test_group')
        self.assertTrue(window.has_contact('*****@*****.**'))
        self.assertFalse(window.has_contact('*****@*****.**'))

    def test_create_handle_dict(self):
        # Setup
        window = self.create_window('test_group')
        message_log = [(datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_CONTACT_HEADER, False),
                       (datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_USER_HEADER, False),
                       (datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_CONTACT_HEADER, False),
                       (datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_CONTACT_HEADER, True),
                       (datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_CONTACT_HEADER, False),
                       (datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_CONTACT_HEADER, False),
                       (datetime.now(), "Lorem ipsum", '*****@*****.**',
                        ORIGIN_CONTACT_HEADER, False)]

        # Test
        self.assertIsNone(window.create_handle_dict(message_log))
        self.assertEqual(
            window.handle_dict, {
                '*****@*****.**': 'Alice',
                '*****@*****.**': 'Bob',
                '*****@*****.**': 'Charlie',
                '*****@*****.**': '*****@*****.**',
                '*****@*****.**': '*****@*****.**'
            })

    def test_get_command_handle(self):
        # Setup
        window = self.create_window(LOCAL_ID)
        window.is_active = True
        window.handle_dict = {LOCAL_ID: LOCAL_ID}

        # Test
        self.assertEqual(
            window.get_handle(self.ts, LOCAL_ID, ORIGIN_USER_HEADER, False),
            f"{self.time} -!- ")

    def test_get_contact_handle(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.is_active = True
        window.handle_dict = {'*****@*****.**': 'Alice'}

        # Test
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**', ORIGIN_USER_HEADER,
                              False), f"{self.time}    Me: ")
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**',
                              ORIGIN_CONTACT_HEADER, False),
            f"{self.time} Alice: ")

        window.is_active = False
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**', ORIGIN_USER_HEADER,
                              False), f"{self.time} Me (private message): ")
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**',
                              ORIGIN_CONTACT_HEADER, False),
            f"{self.time} Alice (private message): ")

    def test_get_group_contact_handle(self):
        # Setup
        window = self.create_window('test_group')
        window.is_active = True
        window.handle_dict = {
            '*****@*****.**': 'Alice',
            '*****@*****.**': 'Charlie',
            '*****@*****.**': '*****@*****.**',
            '*****@*****.**': '*****@*****.**'
        }

        # Test
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**', ORIGIN_USER_HEADER,
                              False), f"{self.time}               Me: ")
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**',
                              ORIGIN_CONTACT_HEADER, False),
            f"{self.time}          Charlie: ")

        window.is_active = False
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**', ORIGIN_USER_HEADER,
                              False), f"{self.time} Me (group test_group): ")
        self.assertEqual(
            window.get_handle(self.ts, '*****@*****.**',
                              ORIGIN_CONTACT_HEADER, False),
            f"{self.time} Charlie (group test_group): ")

    def test_print_to_inactive_window_preview_on_short_message(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.handle_dict = {'*****@*****.**': 'Alice'}
        window.is_active = False
        window.settings = Settings(new_message_notify_preview=True)
        msg_tuple = (self.ts, "Hi Bob", '*****@*****.**', ORIGIN_USER_HEADER,
                     False)

        # Test
        self.assertPrints(
            f"{BOLD_ON}{self.time} Me (private message): {NORMAL_TEXT}Hi Bob\n{CURSOR_UP_ONE_LINE}{CLEAR_ENTIRE_LINE}",
            window.print, msg_tuple)

    def test_print_to_inactive_window_preview_on_long_message(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.is_active = False
        window.handle_dict = {'*****@*****.**': 'Alice'}
        window.settings = Settings(new_message_notify_preview=True)
        long_message = (
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque consequat libero et lao"
            "reet egestas. Aliquam a arcu malesuada, elementum metus eget, elementum mi. Vestibulum i"
            "d arcu sem. Ut sodales odio sed viverra mollis. Praesent gravida ante tellus, pellentesq"
            "ue venenatis massa placerat quis. Nullam in magna porta, hendrerit sem vel, dictum ipsum"
            ". Ut sagittis, ipsum ut bibendum ornare, ex lorem congue metus, vel posuere metus nulla "
            "at augue.")
        msg_tuple = (self.ts, long_message, '*****@*****.**',
                     ORIGIN_USER_HEADER, False)

        # Test
        self.assertPrints(
            f"{BOLD_ON}{self.time} Me (private message): {NORMAL_TEXT}Lorem ipsum dolor sit "
            f"amet, consectetur adipisc...\n{CURSOR_UP_ONE_LINE}{CLEAR_ENTIRE_LINE}",
            window.print, msg_tuple)

    def test_print_to_inactive_window_preview_off(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.is_active = False
        window.handle_dict = {'*****@*****.**': 'Alice'}
        window.settings = Settings(new_message_notify_preview=False)
        msg_tuple = (self.ts, "Hi Bob", '*****@*****.**', ORIGIN_USER_HEADER,
                     False)

        # Test
        self.assertPrints(
            f"{BOLD_ON}{self.time} Me (private message): {NORMAL_TEXT}{BOLD_ON}1 unread message{NORMAL_TEXT}\n"
            f"{CURSOR_UP_ONE_LINE}{CLEAR_ENTIRE_LINE}", window.print,
            msg_tuple)

    def test_print_to_active_window_no_date_change(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.previous_msg_ts = datetime.fromtimestamp(1502750000)
        window.is_active = True
        window.handle_dict = {'*****@*****.**': 'Bob'}
        window.settings = Settings(new_message_notify_preview=False)
        msg_tuple = (self.ts, "Hi Alice", '*****@*****.**',
                     ORIGIN_CONTACT_HEADER, False)

        # Test
        self.assertPrints(f"{BOLD_ON}{self.time} Bob: {NORMAL_TEXT}Hi Alice\n",
                          window.print, msg_tuple)

    def test_print_to_active_window_with_date_change_and_whisper(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.previous_msg_ts = datetime.fromtimestamp(1501750000)
        window.is_active = True
        window.handle_dict = {'*****@*****.**': 'Bob'}
        window.settings = Settings(new_message_notify_preview=False)
        msg_tuple = (self.ts, "Hi Alice", '*****@*****.**',
                     ORIGIN_CONTACT_HEADER, True)
        self.time = self.ts.strftime('%H:%M')

        # Test
        self.assertPrints(
            f"""\
{BOLD_ON}00:00 -!- Day changed to 2017-08-15{NORMAL_TEXT}
{BOLD_ON}{self.time} Bob (whisper): {NORMAL_TEXT}Hi Alice
""", window.print, msg_tuple)

    def test_print_to_active_window_with_date_change_and_whisper_empty_message(
            self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.previous_msg_ts = datetime.fromtimestamp(1501750000)
        window.is_active = True
        window.handle_dict = {'*****@*****.**': 'Bob'}
        window.settings = Settings(new_message_notify_preview=False)
        msg_tuple = (self.ts, " ", '*****@*****.**', ORIGIN_CONTACT_HEADER,
                     True)

        # Test
        self.assertPrints(
            f"""\
{BOLD_ON}00:00 -!- Day changed to 2017-08-15{NORMAL_TEXT}
{BOLD_ON}{self.time} Bob (whisper): {NORMAL_TEXT}
""", window.print, msg_tuple)

    def test_print_new(self):
        # Setup
        window = self.create_window('*****@*****.**')

        # Test
        self.assertIsNone(
            window.add_new(self.ts,
                           "Hi Alice",
                           '*****@*****.**',
                           ORIGIN_CONTACT_HEADER,
                           output=True))
        self.assertEqual(len(window.message_log), 1)
        self.assertEqual(window.handle_dict['*****@*****.**'], 'Bob')

    def test_redraw_message_window(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.is_active = True
        window.message_log = [(self.ts, "Hi Alice", '*****@*****.**',
                               ORIGIN_CONTACT_HEADER, False)]
        window.unread_messages = 1

        # Test
        self.assertPrints(
            f"""\
{CLEAR_ENTIRE_SCREEN}{CURSOR_LEFT_UP_CORNER}{BOLD_ON}{self.time}   Bob: {NORMAL_TEXT}Hi Alice
""", window.redraw)
        self.assertEqual(window.unread_messages, 0)

    def test_redraw_empty_window(self):
        # Setup
        window = self.create_window('*****@*****.**')
        window.is_active = True
        window.message_log = []

        # Test
        self.assertPrints(
            f"""\
{CLEAR_ENTIRE_SCREEN}{CURSOR_LEFT_UP_CORNER}
                   This window for Alice is currently empty.                    \n
""", window.redraw)

    def test_redraw_file_win(self):
        # Setup
        self.packet_list.packets = [
            Packet(type=FILE,
                   name='testfile.txt',
                   assembly_pt_list=5 * [b'a'],
                   packets=10,
                   size="100.0KB",
                   contact=create_contact('Bob')),
            Packet(type=FILE,
                   name='testfile2.txt',
                   assembly_pt_list=7 * [b'a'],
                   packets=100,
                   size="15.0KB",
                   contact=create_contact('Charlie'))
        ]

        # Test
        window = self.create_window(WIN_TYPE_FILE)
        self.assertPrints(
            f"""\

File name         Size        Sender      Complete    
────────────────────────────────────────────────────────────────────────────────
testfile.txt      100.0KB     Bob         50.00%      
testfile2.txt     15.0KB      Charlie     7.00%       

{6*(CURSOR_UP_ONE_LINE+CLEAR_ENTIRE_LINE)}""", window.redraw_file_win)

    def test_redraw_empty_file_win(self):
        # Setup
        self.packet_list.packet_l = []

        # Test
        window = self.create_window(WIN_TYPE_FILE)
        self.assertPrints(
            f"""\

                  No file transmissions currently in progress.                  

{3*(CURSOR_UP_ONE_LINE+CLEAR_ENTIRE_LINE)}""", window.redraw_file_win)
Beispiel #25
0
class TestKeyExchange(TFCTestCase):
    def setUp(self):
        self.o_input = builtins.input

        self.contact_list = ContactList()
        self.settings = Settings()
        self.queues = {
            COMMAND_PACKET_QUEUE: Queue(),
            NH_PACKET_QUEUE: Queue(),
            KEY_MANAGEMENT_QUEUE: Queue()
        }

    def tearDown(self):
        builtins.input = self.o_input

        for key in self.queues.keys():
            while not self.queues[key].empty():
                self.queues[key].get()
            time.sleep(0.1)
            self.queues[key].close()

    def test_zero_public_key_raises_fr(self):
        # Setup
        builtins.input = lambda _: b58encode(bytes(32))

        # Test
        self.assertFR("Error: Zero public key", start_key_exchange,
                      '*****@*****.**', '*****@*****.**', 'Alice',
                      self.contact_list, self.settings, self.queues)

    def test_raises_fr_during_fingerprint_mismatch(self):
        # Setup
        input_list = [
            'resend',  # Resend should resend key
            '5JCVapni8CR2PEXr5v92cCY2QgSd4cztR2v3L3vK2eair7dGHi',  # Short key should fail
            '5JCVapni8CR2PEXr5v92cCY2QgSd4cztR2v3L3vK2eair7dGHiHa',  # Long key should fail
            '5JCVapni8CR2PEXr5v92cCY2QgSd4cztR2v3L3vK2eair7dGHia',  # Invalid key should fail
            '5JCVapni8CR2PEXr5v92cCY2QgSd4cztR2v3L3vK2eair7dGHiH',  # Correct key
            'No'
        ]  # Fingerprint mismatch

        gen = iter(input_list)
        builtins.input = lambda _: str(next(gen))

        # Test
        self.assertFR("Error: Fingerprint mismatch", start_key_exchange,
                      '*****@*****.**', '*****@*****.**', 'Alice',
                      self.contact_list, self.settings, self.queues)

    def test_successful_exchange(self):
        # Setup
        input_list = [
            '5JCVapni8CR2PEXr5v92cCY2QgSd4cztR2v3L3vK2eair7dGHiH',  # Correct key
            'Yes'
        ]  # Fingerprint match
        gen = iter(input_list)
        builtins.input = lambda _: str(next(gen))

        # Test
        self.assertIsNone(
            start_key_exchange('*****@*****.**', '*****@*****.**', 'Alice',
                               self.contact_list, self.settings, self.queues))
        time.sleep(0.1)

        contact = self.contact_list.get_contact('*****@*****.**')

        self.assertEqual(contact.rx_account, '*****@*****.**')
        self.assertEqual(contact.tx_account, '*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertIsInstance(contact.tx_fingerprint, bytes)
        self.assertIsInstance(contact.rx_fingerprint, bytes)
        self.assertEqual(len(contact.tx_fingerprint), FINGERPRINT_LEN)
        self.assertEqual(len(contact.rx_fingerprint), FINGERPRINT_LEN)
        self.assertFalse(contact.log_messages)
        self.assertFalse(contact.file_reception)
        self.assertTrue(contact.notifications)

        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 1)

        cmd, account, tx_key, rx_key, tx_hek, rx_hek = self.queues[
            KEY_MANAGEMENT_QUEUE].get()

        self.assertEqual(cmd, KDB_ADD_ENTRY_HEADER)
        self.assertEqual(account, '*****@*****.**')
        self.assertEqual(len(tx_key), KEY_LENGTH)
        for key in [tx_key, rx_key, tx_hek, rx_hek]:
            self.assertIsInstance(key, bytes)
            self.assertEqual(len(key), KEY_LENGTH)
Beispiel #26
0
class TestPSK(TFCTestCase):
    def setUp(self):
        if 'TRAVIS' not in os.environ or not os.environ['TRAVIS'] == 'true':
            self.o_getrandom = os.getrandom

        self.o_input = builtins.input
        self.o_getpass = getpass.getpass
        self.contact_list = ContactList()
        self.settings = Settings(disable_gui_dialog=True)
        self.queues = {
            COMMAND_PACKET_QUEUE: Queue(),
            KEY_MANAGEMENT_QUEUE: Queue()
        }

        if 'TRAVIS' not in os.environ or not os.environ['TRAVIS'] == 'true':
            os.getrandom = lambda n, flags: n * b'\x00'

        getpass.getpass = lambda _: 'test_password'
        input_list = [
            '/root/',  # Invalid directory
            '.'
        ]  # Valid directory
        gen = iter(input_list)
        builtins.input = lambda _: str(next(gen))

    def tearDown(self):
        builtins.input = self.o_input
        getpass.getpass = self.o_getpass

        if 'TRAVIS' not in os.environ or not os.environ['TRAVIS'] == 'true':
            os.getrandom = self.o_getrandom

        with ignored(OSError):
            os.remove('[email protected] - Give to [email protected]')

        for key in self.queues.keys():
            while not self.queues[key].empty():
                self.queues[key].get()
            time.sleep(0.1)
            self.queues[key].close()

    def test_psk_creation(self):
        self.assertIsNone(
            create_pre_shared_key('*****@*****.**', '*****@*****.**',
                                  'Alice', self.contact_list, self.settings,
                                  self.queues))

        contact = self.contact_list.get_contact('*****@*****.**')

        self.assertEqual(contact.rx_account, '*****@*****.**')
        self.assertEqual(contact.tx_account, '*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertEqual(contact.tx_fingerprint, bytes(FINGERPRINT_LEN))
        self.assertEqual(contact.rx_fingerprint, bytes(FINGERPRINT_LEN))
        self.assertFalse(contact.log_messages)
        self.assertFalse(contact.file_reception)
        self.assertTrue(contact.notifications)

        cmd, account, tx_key, rx_key, tx_hek, rx_hek = self.queues[
            KEY_MANAGEMENT_QUEUE].get()

        self.assertEqual(cmd, KDB_ADD_ENTRY_HEADER)
        self.assertEqual(account, '*****@*****.**')
        for key in [tx_key, rx_key, tx_hek, rx_hek]:
            self.assertIsInstance(key, bytes)
            self.assertEqual(len(key), KEY_LENGTH)

        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 1)
        self.assertTrue(
            os.path.isfile('[email protected] - Give to [email protected]'))
Beispiel #27
0
class TestLocalKey(TFCTestCase):
    def setUp(self):
        self.o_input = builtins.input
        self.o_urandom = os.urandom

        if 'TRAVIS' not in os.environ or not os.environ['TRAVIS'] == 'true':
            self.o_getrandom = os.getrandom

        self.contact_list = ContactList()
        self.settings = Settings()
        self.queues = {
            COMMAND_PACKET_QUEUE: Queue(),
            NH_PACKET_QUEUE: Queue(),
            KEY_MANAGEMENT_QUEUE: Queue()
        }

    def tearDown(self):
        builtins.input = self.o_input
        os.urandom = self.o_urandom

        if 'TRAVIS' not in os.environ or not os.environ['TRAVIS'] == 'true':
            os.getrandom = self.o_getrandom

        for key in self.queues.keys():
            while not self.queues[key].empty():
                self.queues[key].get()
            time.sleep(0.1)
            self.queues[key].close()

    def test_new_local_key_when_traffic_masking_is_enabled_raises_fr(self):
        # Setup
        self.settings.session_traffic_masking = True

        # Test
        self.assertFR("Error: Command is disabled during traffic masking.",
                      new_local_key, self.contact_list, self.settings,
                      self.queues)

    def test_new_local_key(self):
        # Setup
        self.settings.nh_bypass_messages = False
        self.settings.session_traffic_masking = False

        if 'TRAVIS' not in os.environ or not os.environ['TRAVIS'] == 'true':
            os.getrandom = lambda n, flags: n * b'\xff'

        os.urandom = lambda n: n * b'\xff'
        input_list = ['bad', 'resend', 'ff']
        gen = iter(input_list)
        builtins.input = lambda _: str(next(gen))

        # Test
        self.assertIsNone(
            new_local_key(self.contact_list, self.settings, self.queues))
        time.sleep(0.1)

        local_contact = self.contact_list.get_contact(LOCAL_ID)

        self.assertEqual(local_contact.rx_account, LOCAL_ID)
        self.assertEqual(local_contact.tx_account, LOCAL_ID)
        self.assertEqual(local_contact.nick, LOCAL_ID)
        self.assertEqual(local_contact.tx_fingerprint, bytes(FINGERPRINT_LEN))
        self.assertEqual(local_contact.rx_fingerprint, bytes(FINGERPRINT_LEN))
        self.assertFalse(local_contact.log_messages)
        self.assertFalse(local_contact.file_reception)
        self.assertFalse(local_contact.notifications)

        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 1)

        cmd, account, tx_key, rx_key, tx_hek, rx_hek = self.queues[
            KEY_MANAGEMENT_QUEUE].get()

        self.assertEqual(cmd, KDB_ADD_ENTRY_HEADER)
        self.assertEqual(account, LOCAL_ID)
        for key in [tx_key, rx_key, tx_hek, rx_hek]:
            self.assertIsInstance(key, bytes)
            self.assertEqual(len(key), KEY_LENGTH)
Beispiel #28
0
class TestRemoveContact(TFCTestCase):
    def setUp(self):
        self.o_input = builtins.input
        self.settings = Settings()
        self.master_key = MasterKey()
        self.queues = {
            KEY_MANAGEMENT_QUEUE: Queue(),
            COMMAND_PACKET_QUEUE: Queue()
        }
        self.contact_list = ContactList(nicks=['Alice'])
        self.group_list = GroupList(groups=['testgroup'])

    def tearDown(self):
        builtins.input = self.o_input

        for key in self.queues:
            while not self.queues[key].empty():
                self.queues[key].get()
            time.sleep(0.1)
            self.queues[key].close()

    def test_contact_removal_during_traffic_masking_raises_fr(self):
        # Setup
        self.settings.session_traffic_masking = True

        # Test
        self.assertFR("Error: Command is disabled during traffic masking.",
                      remove_contact, None, None, None, None, self.settings,
                      None, self.master_key)

    def test_missing_account_raises_fr(self):
        # Setup
        user_input = UserInput('rm ')

        # Test
        self.assertFR("Error: No account specified.", remove_contact,
                      user_input, None, None, None, self.settings, None,
                      self.master_key)

    def test_user_abort_raises_fr(self):
        # Setup
        builtins.input = lambda _: 'No'
        user_input = UserInput('rm [email protected]')

        # Test
        self.assertFR("Removal of contact aborted.", remove_contact,
                      user_input, None, None, None, self.settings, None,
                      self.master_key)

    def test_successful_removal_of_contact(self):
        # Setup
        builtins.input = lambda _: 'Yes'
        user_input = UserInput('rm Alice')
        window = TxWindow(
            window_contacts=[self.contact_list.get_contact('Alice')],
            type=WIN_TYPE_CONTACT,
            uid='*****@*****.**')

        # Test
        for g in self.group_list:
            self.assertIsInstance(g, Group)
            self.assertTrue(g.has_member('*****@*****.**'))

        self.assertIsNone(
            remove_contact(user_input, window, self.contact_list,
                           self.group_list, self.settings, self.queues,
                           self.master_key))
        time.sleep(0.1)
        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 2)

        km_data = self.queues[KEY_MANAGEMENT_QUEUE].get()
        self.assertEqual(km_data,
                         (KDB_REMOVE_ENTRY_HEADER, '*****@*****.**'))
        self.assertFalse(self.contact_list.has_contact('*****@*****.**'))

        for g in self.group_list:
            self.assertIsInstance(g, Group)
            self.assertFalse(g.has_member('*****@*****.**'))

    def test_successful_removal_of_last_member_of_active_group(self):
        # Setup
        builtins.input = lambda _: 'Yes'
        user_input = UserInput('rm Alice')
        window = TxWindow(
            window_contacts=[self.contact_list.get_contact('Alice')],
            type=WIN_TYPE_GROUP,
            name='testgroup')
        group = self.group_list.get_group('testgroup')
        group.members = [self.contact_list.get_contact('*****@*****.**')]

        # Test
        for g in self.group_list:
            self.assertIsInstance(g, Group)
            self.assertTrue(g.has_member('*****@*****.**'))
        self.assertEqual(len(group), 1)

        self.assertIsNone(
            remove_contact(user_input, window, self.contact_list,
                           self.group_list, self.settings, self.queues,
                           self.master_key))
        time.sleep(0.1)

        for g in self.group_list:
            self.assertIsInstance(g, Group)
            self.assertFalse(g.has_member('*****@*****.**'))

        self.assertFalse(self.contact_list.has_contact('*****@*****.**'))
        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 2)

        km_data = self.queues[KEY_MANAGEMENT_QUEUE].get()
        self.assertEqual(km_data,
                         (KDB_REMOVE_ENTRY_HEADER, '*****@*****.**'))

    def test_no_contact_found_on_txm(self):
        # Setup
        builtins.input = lambda _: 'Yes'
        user_input = UserInput('rm [email protected]')
        contact_list = ContactList(nicks=['Bob'])
        window = TxWindow(window_contact=[contact_list.get_contact('Bob')],
                          type=WIN_TYPE_GROUP)

        # Test
        self.assertIsNone(
            remove_contact(user_input, window, self.contact_list,
                           self.group_list, self.settings, self.queues,
                           self.master_key))
        time.sleep(0.1)

        self.assertEqual(self.queues[COMMAND_PACKET_QUEUE].qsize(), 2)
        command_packet, settings_ = self.queues[COMMAND_PACKET_QUEUE].get()
        self.assertIsInstance(command_packet, bytes)
        self.assertIsInstance(settings_, Settings)
Beispiel #29
0
class TestAddNewContact(TFCTestCase):
    def setUp(self):
        self.o_getpass = getpass.getpass
        self.contact_list = ContactList()
        self.group_list = GroupList()
        self.settings = Settings(disable_gui_dialog=True)
        self.queues = {
            COMMAND_PACKET_QUEUE: Queue(),
            NH_PACKET_QUEUE: Queue(),
            KEY_MANAGEMENT_QUEUE: Queue()
        }

    def tearDown(self):
        getpass.getpass = self.o_getpass

        with ignored(OSError):
            os.remove('[email protected] - Give to [email protected]')

        for key in self.queues:
            while not self.queues[key].empty():
                self.queues[key].get()
            time.sleep(0.1)
            self.queues[key].close()

    def test_adding_new_contact_during_traffic_masking_raises_fr(self):
        # Setup
        self.settings.session_traffic_masking = True

        # Test
        self.assertFR("Error: Command is disabled during traffic masking.",
                      add_new_contact, self.contact_list, self.group_list,
                      self.settings, self.queues)

    def test_contact_list_full_raises_fr(self):
        # Setup
        self.contact_list = ContactList(
            nicks=['contact_{}'.format(n) for n in range(20)])

        # Test
        self.assertFR("Error: TFC settings only allow 20 accounts.",
                      add_new_contact, self.contact_list, self.group_list,
                      self.settings, self.queues)

    def test_default_nick_x25519_kex(self):
        # Setup
        input_list = [
            '*****@*****.**', '*****@*****.**', '', '',
            '5JJwZE46Eic9B8sKJ8Qocyxa8ytUJSfcqRo7Hr5ES7YgFGeJjCJ', 'Yes'
        ]
        gen = iter(input_list)
        builtins.input = lambda _: str(next(gen))

        # Test
        self.assertIsNone(
            add_new_contact(self.contact_list, self.group_list, self.settings,
                            self.queues))

        contact = self.contact_list.get_contact('*****@*****.**')
        self.assertEqual(contact.nick, 'Alice')
        self.assertNotEqual(contact.tx_fingerprint, bytes(
            FINGERPRINT_LEN))  # Indicates that PSK function was not called

    def test_standard_nick_psk_kex(self):
        # Setup
        getpass.getpass = lambda _: 'test_password'
        input_list = [
            '*****@*****.**', '*****@*****.**', 'Alice_', 'psk', '.'
        ]
        gen = iter(input_list)
        builtins.input = lambda _: str(next(gen))

        # Test
        self.assertIsNone(
            add_new_contact(self.contact_list, self.group_list, self.settings,
                            self.queues))
        contact = self.contact_list.get_contact('*****@*****.**')
        self.assertEqual(contact.nick, 'Alice_')
        self.assertEqual(
            contact.tx_fingerprint,
            bytes(FINGERPRINT_LEN))  # Indicates that PSK function was called
Beispiel #30
0
    def test_loop(self):
        # Setup
        queues = {
            MESSAGE_PACKET_QUEUE: Queue(),
            FILE_PACKET_QUEUE: Queue(),
            COMMAND_PACKET_QUEUE: Queue(),
            NH_PACKET_QUEUE: Queue(),
            LOG_PACKET_QUEUE: Queue(),
            NOISE_PACKET_QUEUE: Queue(),
            NOISE_COMMAND_QUEUE: Queue(),
            KEY_MANAGEMENT_QUEUE: Queue(),
            WINDOW_SELECT_QUEUE: Queue(),
            EXIT_QUEUE: Queue()
        }

        settings = Settings(session_traffic_masking=True)
        gateway = Gateway()
        key_list = KeyList(nicks=['Alice', LOCAL_ID])
        window = TxWindow(log_messages=True)
        contact_list = ContactList(nicks=['Alice', LOCAL_ID])
        window.contact_list = contact_list
        window.window_contacts = [contact_list.get_contact('Alice')]
        user_input = UserInput(plaintext='test')

        queue_message(user_input, window, settings,
                      queues[MESSAGE_PACKET_QUEUE])
        queue_message(user_input, window, settings,
                      queues[MESSAGE_PACKET_QUEUE])
        queue_message(user_input, window, settings,
                      queues[MESSAGE_PACKET_QUEUE])
        queue_command(b'test', settings, queues[COMMAND_PACKET_QUEUE])
        queue_command(b'test', settings, queues[COMMAND_PACKET_QUEUE])
        queue_command(b'test', settings, queues[COMMAND_PACKET_QUEUE], window)
        queue_to_nh(UNENCRYPTED_PACKET_HEADER + UNENCRYPTED_EXIT_COMMAND,
                    settings, queues[NH_PACKET_QUEUE])
        queue_to_nh(UNENCRYPTED_PACKET_HEADER + UNENCRYPTED_WIPE_COMMAND,
                    settings, queues[NH_PACKET_QUEUE])

        def queue_delayer():
            time.sleep(0.1)
            queues[WINDOW_SELECT_QUEUE].put((window, True))

        # Test
        threading.Thread(target=queue_delayer).start()
        self.assertIsNone(
            sender_loop(queues, settings, gateway, key_list, unittest=True))

        threading.Thread(target=queue_delayer).start()

        self.assertIsNone(
            sender_loop(queues, settings, gateway, key_list, unittest=True))

        threading.Thread(target=queue_delayer).start()

        self.assertIsNone(
            sender_loop(queues, settings, gateway, key_list, unittest=True))

        self.assertEqual(len(gateway.packets), 8)
        self.assertEqual(queues[EXIT_QUEUE].qsize(), 2)

        # Teardown
        for key in queues:
            while not queues[key].empty():
                queues[key].get()
            time.sleep(0.1)
            queues[key].close()