Package cherrypy :: Package test :: Module test_json
[hide private]
[frames] | no frames]

Source Code for Module cherrypy.test.test_json

 1  import cherrypy 
 2  from cherrypy.test import helper 
 3   
 4  from cherrypy._cpcompat import json 
 5   
6 -class JsonTest(helper.CPWebCase):
7 - def setup_server():
8 class Root(object): 9 def plain(self): 10 return 'hello'
11 plain.exposed = True 12 13 def json_string(self): 14 return 'hello'
15 json_string.exposed = True 16 json_string._cp_config = {'tools.json_out.on': True} 17 18 def json_list(self): 19 return ['a', 'b', 42] 20 json_list.exposed = True 21 json_list._cp_config = {'tools.json_out.on': True} 22 23 def json_dict(self): 24 return {'answer': 42} 25 json_dict.exposed = True 26 json_dict._cp_config = {'tools.json_out.on': True} 27 28 def json_post(self): 29 if cherrypy.request.json == [13, 'c']: 30 return 'ok' 31 else: 32 return 'nok' 33 json_post.exposed = True 34 json_post._cp_config = {'tools.json_in.on': True} 35 36 root = Root() 37 cherrypy.tree.mount(root) 38 setup_server = staticmethod(setup_server) 39
40 - def test_json_output(self):
41 if json is None: 42 self.skip("json not found ") 43 return 44 45 self.getPage("/plain") 46 self.assertBody("hello") 47 48 self.getPage("/json_string") 49 self.assertBody('"hello"') 50 51 self.getPage("/json_list") 52 self.assertBody('["a", "b", 42]') 53 54 self.getPage("/json_dict") 55 self.assertBody('{"answer": 42}')
56
57 - def test_json_input(self):
58 if json is None: 59 self.skip("json not found ") 60 return 61 62 body = '[13, "c"]' 63 headers = [('Content-Type', 'application/json'), 64 ('Content-Length', str(len(body)))] 65 self.getPage("/json_post", method="POST", headers=headers, body=body) 66 self.assertBody('ok') 67 68 body = '[13, "c"]' 69 headers = [('Content-Type', 'text/plain'), 70 ('Content-Length', str(len(body)))] 71 self.getPage("/json_post", method="POST", headers=headers, body=body) 72 self.assertStatus(415, 'Expected an application/json content type') 73 74 body = '[13, -]' 75 headers = [('Content-Type', 'application/json'), 76 ('Content-Length', str(len(body)))] 77 self.getPage("/json_post", method="POST", headers=headers, body=body) 78 self.assertStatus(400, 'Invalid JSON document')
79