Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/tags/cherrypy-3.0.0/cherrypy/test/test_misc_tools.py

Revision 1422 (checked in by fumanchu, 2 years ago)

New tools.accept(media). See test_misc_tools.py for usage.

  • Property svn:eol-style set to native
Line 
1 from cherrypy.test import test
2 test.prefer_parent_path()
3
4 import cherrypy
5 from cherrypy import tools
6
7
8 def setup_server():
9     class Root:
10         def index(self):
11             yield "Hello, world"
12         index.exposed = True
13         h = [("Content-Language", "en-GB"), ('Content-Type', 'text/plain')]
14         tools.response_headers(headers=h)(index)
15        
16         def other(self):
17             return "salut"
18         other.exposed = True
19         other._cp_config = {
20             'tools.response_headers.on': True,
21             'tools.response_headers.headers': [("Content-Language", "fr"),
22                                                ('Content-Type', 'text/plain')],
23             }
24    
25    
26     class Accept:
27         _cp_config = {'tools.accept.on': True}
28        
29         def index(self):
30             return '<a href="feed">Atom feed</a>'
31         index.exposed = True
32        
33         # In Python 2.4+, we could use a decorator instead:
34         # @tools.accept('application/atom+xml')
35         def feed(self):
36             return """<?xml version="1.0" encoding="utf-8"?>
37 <feed xmlns="http://www.w3.org/2005/Atom">
38     <title>Unknown Blog</title>
39 </feed>"""
40         feed.exposed = True
41         feed._cp_config = {'tools.accept.media': 'application/atom+xml'}
42        
43         def select(self):
44             # We could also write this: mtype = cherrypy.lib.accept.accept(...)
45             mtype = tools.accept.callable(['text/html', 'text/plain'])
46             if mtype == 'text/html':
47                 return "<h2>Page Title</h2>"
48             else:
49                 return "PAGE TITLE"
50         select.exposed = True
51    
52     class Referer:
53         def accept(self):
54             return "Accepted!"
55         accept.exposed = True
56         reject = accept
57    
58     conf = {'/referer': {'tools.referer.on': True,
59                          'tools.referer.pattern': r'http://[^/]*thisdomain\.com',
60                          },
61             '/referer/reject': {'tools.referer.accept': False,
62                                 'tools.referer.accept_missing': True,
63                                 },
64             }
65    
66     root = Root()
67     root.referer = Referer()
68     root.accept = Accept()
69     cherrypy.tree.mount(root, config=conf)
70     cherrypy.config.update({'environment': 'test_suite'})
71
72
73 from cherrypy.test import helper
74
75 class ResponseHeadersTest(helper.CPWebCase):
76
77     def testResponseHeadersDecorator(self):
78         self.getPage('/')
79         self.assertHeader("Content-Language", "en-GB")
80         self.assertHeader('Content-Type', 'text/plain')
81
82     def testResponseHeaders(self):
83         self.getPage('/other')
84         self.assertHeader("Content-Language", "fr")
85         self.assertHeader('Content-Type', 'text/plain')
86
87
88 class RefererTest(helper.CPWebCase):
89    
90     def testReferer(self):
91         self.getPage('/referer/accept')
92         self.assertErrorPage(403, 'Forbidden Referer header.')
93        
94         self.getPage('/referer/accept',
95                      headers=[('Referer', 'http://www.thisdomain.com/')])
96         self.assertStatus(200)
97         self.assertBody('Accepted!')
98        
99         # Reject
100         self.getPage('/referer/reject')
101         self.assertStatus(200)
102         self.assertBody('Accepted!')
103        
104         self.getPage('/referer/reject',
105                      headers=[('Referer', 'http://www.thisdomain.com/')])
106         self.assertErrorPage(403, 'Forbidden Referer header.')
107
108
109 class AcceptTest(helper.CPWebCase):
110    
111     def test_Accept_Tool(self):
112         # Test with no header provided
113         self.getPage('/accept/feed')
114         self.assertStatus(200)
115         self.assertInBody('<title>Unknown Blog</title>')
116        
117         # Specify exact media type
118         self.getPage('/accept/feed', headers=[('Accept', 'application/atom+xml')])
119         self.assertStatus(200)
120         self.assertInBody('<title>Unknown Blog</title>')
121        
122         # Specify matching media range
123         self.getPage('/accept/feed', headers=[('Accept', 'application/*')])
124         self.assertStatus(200)
125         self.assertInBody('<title>Unknown Blog</title>')
126        
127         # Specify all media ranges
128         self.getPage('/accept/feed', headers=[('Accept', '*/*')])
129         self.assertStatus(200)
130         self.assertInBody('<title>Unknown Blog</title>')
131        
132         # Specify unacceptable media types
133         self.getPage('/accept/feed', headers=[('Accept', 'text/html')])
134         self.assertErrorPage(406,
135                              "Your client sent this Accept header: text/html. "
136                              "But this resource only emits these media types: "
137                              "application/atom+xml.")
138        
139         # Test resource where tool is 'on' but media is None (not set).
140         self.getPage('/accept/')
141         self.assertStatus(200)
142         self.assertBody('<a href="feed">Atom feed</a>')
143    
144     def test_accept_selection(self):
145         # Try both our expected media types
146         self.getPage('/accept/select', [('Accept', 'text/html')])
147         self.assertStatus(200)
148         self.assertBody('<h2>Page Title</h2>')
149         self.getPage('/accept/select', [('Accept', 'text/plain')])
150         self.assertStatus(200)
151         self.assertBody('PAGE TITLE')
152         self.getPage('/accept/select', [('Accept', 'text/plain, text/*;q=0.5')])
153         self.assertStatus(200)
154         self.assertBody('PAGE TITLE')
155        
156         # text/* and */* should prefer text/html since it comes first
157         # in our 'media' argument to tools.accept
158         self.getPage('/accept/select', [('Accept', 'text/*')])
159         self.assertStatus(200)
160         self.assertBody('<h2>Page Title</h2>')
161         self.getPage('/accept/select', [('Accept', '*/*')])
162         self.assertStatus(200)
163         self.assertBody('<h2>Page Title</h2>')
164        
165         # Try unacceptable media types
166         self.getPage('/accept/select', [('Accept', 'application/xml')])
167         self.assertErrorPage(406,
168                              "Your client sent this Accept header: application/xml. "
169                              "But this resource only emits these media types: "
170                              "text/html, text/plain.")
171
172
173
174 if __name__ == "__main__":
175     setup_server()
176     helper.testmain()
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets