siesta_test.py
上传用户:king477883
上传日期:2021-03-01
资源大小:9553k
文件大小:9k
源码类别:

游戏引擎

开发平台:

C++ Builder

  1. """
  2. @file siesta_test.py
  3. @brief 
  4. $LicenseInfo:firstyear=2007&license=mit$
  5. Copyright (c) 2007-2010, Linden Research, Inc.
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. $/LicenseInfo$
  22. """
  23. from indra.base import llsd, lluuid
  24. from indra.ipc import siesta
  25. import datetime, math, unittest
  26. from webob import exc
  27. class ClassApp(object):
  28.     def handle_get(self, req):
  29.         pass
  30.     def handle_post(self, req):
  31.         return req.llsd
  32.     
  33. def callable_app(req):
  34.     if req.method == 'UNDERPANTS':
  35.         raise exc.HTTPMethodNotAllowed()
  36.     elif req.method == 'GET':
  37.         return None
  38.     return req.llsd
  39. class TestBase:
  40.     def test_basic_get(self):
  41.         req = siesta.Request.blank('/')
  42.         self.assertEquals(req.get_response(self.server).body,
  43.                           llsd.format_xml(None))
  44.         
  45.     def test_bad_method(self):
  46.         req = siesta.Request.blank('/')
  47.         req.environ['REQUEST_METHOD'] = 'UNDERPANTS'
  48.         self.assertEquals(req.get_response(self.server).status_int,
  49.                           exc.HTTPMethodNotAllowed.code)
  50.         
  51.     json_safe = {
  52.         'none': None,
  53.         'bool_true': True,
  54.         'bool_false': False,
  55.         'int_zero': 0,
  56.         'int_max': 2147483647,
  57.         'int_min': -2147483648,
  58.         'long_zero': 0,
  59.         'long_max': 2147483647L,
  60.         'long_min': -2147483648L,
  61.         'float_zero': 0,
  62.         'float': math.pi,
  63.         'float_huge': 3.14159265358979323846e299,
  64.         'str_empty': '',
  65.         'str': 'foo',
  66.         u'unicu1e51de_empty': u'',
  67.         u'unicu1e51de': u'u1e4exxu10480',
  68.         }
  69.     json_safe['array'] = json_safe.values()
  70.     json_safe['tuple'] = tuple(json_safe.values())
  71.     json_safe['dict'] = json_safe.copy()
  72.     json_unsafe = {
  73.         'uuid_empty': lluuid.UUID(),
  74.         'uuid_full': lluuid.UUID('dc61ab0530200d7554d23510559102c1a98aab1b'),
  75.         'binary_empty': llsd.binary(),
  76.         'binary': llsd.binary('fxff'),
  77.         'uri_empty': llsd.uri(),
  78.         'uri': llsd.uri('http://www.secondlife.com/'),
  79.         'datetime_empty': datetime.datetime(1970,1,1),
  80.         'datetime': datetime.datetime(1999,9,9,9,9,9),
  81.         }
  82.     json_unsafe.update(json_safe)
  83.     json_unsafe['array'] = json_unsafe.values()
  84.     json_unsafe['tuple'] = tuple(json_unsafe.values())
  85.     json_unsafe['dict'] = json_unsafe.copy()
  86.     json_unsafe['iter'] = iter(json_unsafe.values())
  87.     def _test_client_content_type_good(self, content_type, ll):
  88.         def run(ll):
  89.             req = siesta.Request.blank('/')
  90.             req.environ['REQUEST_METHOD'] = 'POST'
  91.             req.content_type = content_type
  92.             req.llsd = ll
  93.             req.accept = content_type
  94.             resp = req.get_response(self.server)
  95.             self.assertEquals(resp.status_int, 200)
  96.             return req, resp
  97.         
  98.         if False and isinstance(ll, dict):
  99.             def fixup(v):
  100.                 if isinstance(v, float):
  101.                     return '%.5f' % v
  102.                 if isinstance(v, long):
  103.                     return int(v)
  104.                 if isinstance(v, (llsd.binary, llsd.uri)):
  105.                     return v
  106.                 if isinstance(v, (tuple, list)):
  107.                     return [fixup(i) for i in v]
  108.                 if isinstance(v, dict):
  109.                     return dict([(k, fixup(i)) for k, i in v.iteritems()])
  110.                 return v
  111.             for k, v in ll.iteritems():
  112.                 l = [k, v]
  113.                 req, resp = run(l)
  114.                 self.assertEquals(fixup(resp.llsd), fixup(l))
  115.         run(ll)
  116.     def test_client_content_type_json_good(self):
  117.         self._test_client_content_type_good('application/json', self.json_safe)
  118.     def test_client_content_type_llsd_xml_good(self):
  119.         self._test_client_content_type_good('application/llsd+xml',
  120.                                             self.json_unsafe)
  121.     def test_client_content_type_llsd_notation_good(self):
  122.         self._test_client_content_type_good('application/llsd+notation',
  123.                                             self.json_unsafe)
  124.     def test_client_content_type_llsd_binary_good(self):
  125.         self._test_client_content_type_good('application/llsd+binary',
  126.                                             self.json_unsafe)
  127.     def test_client_content_type_xml_good(self):
  128.         self._test_client_content_type_good('application/xml',
  129.                                             self.json_unsafe)
  130.     def _test_client_content_type_bad(self, content_type):
  131.         req = siesta.Request.blank('/')
  132.         req.environ['REQUEST_METHOD'] = 'POST'
  133.         req.body = 'invalid nonsense under all encodings'
  134.         req.content_type = content_type
  135.         self.assertEquals(req.get_response(self.server).status_int,
  136.                           exc.HTTPBadRequest.code)
  137.         
  138.     def test_client_content_type_json_bad(self):
  139.         self._test_client_content_type_bad('application/json')
  140.     def test_client_content_type_llsd_xml_bad(self):
  141.         self._test_client_content_type_bad('application/llsd+xml')
  142.     def test_client_content_type_llsd_notation_bad(self):
  143.         self._test_client_content_type_bad('application/llsd+notation')
  144.     def test_client_content_type_llsd_binary_bad(self):
  145.         self._test_client_content_type_bad('application/llsd+binary')
  146.     def test_client_content_type_xml_bad(self):
  147.         self._test_client_content_type_bad('application/xml')
  148.     def test_client_content_type_bad(self):
  149.         req = siesta.Request.blank('/')
  150.         req.environ['REQUEST_METHOD'] = 'POST'
  151.         req.body = 'XXX'
  152.         req.content_type = 'application/nonsense'
  153.         self.assertEquals(req.get_response(self.server).status_int,
  154.                           exc.HTTPUnsupportedMediaType.code)
  155.     def test_request_default_content_type(self):
  156.         req = siesta.Request.blank('/')
  157.         self.assertEquals(req.content_type, req.default_content_type)
  158.     def test_request_default_accept(self):
  159.         req = siesta.Request.blank('/')
  160.         from webob import acceptparse
  161.         self.assertEquals(str(req.accept).replace(' ', ''),
  162.                           req.default_accept.replace(' ', ''))
  163.     def test_request_llsd_auto_body(self):
  164.         req = siesta.Request.blank('/')
  165.         req.llsd = {'a': 2}
  166.         self.assertEquals(req.body, '<?xml version="1.0" ?><llsd><map>'
  167.                           '<key>a</key><integer>2</integer></map></llsd>')
  168.     def test_request_llsd_mod_body_changes_llsd(self):
  169.         req = siesta.Request.blank('/')
  170.         req.llsd = {'a': 2}
  171.         req.body = '<?xml version="1.0" ?><llsd><integer>1337</integer></llsd>'
  172.         self.assertEquals(req.llsd, 1337)
  173.     def test_request_bad_llsd_fails(self):
  174.         def crashme(ctype):
  175.             def boom():
  176.                 class foo(object): pass
  177.                 req = siesta.Request.blank('/')
  178.                 req.content_type = ctype
  179.                 req.llsd = foo()
  180.         for mime_type in siesta.llsd_parsers:
  181.             self.assertRaises(TypeError, crashme(mime_type))
  182. class ClassServer(TestBase, unittest.TestCase):
  183.     def __init__(self, *args, **kwargs):
  184.         unittest.TestCase.__init__(self, *args, **kwargs)
  185.         self.server = siesta.llsd_class(ClassApp)
  186. class CallableServer(TestBase, unittest.TestCase):
  187.     def __init__(self, *args, **kwargs):
  188.         unittest.TestCase.__init__(self, *args, **kwargs)
  189.         self.server = siesta.llsd_callable(callable_app)
  190. class RouterServer(unittest.TestCase):
  191.     def test_router(self):
  192.         def foo(req, quux):
  193.             print quux
  194.         r = siesta.Router()
  195.         r.add('/foo/{quux:int}', siesta.llsd_callable(foo), methods=['GET'])
  196.         req = siesta.Request.blank('/foo/33')
  197.         req.get_response(r)
  198.         req = siesta.Request.blank('/foo/bar')
  199.         self.assertEquals(req.get_response(r).status_int,
  200.                           exc.HTTPNotFound.code)
  201.     
  202. if __name__ == '__main__':
  203.     unittest.main()