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

root/branches/cherrypy-2.1/cherrypy/test/test_tutorials.py

Revision 727 (checked in by fumanchu, 3 years ago)

Tutorial fixes, plus a bug in _cputil.getErrorPage.

Line 
1 """
2 Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8     * Redistributions of source code must retain the above copyright notice,
9       this list of conditions and the following disclaimer.
10     * Redistributions in binary form must reproduce the above copyright notice,
11       this list of conditions and the following disclaimer in the documentation
12       and/or other materials provided with the distribution.
13     * Neither the name of the CherryPy Team nor the names of its contributors
14       may be used to endorse or promote products derived from this software
15       without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
21 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 """
28
29 import unittest
30 import sys
31
32 import cherrypy
33 import helper
34
35
36 class TutorialTest(helper.CPWebCase):
37    
38     def load_tut_module(self, tutorialName):
39         """Import or reload tutorial module as needed."""
40         cherrypy.config.reset()
41        
42         target = "cherrypy.tutorial." + tutorialName
43         if target in sys.modules:
44             module = reload(sys.modules[target])
45         else:
46             module = __import__(target, globals(), locals(), [''])
47        
48         cherrypy.config.update({'server.socketHost': self.HOST,
49                                 'server.socketPort': self.PORT,
50                                 'server.threadPool': 10,
51                                 'server.logToScreen': False,
52                                 'server.environment': "production",
53                                 })
54    
55     def test01HelloWorld(self):
56         self.load_tut_module("tut01_helloworld")
57         self.getPage("/")
58         self.assertBody('Hello world!')
59    
60     def test02ExposeMethods(self):
61         self.load_tut_module("tut02_expose_methods")
62         self.getPage("/showMessage")
63         self.assertBody('Hello world!')
64    
65     def test03GetAndPost(self):
66         self.load_tut_module("tut03_get_and_post")
67        
68         # Try different GET queries
69         self.getPage("/greetUser?name=Bob")
70         self.assertBody("Hey Bob, what's up?")
71        
72         self.getPage("/greetUser")
73         self.assertBody('Please enter your name <a href="./">here</a>.')
74        
75         self.getPage("/greetUser?name=")
76         self.assertBody('No, really, enter your name <a href="./">here</a>.')
77        
78         # Try the same with POST
79         self.getPage("/greetUser", method="POST", body="name=Bob")
80         self.assertBody("Hey Bob, what's up?")
81        
82         self.getPage("/greetUser", method="POST", body="name=")
83         self.assertBody('No, really, enter your name <a href="./">here</a>.')
84    
85     def test04ComplexSite(self):
86         self.load_tut_module("tut04_complex_site")
87         msg = '''
88             <p>Here are some extra useful links:</p>
89             
90             <ul>
91                 <li><a href="del.icio.ushttp://del.icio.us">del.icio.us</a></li>
92                 <li><a href="Hendrik's">http://www.mornography.de">Hendrik's weblog</a></li>
93             </ul>
94             
95             <p>[<a href="../">Return to links page</a>]</p>'''
96         self.getPage("/links/extra/")
97         self.assertBody(msg)
98    
99     def test05DerivedObjects(self):
100         self.load_tut_module("tut05_derived_objects")
101         msg = '''
102             <html>
103             <head>
104                 <title>Another Page</title>
105             <head>
106             <body>
107             <h2>Another Page</h2>
108         
109             <p>
110             And this is the amazing second page!
111             </p>
112         
113             </body>
114             </html>
115         '''
116         self.getPage("/another/")
117         self.assertBody(msg)
118    
119     def test06DefaultMethod(self):
120         self.load_tut_module("tut06_default_method")
121         self.getPage('/hendrik')
122         self.assertBody('Hendrik Mans, CherryPy co-developer & crazy German '
123                          '(<a href="./">back</a>)')
124     def test07Sessions(self):
125         self.load_tut_module("tut07_sessions")
126         cherrypy.config.update({"sessionFilter.on": True})
127        
128         self.getPage('/')
129         self.assertBody("\n            During your current session, you've viewed this"
130                          "\n            page 1 times! Your life is a patio of fun!"
131                          "\n        ")
132        
133         self.getPage('/', self.cookies)
134         self.assertBody("\n            During your current session, you've viewed this"
135                          "\n            page 2 times! Your life is a patio of fun!"
136                          "\n        ")
137    
138     def test08GeneratorsAndYield(self):
139         self.load_tut_module("tut08_generators_and_yield")
140         self.getPage('/')
141         self.assertBody('<html><body><h2>Generators rule!</h2>'
142                          '<h3>List of users:</h3>'
143                          'Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/>'
144                          '</body></html>')
145    
146     def test09Files(self):
147         self.load_tut_module("tut09_files")
148        
149         # Test upload
150         h = [("Content-type", "multipart/form-data; boundary=x"),
151              ("Content-Length", "110")]
152         b = """--x
153 Content-Disposition: form-data; name="myFile"; filename="hello.txt"
154 Content-Type: text/plain
155
156 hello
157 --x--
158 """
159         self.getPage('/upload', h, "POST", b)
160         self.assertBody('''<html>
161         <body>
162             myFile length: 5<br />
163             myFile filename: hello.txt<br />
164             myFile mime-type: text/plain
165         </body>
166         </html>''')
167    
168         # Test download
169         self.getPage('/download')
170         self.assertStatus("200 OK")
171         self.assertHeader("Content-Type", "application/x-download")
172         self.assertHeader("Content-Disposition", "attachment; filename=pdf_file.pdf")
173         self.assertEqual(len(self.body), 85698)
174    
175     def test10HTTPErrors(self):
176         self.load_tut_module("tut10_http_errors")
177        
178         self.getPage("/")
179         self.assertInBody("""<a href="toggleTracebacks">""")
180         self.assertInBody("""<a href="/doesNotExist">""")
181         self.assertInBody("""<a href="/error?code=403">""")
182         self.assertInBody("""<a href="/error?code=500">""")
183         self.assertInBody("""<a href="/messageArg">""")
184        
185         tracebacks = cherrypy.config.get('server.showTracebacks')
186         self.getPage("/toggleTracebacks")
187         self.assertEqual(cherrypy.config.get('server.showTracebacks'), not tracebacks)
188         self.assertStatus("302 Found")
189        
190         self.getPage("/error?code=500")
191         self.assertStatus("500 Internal error")
192         self.assertInBody("Server got itself in trouble")
193        
194         self.getPage("/error?code=403")
195         self.assertStatus("403 Forbidden")
196         self.assertInBody("<h2>You can't do that!</h2>")
197        
198         self.getPage("/messageArg")
199         self.assertStatus("500 Internal error")
200         self.assertInBody("If you construct an HTTPError with a 'message'")
201
202
203 if __name__ == "__main__":
204     helper.testmain()
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets