1 from cherrypy.test import test
2 test.prefer_parent_path()
3
4 import os
5 localDir = os.path.dirname(__file__)
6 logfile = os.path.join(localDir, "test_misc_tools.log")
7
8 import cherrypy
9 from cherrypy import tools
10
11
13 class Root:
14 def index(self):
15 yield "Hello, world"
16 index.exposed = True
17 h = [("Content-Language", "en-GB"), ('Content-Type', 'text/plain')]
18 tools.response_headers(headers=h)(index)
19
20 def other(self):
21 return "salut"
22 other.exposed = True
23 other._cp_config = {
24 'tools.response_headers.on': True,
25 'tools.response_headers.headers': [("Content-Language", "fr"),
26 ('Content-Type', 'text/plain')],
27 'tools.log_hooks.on': True,
28 }
29
30
31 class Accept:
32 _cp_config = {'tools.accept.on': True}
33
34 def index(self):
35 return '<a href="feed">Atom feed</a>'
36 index.exposed = True
37
38
39
40 def feed(self):
41 return """<?xml version="1.0" encoding="utf-8"?>
42 <feed xmlns="http://www.w3.org/2005/Atom">
43 <title>Unknown Blog</title>
44 </feed>"""
45 feed.exposed = True
46 feed._cp_config = {'tools.accept.media': 'application/atom+xml'}
47
48 def select(self):
49
50 mtype = tools.accept.callable(['text/html', 'text/plain'])
51 if mtype == 'text/html':
52 return "<h2>Page Title</h2>"
53 else:
54 return "PAGE TITLE"
55 select.exposed = True
56
57 class Referer:
58 def accept(self):
59 return "Accepted!"
60 accept.exposed = True
61 reject = accept
62
63 conf = {'/referer': {'tools.referer.on': True,
64 'tools.referer.pattern': r'http://[^/]*example\.com',
65 },
66 '/referer/reject': {'tools.referer.accept': False,
67 'tools.referer.accept_missing': True,
68 },
69 }
70
71 root = Root()
72 root.referer = Referer()
73 root.accept = Accept()
74 cherrypy.tree.mount(root, config=conf)
75 cherrypy.config.update({'environment': 'test_suite',
76 'log.error_file': logfile})
77
78
79 from cherrypy.test import helper
80
92
93
113
114
116
149
151
152 self.getPage('/accept/select', [('Accept', 'text/html')])
153 self.assertStatus(200)
154 self.assertBody('<h2>Page Title</h2>')
155 self.getPage('/accept/select', [('Accept', 'text/plain')])
156 self.assertStatus(200)
157 self.assertBody('PAGE TITLE')
158 self.getPage('/accept/select', [('Accept', 'text/plain, text/*;q=0.5')])
159 self.assertStatus(200)
160 self.assertBody('PAGE TITLE')
161
162
163
164 self.getPage('/accept/select', [('Accept', 'text/*')])
165 self.assertStatus(200)
166 self.assertBody('<h2>Page Title</h2>')
167 self.getPage('/accept/select', [('Accept', '*/*')])
168 self.assertStatus(200)
169 self.assertBody('<h2>Page Title</h2>')
170
171
172 self.getPage('/accept/select', [('Accept', 'application/xml')])
173 self.assertErrorPage(406,
174 "Your client sent this Accept header: application/xml. "
175 "But this resource only emits these media types: "
176 "text/html, text/plain.")
177
178
179
180 if __name__ == "__main__":
181 setup_server()
182 helper.testmain()
183