import unittest import time import helper from mock import Mock from lib.state import State from lib.message import Message from lib.direct import Direct from lib.long_buffer import LongBuffer from lib.order_buffer import OrderBuffer class TestMessage(unittest.TestCase): def setUp(self): helper.setup() self.alice_socket = Mock() self.alice_state = State(self.alice_socket) self.bob_socket = Mock() self.bob_state = State(self.bob_socket) self.setupAlice() self.setupBob() def setupAlice(self): self.bob_state.add_peer('alice') self.bob_state.add_key( 'alice', '9h6wYndVjt8QpnIZOYb7KD2tYKCKw4rjlYg4LM1ODx1Qkr3qA0IuKNukkwKhQ4UP9ypMlhyPHa7AGD7NO7Ws5w==' ) self.bob_state.update_at({ 'handle': 'alice', 'address': '127.0.0.1', 'port': 8888 }) def setupBob(self): self.alice_state.add_peer('bob') self.alice_state.add_key( 'bob', '9h6wYndVjt8QpnIZOYb7KD2tYKCKw4rjlYg4LM1ODx1Qkr3qA0IuKNukkwKhQ4UP9ypMlhyPHa7AGD7NO7Ws5w==' ) self.alice_state.update_at({ 'handle': 'bob', 'address': '127.0.0.1', 'port': 8889 }) def tearDown(self): self.alice_state.remove_peer('bob') self.bob_state.remove_peer('alice') def test_direct_message(self): message = Direct({ 'handle': 'bob', 'speaker': 'alice', 'body': 'm1', 'long_buffer': LongBuffer(self.alice_state), 'timestamp': int(time.time()) }, self.alice_state) bob = self.alice_state.get_peer_by_handle('bob') message.message_bytes = message.get_message_bytes(bob) message.send() black_packet = Message.pack(bob, message.command, message.bounces, message.message_bytes) self.bob_socket.sendto.called_once_with(black_packet, (bob.address, bob.port)) # now bob must unpack the black packet alice = self.bob_state.get_peer_by_handle('alice') received_message = Message.unpack(alice, black_packet, LongBuffer(self.bob_state), OrderBuffer(self.bob_state), {}) self.assertEqual(message.body, received_message['body'])