def _encode(self, mod): element = mod.Element('foo', bar='baz') return ( pyamf.encode(element, encoding=pyamf.AMF0).getvalue(), pyamf.encode(element, encoding=pyamf.AMF3).getvalue() )
def test_amf3_encode(self): x = decimal.Decimal('1.23456463452345') self.assertEqual( pyamf.encode(x, encoding=pyamf.AMF3, strict=False).getvalue(), '\x05?\xf3\xc0\xc6\xd8\xa18\xfa') with self.assertRaises(pyamf.EncodeError): pyamf.encode(x, encoding=pyamf.AMF3, strict=True)
def test_amf3_encode(self): x = decimal.Decimal('1.23456463452345') self.assertEqual( pyamf.encode(x, encoding=pyamf.AMF3, strict=False).getvalue(), '\x05?\xf3\xc0\xc6\xd8\xa18\xfa' ) with self.assertRaises(pyamf.EncodeError): pyamf.encode(x, encoding=pyamf.AMF3, strict=True)
def test_CommandMessage(self): m = messages.CommandMessage() bytes = pyamf.encode(m.getSmallMessage(), encoding=pyamf.AMF3).getvalue() self.assertEquals(bytes, '\n\x07\x07DSC\x00\x01\x01\x01\x04\xce\x10') m = messages.CommandMessage(operation='foo.bar') bytes = pyamf.encode(m.getSmallMessage(), encoding=pyamf.AMF3).getvalue() self.assertEquals(bytes, '\n\x07\x07DSC\x00\x01\x01\x01\x06\x0ffoo.bar')
def test_default_encoding(self): pyamf.DEFAULT_ENCODING = pyamf.AMF3 x = pyamf.encode('foo').getvalue() self.assertEqual(x, '\x06\x07foo') pyamf.DEFAULT_ENCODING = pyamf.AMF0 x = pyamf.encode('foo').getvalue() self.assertEqual(x, '\x02\x00\x03foo')
def test_post_process(self): """ Ensure that postprocessing happens when data has been decoded. """ self.executed = False post_procs = pyamf.POST_DECODE_PROCESSORS[:] def restore_post_procs(): pyamf.POST_DECODE_PROCESSORS = post_procs self.addCleanup(restore_post_procs) pyamf.POST_DECODE_PROCESSORS = [] def postprocess(payload, context): self.assertEqual(payload, u'foo') self.assertEqual(context, {}) self.executed = True return payload pyamf.add_post_decode_processor(postprocess) # setup complete bytes = pyamf.encode(u'foo', encoding=pyamf.AMF0).getvalue() self.decoder.send(bytes) ret = next(self.decoder) self.assertTrue(self.executed) self.assertEqual(ret, u'foo')
def test_command(self): bytes = ('\n\x07\x07DSC\x88\x02\n\x0b\x01\tDSId\x06IEE0D161D-C11D-' '25CB-8DBE-3B77B54B55D9\x01\x0c!\xc0\xdf\xb7|\xd6\xee$1s\x152f' '\xe11\xa8f\x01\x06\x01\x01\x04\x02') self.buffer.write(bytes) self.buffer.seek(0) msg = self.decoder.readElement() self.assertTrue(isinstance(msg, small.CommandMessageExt)) self.assertEquals(msg.body, None) self.assertEquals(msg.destination, None) self.assertEquals(msg.timeToLive, None) self.assertEquals(msg.timestamp, None) self.assertEquals(msg.headers, { 'DSId': u'EE0D161D-C11D-25CB-8DBE-3B77B54B55D9' }) self.assertEquals(msg.clientId, None) self.assertEquals(msg.messageId, uuid.UUID('c0dfb77c-d6ee-2431-7315-3266e131a866')) self.assertEquals(msg.correlationId, u'') self.assertEquals(self.buffer.remaining(), 0) # now encode the msg to check that encoding is byte for byte the same buffer = pyamf.encode(msg, encoding=pyamf.AMF3).getvalue() self.assertEquals(buffer, bytes)
def test_command(self): bytes = ( '\n\x07\x07DSC\x88\x02\n\x0b\x01\tDSId\x06IEE0D161D-C11D-' '25CB-8DBE-3B77B54B55D9\x01\x0c!\xc0\xdf\xb7|\xd6\xee$1s\x152f' '\xe11\xa8f\x01\x06\x01\x01\x04\x02') self.buffer.write(bytes) self.buffer.seek(0) msg = self.decoder.readElement() self.assertTrue(isinstance(msg, messaging.CommandMessageExt)) self.assertEqual(msg.body, None) self.assertEqual(msg.destination, None) self.assertEqual(msg.timeToLive, None) self.assertEqual(msg.timestamp, None) self.assertEqual(msg.headers, {'DSId': 'EE0D161D-C11D-25CB-8DBE-3B77B54B55D9'}) self.assertEqual(msg.clientId, None) self.assertEqual(msg.messageId, uuid.UUID('c0dfb77c-d6ee-2431-7315-3266e131a866')) self.assertEqual(msg.correlationId, '') self.assertEqual(self.buffer.remaining(), 0) # now encode the msg to check that encoding is byte for byte the same buffer = pyamf.encode(msg, encoding=pyamf.AMF3).getvalue() self.assertEqual(buffer, bytes)
def save(self, out, format): """ """ # # Serialize # if format == "WKT": if "wkt" in self.content["crs"]: out.write(self.content["crs"]["wkt"]) else: out.write(_sref_4326().ExportToWkt()) return if format in ("GeoJSON", "GeoBSON", "GeoAMF"): content = self.content if "wkt" in content["crs"]: content["crs"] = {"type": "link", "properties": {"href": "0.wkt", "type": "ogcwkt"}} else: del content["crs"] elif format in ("ArcJSON", "ArcBSON", "ArcAMF"): content = reserialize_to_arc(self.content, format == "ArcAMF") else: raise KnownUnknown( 'Vector response only saves .geojson, .arcjson, .geobson, .arcbson, .geoamf, .arcamf and .wkt tiles, not "%s"' % format ) # # Encode # if format in ("GeoJSON", "ArcJSON"): indent = self.verbose and 2 or None encoded = JSONEncoder(indent=indent).iterencode(content) float_pat = compile(r"^-?\d+\.\d+$") for atom in encoded: if float_pat.match(atom): out.write("%.6f" % float(atom)) else: out.write(atom) elif format in ("GeoBSON", "ArcBSON"): import bson encoded = bson.dumps(content) out.write(encoded) elif format in ("GeoAMF", "ArcAMF"): import pyamf for class_name in pyamf_classes.items(): pyamf.register_class(*class_name) encoded = pyamf.encode(content, 0).read() out.write(encoded)
def test_amf3_encode(self): x = sets.ImmutableSet(['1', '2', '3']) self.assertTrue( check_buffer( pyamf.encode(x, encoding=pyamf.AMF3).getvalue(), ('\t\x07\x01', ('\x06\x031', '\x06\x033', '\x06\x032'))))
def test_dynamic_property_referenced_object(self): class Author(db.Model): name = db.StringProperty() class Novel(db.Model): title = db.StringProperty() author = db.ReferenceProperty(Author) try: a = Author(name='Jane Austen') a.put() b = Novel(title='Sense and Sensibility', author=a) b.put() x = Novel.all().filter('title = ', 'Sense and Sensibility').get() foo = [1, 2, 3] x.author.bar = foo k = str(x.key()) l = str(x.author.key()) stream = pyamf.encode(x) self.assertEquals(stream.getvalue(), '\x03\x00\x04_key\x02%s%s' '\x00\x06author\x03\x00\x04_key\x02%s%s\x00\x04name\x02\x00' '\x0bJane Austen\x00\x03bar\n\x00\x00\x00\x03\x00?\xf0\x00' '\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00@' '\x08\x00\x00\x00\x00\x00\x00\x00\x00\t\x00\x05title\x02\x00' '\x15Sense and Sensibility\x00\x00\t' % ( struct.pack('>H', len(k)), k, struct.pack('>H', len(l)), l)) finally: a.delete() b.delete()
def test_acknowledge(self): bytes = ('\n\x07\x07DSK\xa8\x03\n\x0b\x01%DSMessagingVersion\x05?\xf0' '\x00\x00\x00\x00\x00\x00\tDSId\x06IEE0D161D-C11D-25CB-8DBE-3B77B' '54B55D9\x01\x05Br3&m\x85\x10\x00\x0c!\xee\r\x16\x1d\xc1(&[\xc9' '\x80RK\x9bE\xc6\xc4\x0c!\xee\r\x16\x1d\xc1=\x8e\xa3\xe0\x10\xef' '\xad;\xe5\xc5j\x02\x0c!S\x84\x83\xdb\xa9\xc8\xcaM`\x952f\xdbQ' '\xc9<\x00') self.buffer.write(bytes) self.buffer.seek(0) msg = self.decoder.readElement() self.assertTrue(isinstance(msg, messaging.AcknowledgeMessageExt)) self.assertEqual(msg.body, None) self.assertEqual(msg.destination, None) self.assertEqual(msg.timeToLive, None) self.assertEqual(msg.timestamp, datetime.datetime(2009, 8, 19, 11, 24, 43, 985000)) self.assertEqual(msg.headers, { 'DSMessagingVersion': 1.0, 'DSId': u'EE0D161D-C11D-25CB-8DBE-3B77B54B55D9' }) self.assertEqual(msg.clientId, uuid.UUID('ee0d161d-c128-265b-c980-524b9b45c6c4')) self.assertEqual(msg.messageId, uuid.UUID('ee0d161d-c13d-8ea3-e010-efad3be5c56a')) self.assertEqual(msg.correlationId, uuid.UUID('538483db-a9c8-ca4d-6095-3266db51c93c')) self.assertEqual(self.buffer.remaining(), 0) # now encode the msg to check that encoding is byte for byte the same buffer = pyamf.encode(msg, encoding=pyamf.AMF3).getvalue() self.assertEqual(buffer, bytes)
def test_acknowledge(self): bytes = ('\n\x07\x07DSK\xa8\x03\n\x0b\x01%DSMessagingVersion\x05?\xf0' '\x00\x00\x00\x00\x00\x00\tDSId\x06IEE0D161D-C11D-25CB-8DBE-3B77B' '54B55D9\x01\x05Br3&m\x85\x10\x00\x0c!\xee\r\x16\x1d\xc1(&[\xc9' '\x80RK\x9bE\xc6\xc4\x0c!\xee\r\x16\x1d\xc1=\x8e\xa3\xe0\x10\xef' '\xad;\xe5\xc5j\x02\x0c!S\x84\x83\xdb\xa9\xc8\xcaM`\x952f\xdbQ' '\xc9<\x00') self.buffer.write(bytes) self.buffer.seek(0) msg = self.decoder.readElement() self.assertTrue(isinstance(msg, messaging.AcknowledgeMessageExt)) self.assertEqual(msg.body, None) self.assertEqual(msg.destination, None) self.assertEqual(msg.timeToLive, None) self.assertEqual(msg.timestamp, datetime.datetime(2009, 8, 19, 11, 24, 43, 985000)) self.assertEqual(msg.headers, { 'DSMessagingVersion': 1.0, 'DSId': 'EE0D161D-C11D-25CB-8DBE-3B77B54B55D9' }) self.assertEqual(msg.clientId, uuid.UUID('ee0d161d-c128-265b-c980-524b9b45c6c4')) self.assertEqual(msg.messageId, uuid.UUID('ee0d161d-c13d-8ea3-e010-efad3be5c56a')) self.assertEqual(msg.correlationId, uuid.UUID('538483db-a9c8-ca4d-6095-3266db51c93c')) self.assertEqual(self.buffer.remaining(), 0) # now encode the msg to check that encoding is byte for byte the same buffer = pyamf.encode(msg, encoding=pyamf.AMF3).getvalue() self.assertEqual(buffer, bytes)
def test_post_process(self): """ Ensure that postprocessing happens when data has been decoded. """ self.executed = False post_procs = pyamf.POST_DECODE_PROCESSORS[:] def restore_post_procs(): pyamf.POST_DECODE_PROCESSORS = post_procs self.addCleanup(restore_post_procs) pyamf.POST_DECODE_PROCESSORS = [] def postprocess(payload, context): self.assertEqual(payload, u'foo') self.assertEqual(context, {}) self.executed = True return payload pyamf.add_post_decode_processor(postprocess) # setup complete bytes = pyamf.encode(u'foo', encoding=pyamf.AMF0).getvalue() self.decoder.send(bytes) ret = self.decoder.next() self.assertTrue(self.executed) self.assertEqual(ret, u'foo')
def test_referenced_encode(self): f = self.ParentReference() f.name = "foo" b = self.ChildReference() b.name = "bar" f.save() b.foo = f b.save() f.bar = b f.save() self.assertEquals(f.id, 2) foo = self.ParentReference.objects.select_related().get(id=2) # ensure the referenced attribute resolves foo.bar.foo self.assertEquals( pyamf.encode(foo).getvalue(), "\x03\x00\x02id\x00" "@\x00\x00\x00\x00\x00\x00\x00\x00\x04name\x02\x00\x03foo\x00" "\x03bar\x03\x00\x02id\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x04na" "me\x02\x00\x03bar\x00\x03foo\x07\x00\x00\x00\x00\t\x00\x00\t", )
def test_encode(self): from django.utils.translation import ugettext_lazy self.assertEqual( pyamf.encode(ugettext_lazy('Hello')).getvalue(), '\x06\x0bHello' )
def test_RemotingMessage(self): m = messaging.RemotingMessage(source='foo.bar') self.assertEqual(pyamf.encode(m).getvalue(), '\n\x81\x1bOflex.messaging.messages.RemotingMessage\x15timeToLive' '\x13timestamp\x13messageId\x0fheaders\x17destination\x11clientId' '\tbody\x13operation\rsource\x01\x01\x01\n\x0b\x01\x01\x01\x01\x01' '\x01\x06\x0ffoo.bar\x01')
def test_amf3_encode(self): x = sets.ImmutableSet(["1", "2", "3"]) self.assertTrue( check_buffer( pyamf.encode(x, encoding=pyamf.AMF3).getvalue(), ("\t\x07\x01", ("\x06\x031", "\x06\x033", "\x06\x032")) ) )
def test_CommandMessage(self): m = messaging.CommandMessage(operation='foo.bar') self.assertEqual(pyamf.encode(m).getvalue(), '\n\x81\x1bMflex.messaging.messages.CommandMessage\x1bcorrelationId' '\tbody\x11clientId\x17destination\x0fheaders\x13messageId\x13' 'timestamp\x15timeToLive\x13operation\x01\x01\x01\x01\n\x0b\x01\x01' '\x01\x01\x01\x06\x0ffoo.bar\x01')
def test_Query_type(self): """ L{db.Query} instances get converted to lists .. """ q = PetModel.all() self.assertTrue(isinstance(q, db.Query)) self.assertEquals(pyamf.encode(q).getvalue(), '\n\x00\x00\x00\x00')
def test_amf0_encode(self): x = sets.ImmutableSet(['1', '2', '3']) self.assertTrue( check_buffer( pyamf.encode(x, encoding=pyamf.AMF0).getvalue(), ('\n\x00\x00\x00\x03', ('\x02\x00\x011', '\x02\x00\x013', '\x02\x00\x012'))))
def test_amf0_encode(self): x = decimal.Decimal("1.23456463452345") self.assertEqual( pyamf.encode(x, encoding=pyamf.AMF0, strict=False).getvalue(), "\x00?\xf3\xc0\xc6\xd8\xa18\xfa" ) self.assertRaises(pyamf.EncodeError, pyamf.encode, x, encoding=pyamf.AMF0, strict=True)
def test_Query_type(self): """ L{db.Query} instances get converted to lists .. """ q = PetModel.all() self.assertTrue(isinstance(q, db.Query)) self.assertEquals(pyamf.encode(q).getvalue(), "\n\x00\x00\x00\x00")
def save(self, out, format): """ """ # # Serialize # if format == 'WKT': if 'wkt' in self.content['crs']: out.write(self.content['crs']['wkt']) else: out.write(_sref_4326().ExportToWkt()) return if format in ('GeoJSON', 'GeoBSON', 'GeoAMF'): content = self.content if 'wkt' in content['crs']: content['crs'] = {'type': 'link', 'properties': {'href': '0.wkt', 'type': 'ogcwkt'}} else: del content['crs'] elif format in ('ArcJSON', 'ArcBSON', 'ArcAMF'): content = reserialize_to_arc(self.content, format == 'ArcAMF') else: raise KnownUnknown('Vector response only saves .geojson, .arcjson, .geobson, .arcbson, .geoamf, .arcamf and .wkt tiles, not "%s"' % format) # # Encode # if format in ('GeoJSON', 'ArcJSON'): indent = self.verbose and 2 or None encoded = JSONEncoder(indent=indent).iterencode(content) float_pat = compile(r'^-?\d+\.\d+$') for atom in encoded: if float_pat.match(atom): piece = ('%%.%if' % self.precision) % float(atom) else: piece = atom out.write(piece.encode('utf8')) elif format in ('GeoBSON', 'ArcBSON'): import bson encoded = bson.dumps(content) out.write(encoded) elif format in ('GeoAMF', 'ArcAMF'): import pyamf for class_name in pyamf_classes.items(): pyamf.register_class(*class_name) encoded = pyamf.encode(content, 0).read() out.write(encoded)
def test_AcknowledgeMessage(self): m = messaging.AcknowledgeMessage() m.correlationId = '1234' self.assertEqual(pyamf.encode(m).getvalue(), '\n\x81\x0bUflex.messaging.messages.AcknowledgeMessage\tbody' '\x11clientId\x17destination\x0fheaders\x13messageId\x13timestamp' '\x15timeToLive\x1bcorrelationId\x01\x01\x01\n\x0b\x01\x01\x01\x01' '\x01\x06\t1234\x01')
def test_ErrorMessage(self): m = messaging.ErrorMessage(faultString='ValueError') self.assertEqual(pyamf.encode(m).getvalue(), '\n\x81[Iflex.messaging.messages.ErrorMessage\x1bcorrelationId\x15' 'timeToLive\x13timestamp\x13messageId\x0fheaders\x17destination' '\x11clientId\tbody\x19extendedData\x13faultCode\x17faultDetail' '\x17faultString\x13rootCause\x01\x01\x01\x01\n\x0b\x01\x01\x01' '\x01\x01\n\x05\x01\x01\x01\x06\x15ValueError\n\x05\x01\x01')
def assertEncodes(self, obj, buffer, encoding=pyamf.AMF3): bytes = pyamf.encode(obj, encoding=encoding).getvalue() if isinstance(buffer, basestring): self.assertEqual(bytes, buffer) return self.assertBuffer(bytes, buffer)
def test_NOT_PROVIDED(self): from django.db.models import fields self.assertEqual(pyamf.encode(fields.NOT_PROVIDED, encoding=pyamf.AMF0).getvalue(), '\x06') encoder = pyamf.get_encoder(pyamf.AMF3) encoder.writeElement(fields.NOT_PROVIDED) self.assertEqual(encoder.stream.getvalue(), '\x00')
def assertEncodes(self, obj, buffer, encoding=pyamf.AMF3): bytes = pyamf.encode(obj, encoding=encoding).getvalue() if isinstance(buffer, six.string_types): self.assertEqual(bytes, buffer) return self.assertBuffer(bytes, buffer)
def test_amf0_encode(self): x = sets.ImmutableSet(["1", "2", "3"]) self.assertTrue( check_buffer( pyamf.encode(x, encoding=pyamf.AMF0).getvalue(), ("\n\x00\x00\x00\x03", ("\x02\x00\x011", "\x02\x00\x013", "\x02\x00\x012")), ) )
def write(self): """ Encode packet into bytes. @return: representation of packet @rtype: C{str} """ buf = pyamf.encode(self.name, self.id, *self.argv, encoding=pyamf.AMF0) self.header.length = len(buf) return buf.read()
def sendmessage(self, command, data): msg = {'cmd': command, 'data': data} if self.__callback != None: self.__callback(msg) else: print(msg) msg = pyamf.encode(msg).read() size = len(msg) msg = (struct.pack('>L', size)) + msg self.server.sendall(msg)
def test_RemotingMessage(self): m = messaging.RemotingMessage(source="foo.bar") self.assertEquals( pyamf.encode(m).getvalue(), "\x11\n\x81\x13Oflex.messaging.messages.RemotingMessage\x13" "operation\rsource\tbody\x11clientId\x17destination\x0fheaders\x13" "messageId\x15timeToLive\x13timestamp\x01\x06\x0ffoo.bar\x01\x01" "\x01\n\x0b\x01\x01\x01\x04\x00\x04\x00", )
def test_no_pk(self): """ Ensure that Models without a primary key are correctly serialized. See #691. """ instances = [models.NotSaved(name="a"), models.NotSaved(name="b")] encoded = pyamf.encode(instances, encoding=pyamf.AMF3).getvalue() decoded = pyamf.decode(encoded, encoding=pyamf.AMF3).next() self.assertEqual(decoded[0]['name'], 'a') self.assertEqual(decoded[1]['name'], 'b')
def test_amf3_encode(self): x = sets.ImmutableSet(['1', '2', '3']) self.assertTrue(check_buffer( pyamf.encode(x, encoding=pyamf.AMF3).getvalue(), ( '\t\x07\x01', ( '\x06\x031', '\x06\x033', '\x06\x032' )) ))
def test_amf0_encode(self): x = sets.ImmutableSet(['1', '2', '3']) self.assertTrue(check_buffer( pyamf.encode(x, encoding=pyamf.AMF0).getvalue(), ( '\n\x00\x00\x00\x03', ( '\x02\x00\x011', '\x02\x00\x013', '\x02\x00\x012' )) ))
def test_AcknowledgeMessage(self): m = messaging.AcknowledgeMessage() m.correlationId = "1234" self.assertEquals( pyamf.encode(m).getvalue(), "\x11\n\x81\x03Uflex.messaging.messages.AcknowledgeMessage" "\x1bcorrelationId\tbody\x11clientId\x17destination\x0fheaders\x13" "messageId\x15timeToLive\x13timestamp\x06\t1234\x01\x01\x01\n\x0b" "\x01\x01\x01\x04\x00\x04\x00", )
def test_no_pk(self): """ Ensure that Models without a primary key are correctly serialized. See #691. """ instances = [models.NotSaved(name="a"), models.NotSaved(name="b")] encoded = pyamf.encode(instances, encoding=pyamf.AMF3).getvalue() decoded = next(pyamf.decode(encoded, encoding=pyamf.AMF3)) self.assertEqual(decoded[0]['name'], 'a') self.assertEqual(decoded[1]['name'], 'b')
def test_CommandMessage(self): m = messaging.CommandMessage(operation="foo.bar") self.assertEquals( pyamf.encode(m).getvalue(), "\x11\n\x81#Mflex.messaging.messages.CommandMessage\x13operation" "\x1dmessageRefType\x1bcorrelationId\tbody\x11clientId\x17" "destination\x0fheaders\x13messageId\x15timeToLive\x13timestamp" "\x06\x0ffoo.bar\x01\x01\x01\x01\x01\n\x0b\x01\x01\x01\x04\x00" "\x04\x00", )
def test_amf3_encode(self): x = frozenset(['1', '2', '3']) self.assertTrue(check_buffer( pyamf.encode(x, encoding=pyamf.AMF3).getvalue(), ( b'\t\x07\x01', ( b'\x06\x031', b'\x06\x033', b'\x06\x032' ) ) ))
def amf(self, tables, path=None, upload=False, tags='', summary=None): amf = pyamf.encode( dict([(t, self.table[t].__amf__()) for t in tables]) ).read() temp = path or 'balance_%s_%s.amf' % self.summary() f = open(temp, 'wb') f.write(amf) f.close() if upload: a = self.upload(temp, tags) os.remove(temp) return a
def test_amf0_encode(self): x = frozenset(['1', '2', '3']) self.assertTrue(check_buffer( pyamf.encode(x, encoding=pyamf.AMF0).getvalue(), ( b'\n\x00\x00\x00\x03', ( b'\x02\x00\x011', b'\x02\x00\x013', b'\x02\x00\x012' ) ) ))
def test_alias_amf0(self): pyamf.register_class(test_models.PetExpando, 'Pet') bytes = pyamf.encode(self.jessica, encoding=pyamf.AMF0).getvalue() self.assertBuffer(bytes, ('\x10\x00\x03Pet', ( '\x00\x04_key%s' % self.encodeKey(self.jessica, pyamf.AMF0), '\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00\x00\x00\x00\x00', '\x00\x04name\x02\x00\x07Jessica', '\x00\x12spayed_or_neutered\x01\x00', '\x00\x04type\x02\x00\x03cat', '\x00\x10weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00', '\x00\x03foo\x02\x00\x03bar'), '\x00\x00\t'))
def test_numerical_keys_mixed_array(self): """ Numerical keys in L{pyamf.MixedArray} must not cause a KeyError on decode. @see: #843 """ x = pyamf.MixedArray({'10': u'foobar'}) bytes = pyamf.encode(x, encoding=pyamf.AMF0) d = list(pyamf.decode(bytes, encoding=pyamf.AMF0)) self.assertEqual(d, [{10: u'foobar'}])
def test_save_amf0(self): self.put(self.jessica) bytes = pyamf.encode(self.jessica, encoding=pyamf.AMF0).getvalue() self.assertBuffer(bytes, ('\x03', ( '\x00\x04_key%s' % self.encodeKey(self.jessica, pyamf.AMF0), '\x00\tbirthdate\x0bB^\xc4\xae\xaa\x00\x00\x00\x00\x00', '\x00\x04name\x02\x00\x07Jessica', '\x00\x12spayed_or_neutered\x01\x00', '\x00\x04type\x02\x00\x03cat', '\x00\x10weight_in_pounds\x00@\x14\x00\x00\x00\x00\x00\x00', '\x00\x03foo\x02\x00\x03bar'), '\x00\x00\t'))
def test_ioerror_buffer_position(self): """ Test to ensure that if an IOError is raised by `readElement` that the original position of the stream is restored. """ bytes = pyamf.encode('foo', [1, 2, 3], encoding=pyamf.AMF0).getvalue() self.buf.write(bytes[:-1]) self.buf.seek(0) self.decoder.readElement() self.assertEqual(self.buf.tell(), 6) self.assertRaises(IOError, self.decoder.readElement) self.assertEqual(self.buf.tell(), 6)
def debugstring(self): tr = self.sender.registernewplayer()['data']['player'] tr['castles'][0]['troopqueued'] = self.troopqueued tr['castles'][0]['researches'] = self.researches trr = pyamf.encode(tr).read() trr = zlib.compress(trr) trr = base64.b64encode(trr) z = { 'accname': self.player['accountName'], 'summary_resources': self.getresourcesummary(), 'summary_troops': self.gettroopsummary(), 'summary_attacks': 0, 'summary_username': self.player['userName'], 'player': trr, 'server': 'Falx (na59)', 'warlog': '' } return z
def test_amf3(self): """ Test encoding in AMF3. """ import pyamf ref_dict = { 'level': 'alevel', 'code': 'Some.Code.Here', 'description': 'Look mom, no hands!' } s = status.Status(ref_dict['level'], ref_dict['code'], ref_dict['description']) blob = pyamf.encode(s, encoding=pyamf.AMF3) decoded_status = pyamf.decode(blob, encoding=pyamf.AMF3).next() self.assertEqual(decoded_status, s)
def test_one_to_many(self): # initialise the db .. r = models.Reporter(first_name='John', last_name='Smith', email='*****@*****.**') r.save() self.addCleanup(r.delete) r2 = models.Reporter(first_name='Paul', last_name='Jones', email='*****@*****.**') r2.save() self.addCleanup(r2.delete) a = models.Article(headline="This is a test", reporter=r) a.save() self.addCleanup(a.delete) self.assertEqual(a.id, 1) del a a = models.Article.objects.filter(pk=1)[0] self.assertFalse('_reporter_cache' in a.__dict__) a.reporter self.assertTrue('_reporter_cache' in a.__dict__) del a a = models.Article.objects.filter(pk=1)[0] alias = adapter.DjangoClassAlias(models.Article, defer=True) self.assertFalse(hasattr(alias, 'fields')) attrs = alias.getEncodableAttributes(a) # note that the reporter attribute does not exist. self.assertEqual(attrs, { 'headline': 'This is a test', 'id': 1, 'publications': [] }) self.assertFalse('_reporter_cache' in a.__dict__) self.assertEqual( pyamf.encode(a, encoding=pyamf.AMF3).getvalue(), '\n\x0b\x01\x11headline\x06\x1dThis is a test\x05id\x04\x01' '\x19publications\t\x01\x01\x01') del a # now with select_related to pull in the reporter object a = models.Article.objects.select_related('reporter').filter(pk=1)[0] alias = adapter.DjangoClassAlias(models.Article, defer=True) self.assertFalse(hasattr(alias, 'fields')) self.assertEqual( alias.getEncodableAttributes(a), { 'headline': 'This is a test', 'id': 1, 'reporter': r, 'publications': [] }) self.assertTrue('_reporter_cache' in a.__dict__) self.assertEqual( pyamf.encode(a, encoding=pyamf.AMF3).getvalue(), '\n\x0b\x01\x11reporter\n\x0b\x01\x15first_name\x06\tJohn\x13' 'last_name\x06\x0bSmith\x05id\x04\x01\x0bemail\x06!john' '@example.com\x01\x11headline\x06\x1dThis is a test\x19' 'publications\t\x01\x01\n\x04\x01\x01')
def test_encode(self): self.assertEqual( '\x06\x0fconnect\x05?\xf0\x00\x00\x00\x00\x00\x00', pyamf.encode(u'connect', 1.0).getvalue() )