def test_customSerialization(self): """ L{json.serialize} should emit JavaScript calls to the JavaScript object named by L{IAthenaTransportable.jsClass} with the arguments returned by L{IAthenaTransportable.getInitialArguments} when passed an object which can be adapted to L{IAthenaTransportable}. """ class Transportable(object): """ Completely parameterized L{IAthenaTransportable} implementation so different data can be easily tested. """ implements(IAthenaTransportable) def __init__(self, jsClass, initialArgs): self.jsClass = jsClass self.getInitialArguments = lambda: initialArgs self.assertEqual( json.serialize(Transportable(u"Foo", ())), "(new Foo())") self.assertEqual( json.serialize(Transportable(u"Bar", (None,))), "(new Bar(null))") self.assertEqual( json.serialize(Transportable(u"Baz.Quux", (1, 2))), "(new Baz.Quux(1,2))") # The style of the quotes in this assertion is basically irrelevant. # If, for some reason, the serializer changes to use ' instead of ", # there's no reason not to change this test to reflect that. -exarkun self.assertEqual( json.serialize(Transportable(u"Quux", (u"Foo",))), '(new Quux("Foo"))')
def _doubleLiveSerialization(self, cls, renderer): livePage = DummyLivePage() liveFragment = cls(docFactory=loaders.stan( tags.div(render=tags.directive(renderer))['Hello'])) liveFragment.setFragmentParent(livePage) self.assertEqual(json.serialize(liveFragment), json.serialize(liveFragment))
def test_customSerialization(self): """ L{json.serialize} should emit JavaScript calls to the JavaScript object named by L{IAthenaTransportable.jsClass} with the arguments returned by L{IAthenaTransportable.getInitialArguments} when passed an object which can be adapted to L{IAthenaTransportable}. """ class Transportable(object): """ Completely parameterized L{IAthenaTransportable} implementation so different data can be easily tested. """ implements(IAthenaTransportable) def __init__(self, jsClass, initialArgs): self.jsClass = jsClass self.getInitialArguments = lambda: initialArgs self.assertEqual(json.serialize(Transportable(u"Foo", ())), "(new Foo())") self.assertEqual(json.serialize(Transportable(u"Bar", (None, ))), "(new Bar(null))") self.assertEqual(json.serialize(Transportable(u"Baz.Quux", (1, 2))), "(new Baz.Quux(1,2))") # The style of the quotes in this assertion is basically irrelevant. # If, for some reason, the serializer changes to use ' instead of ", # there's no reason not to change this test to reflect that. -exarkun self.assertEqual(json.serialize(Transportable(u"Quux", (u"Foo", ))), '(new Quux("Foo"))')
def _doubleLiveSerialization(self, cls, renderer): livePage = DummyLivePage() liveFragment = cls( docFactory=loaders.stan( [tags.div(render=tags.directive(renderer))['Hello'], tags.div(render=tags.directive('foo'))])) liveFragment.setFragmentParent(livePage) self.assertEqual( json.serialize(liveFragment), json.serialize(liveFragment))
def test_lineTerminators(self): """ When passed a unicode string containing a line terminator, L{json.serialize} emits an escape sequence representing that character (not a UTF-8 sequence directly representing that the line terminator code point). Literal line terminators are allowed in JSON, but some parsers do not handle them properly. """ # These are the four line terminators currently in Unicode. self.assertEqual('"\\r"', json.serialize(u"\r")) self.assertEqual('"\\n"', json.serialize(u"\n")) self.assertEqual('"\\u2028"', json.serialize(u"\u2028")) self.assertEqual('"\\u2029"', json.serialize(u"\u2029"))
def test_lineTerminators(self): """ When passed a unicode string containing a line terminator, L{json.serialize} emits an escape sequence representing that character (not a UTF-8 sequence directly representing that the line terminator code point). Literal line terminators are allowed in JSON, but some parsers do not handle them properly. """ # These are the four line terminators currently in Unicode. self.assertEqual(u'"\\r"', json.serialize("\r")) self.assertEqual(u'"\\n"', json.serialize("\n")) self.assertEqual(u'"\\u2028"', json.serialize(u"\u2028")) self.assertEqual(u'"\\u2029"', json.serialize(u"\u2029"))
def child_history(self, ctx): cmds = list(self.cmdlog.recentCommands(10)) ret = [] for c, t, u in cmds: c = self.cmdlog.graph.label(c, default=c) ret.append((c, t, u)) return returnPage("text/javascript", json.serialize(ret))
def child_treeData(self, ctx): """extjs tree makes POST requests with a 'node' arg, and expects child node definitions http://extjs.com/deploy/dev/docs/output/Ext.tree.TreeLoader.html """ node = URIRef(ctx.arg('node')) ret = [] q = "SELECT ?child WHERE { ?child pho:inDirectory ?node . } ORDER BY ?child" for row in self.graph.queryd(q, initBindings={Variable('node') : node}): child = row['child'] leaf = not self.graph.contains((child, RDF.type, PHO['DiskDirectory'])) fmt = u'%s' isImage = self.graph.contains((child, RDF.type, FOAF['Image'])) viewable = self.graph.contains((child, PHO['viewableBy'], PHO['friends'])) if isImage and not viewable: fmt = u'<span class="access">%s</span>' ret.append({u'id' : child, u'text': fmt % self.graph.value(child, PHO['filename']), u'leaf': leaf}) if len(ret) > 500: ret.append({u'id' : u'', u'text' : u'(too many to show)', u'leaf' : True}) break return json.serialize(ret)
def testRoundtrip(self): for struct in TEST_OBJECTS: bytes = json.serialize(struct) unstruct = json.parse(bytes) self.assertEquals( unstruct, struct, "Failed to roundtrip %r: %r (through %r)" % (struct, unstruct, bytes))
def testStringlikeRountrip(self): for struct in TEST_STRINGLIKE_OBJECTS: bytes = json.serialize(struct) unstruct = json.parse(bytes) failMsg = "Failed to roundtrip %r: %r (through %r)" % ( struct, unstruct, bytes) self.assertEquals(unstruct, struct, failMsg) self.assert_(isinstance(unstruct, unicode), failMsg)
def child_tagSuggestion(self, ctx): print "req", ctx.arg('subj'), ctx.arg('tag') prefix = ctx.arg('tag') ret = [] for t in "apollo kelsi drew matthew rachel kathy mark brendan wily karin colin raelle rivven chris rosemary peter bonnie livingroom".split(): if t.startswith(prefix): ret.append(t.decode('utf-8')) return json.serialize(ret)
def testStringlikeRoundtrip(self): for struct in TEST_STRINGLIKE_OBJECTS: serialised = json.serialize(struct) deserialised = json.parse(serialised) failMsg = "Failed to roundtrip %r: %r (through %r)" % ( struct, deserialised, serialised) self.assertEqual(deserialised, struct, failMsg) self.assertTrue(isinstance(deserialised, compat.unicode), failMsg)
def testRoundtrip(self): for struct in TEST_OBJECTS: bytes = json.serialize(struct) unstruct = json.parse(bytes) self.assertEquals( unstruct, struct, "Failed to roundtrip %r: %r (through %r)" % ( struct, unstruct, bytes))
def renderHTTP(self, ctx): sensors = set() for row in (history[:10] + history[::10]): # hope we hit all the keys sensors.update(row.keys()) sensors.discard(u'time') sensors = sorted(sensors) return "(%s)" % json.serialize({ u'sensors' : sensors, u'temps' : history[-(ctx.arg('limit') or 0):]})
def formatChildren(result): ret = [] for child in result: name = child[1].decode('utf-8') base = name.rsplit('/',1)[-1] ret.append({u'id':name, u'text':base, u'leaf':child[0] == 'file'}) return json.serialize(ret)
def convert(result): if hasattr(result, 'jsonState'): ret = result.jsonState() else: ret = result log.debug("result %s", str(ret)[:1000]) try: return json.serialize(ret) except TypeError, e: # out of sync with mpd? let supervisor restart us raise SystemExit("result %r, error %r" % (result, e))
def _rewriteEventHandlerToAttribute(tag): """ Replace athena:handler children of the given tag with attributes on the tag which correspond to those event handlers. """ if isinstance(tag, stan.Tag): extraAttributes = {} for i in xrange(len(tag.children) - 1, -1, -1): if isinstance( tag.children[i], stan.Tag) and tag.children[i].tagName == 'athena:handler': info = tag.children.pop(i) name = info.attributes['event'].encode('ascii') handler = info.attributes['handler'] extraAttributes[name] = _handlerFormat % { 'handler': json.serialize(handler.decode('ascii')), 'event': json.serialize(name.decode('ascii')) } tag(**extraAttributes) return tag
def renderHTTP(self, ctx): sensors = set() for row in (history[:10] + history[::10]): # hope we hit all the keys sensors.update(row.keys()) sensors.discard(u'time') sensors = sorted(sensors) return "(%s)" % json.serialize( { u'sensors': sensors, u'temps': history[-(ctx.arg('limit') or 0):] })
def benchmark(iterations, scale): """ Deserialize a string C{iterations} times. Make the string longer based on C{scale}. Prints the mean time per parse call. """ s = serialize(BASE * scale) before = time() for i in range(iterations): parse(s) after = time() print((after - before) / iterations, 'per call')
def benchmark(iterations, scale): """ Deserialize a string C{iterations} times. Make the string longer based on C{scale}. Prints the mean time per parse call. """ s = serialize(BASE * scale) before = time() for i in xrange(iterations): parse(s) after = time() print (after - before) / iterations, 'per call'
def liveElement(self, request, tag): """ Render framework-level boilerplate for making sure the Widget for this Element is created and added to the page properly. """ requiredModules = self._getRequiredModules() # Add required attributes to the top widget node tag( **{ 'xmlns:athena': ATHENA_XMLNS_URI, 'id': 'athena:%d' % self._athenaID, 'athena:class': self.jsClass }) # This will only be set if _structured() is being run. if context.get('children') is not None: context.get('children').append({ u'class': self.jsClass, u'id': self._athenaID, u'initArguments': self.getInitialArguments() }) context.get('requiredModules').extend(requiredModules) return tag return ( # Import stuff [self.getImportStan(name) for (name, url) in requiredModules], # Dump some data for our client-side __init__ into a text area # where it can easily be found. tags.textarea(id='athena-init-args-' + str(self._athenaID), style="display: none") [json.serialize(self.getInitialArguments())], # Arrange to be instantiated tags.script(type='text/javascript') [""" Nevow.Athena.Widget._widgetNodeAdded(%(athenaID)d); """ % { 'athenaID': self._athenaID, 'pythonClass': self.__class__.__name__ }], # Okay, application stuff, plus metadata tag, )
def child_getMusicState(self, ctx): """returns a json object suitable for passing to setMusicState. The consumer will now have the same playlist and current song/position as the producer. post this with a stop=0 arg if you also want to stop the playback, which might be suitable if you're passing the playback from one mpd instance to another. The value to stop is the delay in seconds before stopping. """ req = inevow.IRequest(ctx) status = yield self.mpd.status() pl = yield self.mpd.playlistinfo() if ctx.arg('stop') is not None: if req.method != 'POST': raise ValueError("must use POST to affect playback") reactor.callLater(float(ctx.arg('stop')), self.mpd.stop) defer.returnValue(json.serialize({ u'status' : status.jsonState(), u'playlist' : pl.jsonState()}))
def child_treeData(self, ctx): """extjs tree makes POST requests with a 'node' arg, and expects child node definitions http://extjs.com/deploy/dev/docs/output/Ext.tree.TreeLoader.html """ node = URIRef(ctx.arg('node')) ret = [] q = "SELECT ?child WHERE { ?child pho:inDirectory ?node . } ORDER BY ?child" for row in self.graph.queryd(q, initBindings={Variable('node'): node}): child = row['child'] leaf = not self.graph.contains( (child, RDF.type, PHO['DiskDirectory'])) fmt = u'%s' isImage = self.graph.contains((child, RDF.type, FOAF['Image'])) viewable = self.graph.contains( (child, PHO['viewableBy'], PHO['friends'])) if isImage and not viewable: fmt = u'<span class="access">%s</span>' ret.append({ u'id': child, u'text': fmt % self.graph.value(child, PHO['filename']), u'leaf': leaf }) if len(ret) > 500: ret.append({ u'id': u'', u'text': u'(too many to show)', u'leaf': True }) break return json.serialize(ret)
def serialize(data): return json.serialize(sanitize(data))
def _ebOutput(self, err): msg = u"%s: %s" % (err.type.__name__, err.getErrorMessage()) return 'throw new Error(%s);' % (json.serialize(msg),)
def testSerialize(self): for struct in TEST_OBJECTS: json.serialize(struct)
def _doubleSerialization(self, cls): fragment = cls(docFactory=loaders.stan(tags.div['Hello'])) self.assertEqual(json.serialize(fragment), json.serialize(fragment))
def _rendererTest(self, cls): self.assertEquals( json.serialize( cls(docFactory=loaders.stan(tags.p['Hello, world.']))), '"<div xmlns=\\"http://www.w3.org/1999/xhtml\\"><p>Hello, world.</p></div>"' )
def _rendererTest(self, cls): self.assertEquals( json.serialize( cls( docFactory=loaders.stan(tags.p['Hello, world.']))), '"<div xmlns=\\"http://www.w3.org/1999/xhtml\\"><p>Hello, world.</p></div>"')
def renderHTTP(self, ctx): inevow.IRequest(ctx).setHeader("Content-Type", "application/json") host, port = self.mpd.conn.transport.addr return json.serialize({ u"host" : socket.gethostname().decode('ascii'), u"mpd" : {u"host" : host.decode('ascii'), u"port" : port}})
def render_lastFileData(self, ctx, data): if self.lastFile is None: return '' return json.serialize({u'id': self.lastFile.storeID, u'name': self.lastFile.name})
def _doubleSerialization(self, cls): fragment = cls(docFactory=loaders.stan(tags.div['Hello'])) self.assertEqual( json.serialize(fragment), json.serialize(fragment))
def findPlaylists(result): request = inevow.IRequest(ctx) request.setHeader("Content-Type", "application/json") return json.serialize({u'playlists' : [ {u'name' : row[1].decode('utf8')} for row in result if row[0] == 'playlist']})
def render_loadtree(self,ctx,data): return T.script(type='text/javascript')[T.raw(""" addLoadEvent(function() { Numbler.apidoc.loadTree('%s'); }); """ % json.serialize(list(self.stripfiles(self.displayTree))))]