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

root/trunk/cherrypy/test/test_encoding.py

Revision 1993 (checked in by fumanchu, 4 months ago)

Fix for #832 (Failure in test_encoding). I'm reasonably sure this is what we want.

  • Property svn:eol-style set to native
Line 
1 from cherrypy.test import test
2 test.prefer_parent_path()
3
4 import gzip, StringIO
5 import cherrypy
6 europoundUnicode = u'\x80\xa3'
7 europoundUtf8 = u'\x80\xa3'.encode('utf-8')
8 sing = u"\u6bdb\u6cfd\u4e1c: Sing, Little Birdie?"
9 sing8 = sing.encode('utf-8')
10 sing16 = sing.encode('utf-16')
11
12
13 def setup_server():
14     class Root:
15         def index(self, param):
16             assert param == europoundUnicode
17             yield europoundUnicode
18         index.exposed = True
19        
20         def mao_zedong(self):
21             return sing
22         mao_zedong.exposed = True
23        
24         def utf8(self):
25             return sing8
26         utf8.exposed = True
27         utf8._cp_config = {'tools.encode.encoding': 'utf-8'}
28        
29         def reqparams(self, *args, **kwargs):
30             return repr(cherrypy.request.params)
31         reqparams.exposed = True
32    
33     class GZIP:
34         def index(self):
35             yield "Hello, world"
36         index.exposed = True
37        
38         def noshow(self):
39             # Test for ticket #147, where yield showed no exceptions (content-
40             # encoding was still gzip even though traceback wasn't zipped).
41             raise IndexError()
42             yield "Here be dragons"
43         noshow.exposed = True
44        
45         def noshow_stream(self):
46             # Test for ticket #147, where yield showed no exceptions (content-
47             # encoding was still gzip even though traceback wasn't zipped).
48             raise IndexError()
49             yield "Here be dragons"
50         noshow_stream.exposed = True
51         noshow_stream._cp_config = {'response.stream': True}
52    
53     cherrypy.config.update({
54             'environment': 'test_suite',
55             'tools.encode.on': True,
56             'tools.decode.on': True,
57     })
58    
59     root = Root()
60     root.gzip = GZIP()
61     cherrypy.tree.mount(root, config={'/gzip': {'tools.gzip.on': True}})
62
63
64
65 from cherrypy.test import helper
66
67
68 class EncodingTests(helper.CPWebCase):
69    
70     def testDecoding(self):
71         europoundUtf8 = europoundUnicode.encode('utf-8')
72         self.getPage('/?param=%s' % europoundUtf8)
73         self.assertBody(europoundUtf8)
74        
75         # Make sure that encoded utf8 gets parsed correctly
76         self.getPage("/reqparams?q=%C2%A3")
77         self.assertBody(r"{'q': u'\xa3'}")
78    
79     def testEncoding(self):
80         # Default encoding should be utf-8
81         self.getPage('/mao_zedong')
82         self.assertBody(sing8)
83        
84         # Ask for utf-16.
85         self.getPage('/mao_zedong', [('Accept-Charset', 'utf-16')])
86         self.assertHeader('Content-Type', 'text/html;charset=utf-16')
87         self.assertBody(sing16)
88        
89         # Ask for multiple encodings. ISO-8859-1 should fail, and utf-16
90         # should be produced.
91         self.getPage('/mao_zedong', [('Accept-Charset',
92                                       'iso-8859-1;q=1, utf-16;q=0.5')])
93         self.assertBody(sing16)
94        
95         # The "*" value should default to our default_encoding, utf-8
96         self.getPage('/mao_zedong', [('Accept-Charset', '*;q=1, utf-7;q=.2')])
97         self.assertBody(sing8)
98        
99         # Only allow iso-8859-1, which should fail and raise 406.
100         self.getPage('/mao_zedong', [('Accept-Charset', 'iso-8859-1, *;q=0')])
101         self.assertStatus("406 Not Acceptable")
102         self.assertInBody("Your client sent this Accept-Charset header: "
103                           "iso-8859-1, *;q=0. We tried these charsets: "
104                           "iso-8859-1.")
105        
106         # Ask for x-mac-ce, which should be unknown. See ticket #569.
107         self.getPage('/mao_zedong', [('Accept-Charset',
108                                       'us-ascii, ISO-8859-1, x-mac-ce')])
109         self.assertStatus("406 Not Acceptable")
110         self.assertInBody("Your client sent this Accept-Charset header: "
111                           "us-ascii, ISO-8859-1, x-mac-ce. We tried these "
112                           "charsets: x-mac-ce, us-ascii, ISO-8859-1.")
113        
114         # Test the 'encoding' arg to encode.
115         self.getPage('/utf8')
116         self.assertBody(sing8)
117         self.getPage('/utf8', [('Accept-Charset', 'us-ascii, ISO-8859-1')])
118         self.assertStatus("406 Not Acceptable")
119    
120     def testGzip(self):
121         zbuf = StringIO.StringIO()
122         zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9)
123         zfile.write("Hello, world")
124         zfile.close()
125        
126         self.getPage('/gzip/', headers=[("Accept-Encoding", "gzip")])
127         self.assertInBody(zbuf.getvalue()[:3])
128         self.assertHeader("Vary", "Accept-Encoding")
129         self.assertHeader("Content-Encoding", "gzip")
130        
131         # Test when gzip is denied.
132         self.getPage('/gzip/', headers=[("Accept-Encoding", "identity")])
133         self.assertNoHeader("Vary")
134         self.assertBody("Hello, world")
135        
136         self.getPage('/gzip/', headers=[("Accept-Encoding", "gzip;q=0")])
137         self.assertNoHeader("Vary")
138         self.assertBody("Hello, world")
139        
140         self.getPage('/gzip/', headers=[("Accept-Encoding", "*;q=0")])
141         self.assertStatus(406)
142         self.assertNoHeader("Vary")
143         self.assertErrorPage(406, "identity, gzip")
144        
145         # Test for ticket #147
146         self.getPage('/gzip/noshow', headers=[("Accept-Encoding", "gzip")])
147         self.assertNoHeader('Content-Encoding')
148         self.assertStatus(500)
149         self.assertErrorPage(500, pattern="IndexError\n")
150        
151         # In this case, there's nothing we can do to deliver a
152         # readable page, since 1) the gzip header is already set,
153         # and 2) we may have already written some of the body.
154         # The fix is to never stream yields when using gzip.
155         if cherrypy.server.protocol_version == "HTTP/1.0":
156             self.getPage('/gzip/noshow_stream',
157                          headers=[("Accept-Encoding", "gzip")])
158             self.assertHeader('Content-Encoding', 'gzip')
159             self.assertInBody('\x1f\x8b\x08\x00')
160         else:
161             # The wsgiserver will simply stop sending data, and the HTTP client
162             # will error due to an incomplete chunk-encoded stream.
163             self.assertRaises(ValueError, self.getPage, '/gzip/noshow_stream',
164                               headers=[("Accept-Encoding", "gzip")])
165
166
167 if __name__ == "__main__":
168     setup_server()
169     helper.testmain()
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets