def test_generic_deserialize(self): class TestMessage1(Serializable): def __init__(self, a, b): super().__init__(a, b) self.a = a self.b = b class TestMessage2(Serializable): def __init__(self, c, d): super().__init__(c, d) self.c = c self.d = d msg1 = TestMessage1('a', 'b') msg2 = TestMessage2('c', 'd') serialized1 = msg1.serialize() serialized2 = msg2.serialize() obj1 = deserialize(serialized1) obj2 = deserialize(serialized2) self.assertTrue(isinstance(obj1, TestMessage1)) self.assertTrue(isinstance(obj2, TestMessage2)) self.assertEqual(obj1.a, msg1.a) self.assertEqual(obj2.c, msg2.c) bad_data = {'klass': 'UNKNOWN'} self.assertRaises(ValueError, deserialize, json.dumps(bad_data))
def test_nested_deserialize(self): class Child(Serializable): def __init__(self, c): super().__init__(c) self.c = c class Parent(Serializable): def __init__(self, p, child): super().__init__(p, child) self.p = p self.child = child child = Child('c') parent = Parent('p', child) self.assertTrue(isinstance(parent.child, Child)) serialized = parent.serialize() obj = deserialize(serialized) self.assertTrue(isinstance(obj, Parent)) self.assertTrue(isinstance(obj.child, Child)) self.assertEqual(obj.child.c, parent.child.c) del Child del Parent # child is not serializable class Child: def __init__(self, c): self.c = c class Parent(Serializable): def __init__(self, p, child): super().__init__(p, child) self.p = p self.child = child child = Child('c') parent = Parent('p', child) self.assertTrue(isinstance(parent.child, Child)) serialized = parent.serialize() obj = deserialize(serialized) self.assertTrue(isinstance(obj, Parent)) # not serilizable self.assertFalse(isinstance(obj.child, Child))
def test_real_complex_object_deserialize(self): class Child(Serializable): def __init__(self, c): super().__init__(c) self.c = c class Parent(Serializable): def __init__(self, p, leader): super().__init__(p, leader) self.p = p self.leader = leader self.followers = [] def add_follower(self, follower): self.followers.append(follower) class Parent2(Serializable): def __init__(self, p): super().__init__(p) self.p = p parent = Parent('p', Child('l')) parent.add_follower(Child('f1')) parent2 = Parent2(parent) serialized = parent2.serialize() obj = deserialize(serialized) self.assertTrue(isinstance(obj, Parent2)) self.assertTrue(isinstance(obj.p, Parent)) self.assertTrue(isinstance(obj.p.leader, Child)) self.assertTrue(isinstance(obj.p.followers[-1], Child)) self.assertEqual(obj, parent2)
def test_complext_object_deserialize(self): import time class State(Serializable): def __init__(self, state, timestamp): super().__init__(state, timestamp) self.state = state self.timestamp = timestamp class Query(Serializable): def __init__(self, query): super().__init__(query) self.query = query self.states = [] self.set_state('NEW') def set_state(self, new_state): self.states.append(State(new_state, time.time())) query = Query('a query') serialized = query.serialize() obj = deserialize(serialized) self.assertTrue(isinstance(obj, Query)) self.assertEqual(query.states[-1].state, 'NEW') self.assertTrue(isinstance(obj.states[-1], State)) self.assertEqual(query.states[-1].state, obj.states[-1].state)
def processReceivedMessageData(self, msgData): log.log("Received data: %s\n" % msgData) try: container = serializable.deserialize(msgData) if 'received' in container.keys(): #Process received confirmation: index = container['received'] self.network.callback.handleMessage( messages.Confirmation(localID=self.localID, index=index) ) elif 'message' in container.keys(): index = container['index'] msg = container['message'] #print "Got message: ", str(msg.__class__) if isinstance(msg, messages.Connect): if not (self.localID is None): raise Exception("Received connect message while already connected") self.localID = msg.ID self.dice = msg.dice self.network.checkForDuplicateConnections(self.localID) else: #Send confirmation on non-connect messages: confirmation = {'received': index} self.send(serializable.serialize(confirmation) + '\n') #TODO: filter for acceptable message types, IDs etc. before #sending them to a general-purpose message handler self.network.callback.handleMessage(msg) else: log.log("Received message with invalid format") except Exception as e: log.logException()
def test_deserialize_with_missing_field(self): class Event1(EventBase): def __init__(self, fieldOne=None): super().__init__(fieldOne) self.fieldOne = fieldOne class Event2(EventBase): def __init__(self, fieldTwo=None): super().__init__(fieldTwo) self.fieldTwo = fieldTwo msg = Message() msg.push_event(Event1('one')) msg.push_event(Event2('two')) serialized = msg.serialize() print(serialized) mangled_serialized = serialized.replace('"fieldOne": "one"', '"bogus": "bogusness"') print(mangled_serialized) self.assertNotEqual(serialized, mangled_serialized) obj = deserialize(mangled_serialized) self.assertTrue(isinstance(obj, Message)) instance_dict = obj._traverse_dict(obj.__dict__) self.assertEqual('Event2', instance_dict['events'][-1]['eventType']) self.assertNotEqual(msg, obj) obj.get_event(Event1).fieldOne = 'one' msg.get_event(Event1).bogus = 'bogusness' self.assertEqual(msg, obj)
def test_message_batch_deserialize(self): class Event1(EventBase): pass class Event2(EventBase): pass class Event3(EventBase): pass msg = Message() msg.push_event(Event1()) msg.push_event(Event2()) msg2 = Message() msg2.push_event(Event2()) msg2.push_event(Event3()) batch = MessageBatch() batch.push_back(msg) batch.push_back(msg2) self.assertEqual(2, len(batch)) serialized = batch.serialize() obj = deserialize(serialized) self.assertTrue(isinstance(obj, MessageBatch)) instance_dict = obj._traverse_dict(obj.__dict__) print(instance_dict) self.assertEqual( 'Event1', instance_dict['messages'][0]['events'][0]['eventType']) self.assertEqual( 'Event3', instance_dict['messages'][-1]['events'][-1]['eventType']) self.assertEqual(batch, obj)
def test_none(self): class TestMessage(Serializable): def __init__(self, a=None, b=None): self.a = a self.b = b test = TestMessage(a='a') self.assertTrue(test.b is None) obj = deserialize(test.serialize()) self.assertEqual(test, obj) self.assertTrue(obj.b is None)
def test_event_type(self): class MyEventType(EventBase): def __init__(self, c): super().__init__(c) self.c = c event = MyEventType('c') event.mark_begin_timestamp() event.mark_end_timestamp() serialized = event.serialize() obj = deserialize(serialized) self.assertEqual(obj.event_type(), 'MyEventType') self.assertTrue(isinstance(obj, MyEventType)) self.assertEqual(event, obj)
def test_deserialize(self): class Event1(EventBase): pass class Event2(EventBase): pass msg = Message() msg.push_event(Event1()) msg.push_event(Event2()) serialized = msg.serialize() obj = deserialize(serialized) self.assertTrue(isinstance(obj, Message)) instance_dict = obj._traverse_dict(obj.__dict__) self.assertEqual('Event2', instance_dict['events'][-1]['eventType']) self.assertEqual(msg, obj)
def test_type(self): class Child(Serializable): def __init__(self, c): super().__init__(c) self.c = c class Parent(Serializable): def __init__(self, p, child): super().__init__(p, child) self.p = p self.child = child child = Child('c') parent = Parent('p', child) serialized = parent.serialize() obj = deserialize(serialized) self.assertEqual(obj.type(), 'Parent') self.assertEqual(obj.child.type(), 'Child')