How to use json_safe method in localstack

Best Python code snippet using localstack_python

siesta_test.py

Source:siesta_test.py Github

copy

Full Screen

1#!/usr/bin/python2## $LicenseInfo:firstyear=2011&license=viewerlgpl$3## Second Life Viewer Source Code4## Copyright (C) 2011, Linden Research, Inc.5## 6## This library is free software; you can redistribute it and/or7## modify it under the terms of the GNU Lesser General Public8## License as published by the Free Software Foundation;9## version 2.1 of the License only.10## 11## This library is distributed in the hope that it will be useful,12## but WITHOUT ANY WARRANTY; without even the implied warranty of13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU14## Lesser General Public License for more details.15## 16## You should have received a copy of the GNU Lesser General Public17## License along with this library; if not, write to the Free Software18## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA19## 20## Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA21## $/LicenseInfo$22from indra.base import llsd, lluuid23from indra.ipc import siesta24import datetime, math, unittest25from webob import exc26class ClassApp(object):27 def handle_get(self, req):28 pass29 def handle_post(self, req):30 return req.llsd31 32def callable_app(req):33 if req.method == 'UNDERPANTS':34 raise exc.HTTPMethodNotAllowed()35 elif req.method == 'GET':36 return None37 return req.llsd38class TestBase:39 def test_basic_get(self):40 req = siesta.Request.blank('/')41 self.assertEquals(req.get_response(self.server).body,42 llsd.format_xml(None))43 44 def test_bad_method(self):45 req = siesta.Request.blank('/')46 req.environ['REQUEST_METHOD'] = 'UNDERPANTS'47 self.assertEquals(req.get_response(self.server).status_int,48 exc.HTTPMethodNotAllowed.code)49 50 json_safe = {51 'none': None,52 'bool_true': True,53 'bool_false': False,54 'int_zero': 0,55 'int_max': 2147483647,56 'int_min': -2147483648,57 'long_zero': 0,58 'long_max': 2147483647L,59 'long_min': -2147483648L,60 'float_zero': 0,61 'float': math.pi,62 'float_huge': 3.14159265358979323846e299,63 'str_empty': '',64 'str': 'foo',65 u'unic\u1e51de_empty': u'',66 u'unic\u1e51de': u'\u1e4exx\u10480',67 }68 json_safe['array'] = json_safe.values()69 json_safe['tuple'] = tuple(json_safe.values())70 json_safe['dict'] = json_safe.copy()71 json_unsafe = {72 'uuid_empty': lluuid.UUID(),73 'uuid_full': lluuid.UUID('dc61ab0530200d7554d23510559102c1a98aab1b'),74 'binary_empty': llsd.binary(),75 'binary': llsd.binary('f\0\xff'),76 'uri_empty': llsd.uri(),77 'uri': llsd.uri('http://www.secondlife.com/'),78 'datetime_empty': datetime.datetime(1970,1,1),79 'datetime': datetime.datetime(1999,9,9,9,9,9),80 }81 json_unsafe.update(json_safe)82 json_unsafe['array'] = json_unsafe.values()83 json_unsafe['tuple'] = tuple(json_unsafe.values())84 json_unsafe['dict'] = json_unsafe.copy()85 json_unsafe['iter'] = iter(json_unsafe.values())86 def _test_client_content_type_good(self, content_type, ll):87 def run(ll):88 req = siesta.Request.blank('/')89 req.environ['REQUEST_METHOD'] = 'POST'90 req.content_type = content_type91 req.llsd = ll92 req.accept = content_type93 resp = req.get_response(self.server)94 self.assertEquals(resp.status_int, 200)95 return req, resp96 97 if False and isinstance(ll, dict):98 def fixup(v):99 if isinstance(v, float):100 return '%.5f' % v101 if isinstance(v, long):102 return int(v)103 if isinstance(v, (llsd.binary, llsd.uri)):104 return v105 if isinstance(v, (tuple, list)):106 return [fixup(i) for i in v]107 if isinstance(v, dict):108 return dict([(k, fixup(i)) for k, i in v.iteritems()])109 return v110 for k, v in ll.iteritems():111 l = [k, v]112 req, resp = run(l)113 self.assertEquals(fixup(resp.llsd), fixup(l))114 run(ll)115 def test_client_content_type_json_good(self):116 self._test_client_content_type_good('application/json', self.json_safe)117 def test_client_content_type_llsd_xml_good(self):118 self._test_client_content_type_good('application/llsd+xml',119 self.json_unsafe)120 def test_client_content_type_llsd_notation_good(self):121 self._test_client_content_type_good('application/llsd+notation',122 self.json_unsafe)123 def test_client_content_type_llsd_binary_good(self):124 self._test_client_content_type_good('application/llsd+binary',125 self.json_unsafe)126 def test_client_content_type_xml_good(self):127 self._test_client_content_type_good('application/xml',128 self.json_unsafe)129 def _test_client_content_type_bad(self, content_type):130 req = siesta.Request.blank('/')131 req.environ['REQUEST_METHOD'] = 'POST'132 req.body = '\0invalid nonsense under all encodings'133 req.content_type = content_type134 self.assertEquals(req.get_response(self.server).status_int,135 exc.HTTPBadRequest.code)136 137 def test_client_content_type_json_bad(self):138 self._test_client_content_type_bad('application/json')139 def test_client_content_type_llsd_xml_bad(self):140 self._test_client_content_type_bad('application/llsd+xml')141 def test_client_content_type_llsd_notation_bad(self):142 self._test_client_content_type_bad('application/llsd+notation')143 def test_client_content_type_llsd_binary_bad(self):144 self._test_client_content_type_bad('application/llsd+binary')145 def test_client_content_type_xml_bad(self):146 self._test_client_content_type_bad('application/xml')147 def test_client_content_type_bad(self):148 req = siesta.Request.blank('/')149 req.environ['REQUEST_METHOD'] = 'POST'150 req.body = 'XXX'151 req.content_type = 'application/nonsense'152 self.assertEquals(req.get_response(self.server).status_int,153 exc.HTTPUnsupportedMediaType.code)154 def test_request_default_content_type(self):155 req = siesta.Request.blank('/')156 self.assertEquals(req.content_type, req.default_content_type)157 def test_request_default_accept(self):158 req = siesta.Request.blank('/')159 from webob import acceptparse160 self.assertEquals(str(req.accept).replace(' ', ''),161 req.default_accept.replace(' ', ''))162 def test_request_llsd_auto_body(self):163 req = siesta.Request.blank('/')164 req.llsd = {'a': 2}165 self.assertEquals(req.body, '<?xml version="1.0" ?><llsd><map>'166 '<key>a</key><integer>2</integer></map></llsd>')167 def test_request_llsd_mod_body_changes_llsd(self):168 req = siesta.Request.blank('/')169 req.llsd = {'a': 2}170 req.body = '<?xml version="1.0" ?><llsd><integer>1337</integer></llsd>'171 self.assertEquals(req.llsd, 1337)172 def test_request_bad_llsd_fails(self):173 def crashme(ctype):174 def boom():175 class foo(object): pass176 req = siesta.Request.blank('/')177 req.content_type = ctype178 req.llsd = foo()179 for mime_type in siesta.llsd_parsers:180 self.assertRaises(TypeError, crashme(mime_type))181class ClassServer(TestBase, unittest.TestCase):182 def __init__(self, *args, **kwargs):183 unittest.TestCase.__init__(self, *args, **kwargs)184 self.server = siesta.llsd_class(ClassApp)185class CallableServer(TestBase, unittest.TestCase):186 def __init__(self, *args, **kwargs):187 unittest.TestCase.__init__(self, *args, **kwargs)188 self.server = siesta.llsd_callable(callable_app)189class RouterServer(unittest.TestCase):190 def test_router(self):191 def foo(req, quux):192 print quux193 r = siesta.Router()194 r.add('/foo/{quux:int}', siesta.llsd_callable(foo), methods=['GET'])195 req = siesta.Request.blank('/foo/33')196 req.get_response(r)197 req = siesta.Request.blank('/foo/bar')198 self.assertEquals(req.get_response(r).status_int,199 exc.HTTPNotFound.code)200 201if __name__ == '__main__':...

Full Screen

Full Screen

serializers.py

Source:serializers.py Github

copy

Full Screen

1from furl import furl2from datetime import datetime3from framework.utils import iso8601format4from dateutil import parser5from website.project.metadata.utils import serialize_meta_schema6from website.settings import DOMAIN as OSF_DOMAIN7EMBARGO = 'embargo'8IMMEDIATE = 'immediate'9CANCELED = 'canceled'10def serialize_user(user):11 return {12 'full_name': user.fullname,13 'username': user.username,14 'id': user._id15 }16# TODO: Write and use APIv2 serializer for this17def serialize_draft_registration(draft, json_safe=True):18 node_url = get_url(draft)19 embargo = get_embargo(draft, json_safe)20 submitted = None21 if draft.approval is not None:22 if json_safe:23 submitted = iso8601format(draft.approval.initiation_date)24 else:25 submitted = draft.approval.initiation_date26 return {27 'pk': draft._id,28 'initiator': serialize_user(draft.initiator),29 'registration_metadata': draft.registration_metadata,30 'registration_schema': serialize_meta_schema(draft.registration_schema),31 'initiated': iso8601format(draft.datetime_initiated) if json_safe else draft.datetime_initiated,32 'updated': iso8601format(draft.datetime_updated) if json_safe else draft.datetime_updated,33 'submitted': submitted,34 'requires_approval': draft.requires_approval,35 'is_pending_approval': draft.is_pending_review,36 'is_approved': draft.is_approved,37 'is_rejected': draft.is_rejected,38 'notes': draft.notes,39 'proof_of_publication': draft.flags.get('proof_of_publication'),40 'payment_sent': draft.flags.get('payment_sent'),41 'assignee': draft.flags.get('assignee'),42 'title': draft.registration_metadata['q1']['value'],43 'embargo': embargo,44 'registered_node': node_url,45 'status': get_approval_status(draft),46 'logs': map(serialize_draft_logs, draft.status_logs),47 }48def serialize_draft_logs(log):49 return '{} on {}'.format(log.action, datetime.strftime(log.date, '%c'))50def get_url(draft):51 url = furl(OSF_DOMAIN)52 if draft.registered_node is not None:53 url.path.add(draft.registered_node.url)54 return url.url55 elif draft.branched_from is not None:56 url.path.add(draft.branched_from.url)57 return url.url58 return None59def get_embargo(draft, json_safe):60 if draft.approval is not None:61 registration_choice = draft.approval.meta.get('registration_choice', None)62 if registration_choice == EMBARGO:63 time = parser.parse(draft.approval.meta['embargo_end_date'])64 return iso8601format(time) if json_safe else time65 return IMMEDIATE66 else:67 return CANCELED68def get_approval_status(draft):69 if draft.is_approved:70 if draft.registered_node is not None:71 if draft.registered_node.is_deleted:72 return 'Approved but canceled'73 if draft.registered_node.retraction is None:74 return 'Approved and registered'75 else:76 return 'Approved but withdrawn'77 return 'Approved but not registered'78 elif draft.is_rejected:79 return 'Rejected'80 else:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful