Fixed python_path problem.
[smonitor.git] / lib / cherrypy / test / test_json.py
bloba02c07674b3bb48bfd7043c138c478e72dc0742d
1 import cherrypy
2 from cherrypy.test import helper
4 from cherrypy._cpcompat import json
6 class JsonTest(helper.CPWebCase):
7 def setup_server():
8 class Root(object):
9 def plain(self):
10 return 'hello'
11 plain.exposed = True
13 def json_string(self):
14 return 'hello'
15 json_string.exposed = True
16 json_string._cp_config = {'tools.json_out.on': True}
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}
23 def json_dict(self):
24 return {'answer': 42}
25 json_dict.exposed = True
26 json_dict._cp_config = {'tools.json_out.on': True}
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}
36 root = Root()
37 cherrypy.tree.mount(root)
38 setup_server = staticmethod(setup_server)
40 def test_json_output(self):
41 if json is None:
42 self.skip("json not found ")
43 return
45 self.getPage("/plain")
46 self.assertBody("hello")
48 self.getPage("/json_string")
49 self.assertBody('"hello"')
51 self.getPage("/json_list")
52 self.assertBody('["a", "b", 42]')
54 self.getPage("/json_dict")
55 self.assertBody('{"answer": 42}')
57 def test_json_input(self):
58 if json is None:
59 self.skip("json not found ")
60 return
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')
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')
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')