Changeset 256
- Timestamp:
- 06/08/05 16:20:47
- Files:
-
- branches/ticket-177/cherrypy/_cphttpserver.py (modified) (1 diff)
- branches/ticket-177/cherrypy/cpg.py (modified) (1 diff)
- branches/ticket-177/cherrypy/test/__init__.py (modified) (1 diff)
- branches/ticket-177/cherrypy/test/buildInfoMap.py (deleted)
- branches/ticket-177/cherrypy/test/helper.py (modified) (3 diffs)
- branches/ticket-177/cherrypy/test/test.py (modified) (1 diff)
- branches/ticket-177/cherrypy/test/testBaseUrlFilter.py (deleted)
- branches/ticket-177/cherrypy/test/testCacheFilter.py (deleted)
- branches/ticket-177/cherrypy/test/testCombinedFilters.py (deleted)
- branches/ticket-177/cherrypy/test/testCore.py (deleted)
- branches/ticket-177/cherrypy/test/testDecodingEncodingFilter.py (deleted)
- branches/ticket-177/cherrypy/test/testGzipFilter.py (deleted)
- branches/ticket-177/cherrypy/test/testLogDebugInfoFilter.py (deleted)
- branches/ticket-177/cherrypy/test/testObjectMapping.py (deleted)
- branches/ticket-177/cherrypy/test/testStaticFilter.py (deleted)
- branches/ticket-177/cherrypy/test/testVirtualHostFilter.py (deleted)
- branches/ticket-177/cherrypy/test/test_baseurl_filter.py (copied) (copied from trunk/cherrypy/test/testBaseUrlFilter.py) (2 diffs)
- branches/ticket-177/cherrypy/test/test_cache_filter.py (copied) (copied from trunk/cherrypy/test/testCacheFilter.py) (1 diff)
- branches/ticket-177/cherrypy/test/test_combinedfilters.py (copied) (copied from trunk/cherrypy/test/testCombinedFilters.py) (3 diffs)
- branches/ticket-177/cherrypy/test/test_core.py (copied) (copied from trunk/cherrypy/test/testCore.py) (5 diffs)
- branches/ticket-177/cherrypy/test/test_decodingencoding_filter.py (copied) (copied from trunk/cherrypy/test/testDecodingEncodingFilter.py) (3 diffs)
- branches/ticket-177/cherrypy/test/test_gzip_filter.py (added)
- branches/ticket-177/cherrypy/test/test_logdebuginfo_filter.py (copied) (copied from trunk/cherrypy/test/testLogDebugInfoFilter.py) (1 diff)
- branches/ticket-177/cherrypy/test/test_objectmapping.py (copied) (copied from trunk/cherrypy/test/testObjectMapping.py) (2 diffs)
- branches/ticket-177/cherrypy/test/test_static_filter.py (copied) (copied from trunk/cherrypy/test/testStaticFilter.py) (2 diffs)
- branches/ticket-177/cherrypy/test/test_tutorials.py (added)
- branches/ticket-177/cherrypy/test/test_virtualhost_filter.py (copied) (copied from trunk/cherrypy/test/testVirtualHostFilter.py) (1 diff)
- branches/ticket-177/cherrypy/tutorial/01_helloworld.py (deleted)
- branches/ticket-177/cherrypy/tutorial/02_expose_methods.py (deleted)
- branches/ticket-177/cherrypy/tutorial/03_get_and_post.py (deleted)
- branches/ticket-177/cherrypy/tutorial/04_complex_site.py (deleted)
- branches/ticket-177/cherrypy/tutorial/05_derived_objects.py (deleted)
- branches/ticket-177/cherrypy/tutorial/06_aspects.py (deleted)
- branches/ticket-177/cherrypy/tutorial/07_default_method.py (deleted)
- branches/ticket-177/cherrypy/tutorial/08_sessions.py (deleted)
- branches/ticket-177/cherrypy/tutorial/09_generators_and_yield.py (deleted)
- branches/ticket-177/cherrypy/tutorial/tut01_helloworld.py (copied) (copied from trunk/cherrypy/tutorial/01_helloworld.py) (1 diff)
- branches/ticket-177/cherrypy/tutorial/tut02_expose_methods.py (copied) (copied from trunk/cherrypy/tutorial/02_expose_methods.py) (1 diff)
- branches/ticket-177/cherrypy/tutorial/tut03_get_and_post.py (copied) (copied from trunk/cherrypy/tutorial/03_get_and_post.py) (3 diffs)
- branches/ticket-177/cherrypy/tutorial/tut04_complex_site.py (copied) (copied from trunk/cherrypy/tutorial/04_complex_site.py) (6 diffs)
- branches/ticket-177/cherrypy/tutorial/tut05_derived_objects.py (copied) (copied from trunk/cherrypy/tutorial/05_derived_objects.py) (8 diffs)
- branches/ticket-177/cherrypy/tutorial/tut06_aspects.py (copied) (copied from trunk/cherrypy/tutorial/06_aspects.py) (9 diffs)
- branches/ticket-177/cherrypy/tutorial/tut07_default_method.py (copied) (copied from trunk/cherrypy/tutorial/07_default_method.py) (4 diffs)
- branches/ticket-177/cherrypy/tutorial/tut08_sessions.py (copied) (copied from trunk/cherrypy/tutorial/08_sessions.py) (3 diffs)
- branches/ticket-177/cherrypy/tutorial/tut09_generators_and_yield.py (copied) (copied from trunk/cherrypy/tutorial/09_generators_and_yield.py) (3 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
branches/ticket-177/cherrypy/_cphttpserver.py
r253 r256 293 293 294 294 # Set protocol_version 295 CherryHTTPRequestHandler.protocol_version = cpg.config.get('server.protocolVersion') 295 proto = cpg.config.get('server.protocolVersion') 296 if not proto: 297 proto = "HTTP/1.0" 298 CherryHTTPRequestHandler.protocol_version = proto 296 299 297 300 # Select the appropriate server based on config options branches/ticket-177/cherrypy/cpg.py
r199 r256 33 33 from __init__ import __version__ 34 34 35 _httpserver = None 36 35 37 # import server module 36 38 import _cpserver as server branches/ticket-177/cherrypy/test/__init__.py
r8 r256 1 """Regression test suite for CherryPy. 2 3 Run test.py to exercise all tests. 4 """ 5 6 # Ideas for future tests: 7 # - test if tabs and whitespaces are handled correctly in source file (option -W) 8 # - test if absolute pathnames work fine on windows 9 # - test sessions 10 # - test threading server 11 # - test forking server 12 # - test process pooling server 13 # - test SSL 14 # - test compilator errors 15 # - test abstract classes 16 # - test hidden classes 17 # ... 18 branches/ticket-177/cherrypy/test/helper.py
r243 r256 26 26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 27 """ 28 import os,urllib,time,sys,signal,socket,httplib,os.path29 28 30 def startServer(infoMap): 31 # Start the server in another thread 32 if not hasattr(os, "fork"): # win32 mostly 33 pid = os.spawnl(os.P_NOWAIT, infoMap['path'], infoMap['path'], 34 '"' + os.path.join(os.getcwd(), 'testsite.py') + '"') 29 import os, os.path 30 import time 31 import sys 32 import socket 33 import httplib 34 import threading 35 from cherrypy import cpg 36 37 38 HOST = "127.0.0.1" 39 PORT = 8000 40 41 def port_is_free(): 42 try: 43 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 44 s.connect((HOST, PORT)) 45 s.close() 46 return False 47 except socket.error: 48 return True 49 50 51 def startServer(serverClass=None): 52 if serverClass is None: 53 cpg.server.start(initOnly=True) 35 54 else: 36 pid = os.fork() 37 if not pid: 38 os.execlp(infoMap['path'], infoMap['path'], 'testsite.py') 39 return pid 55 if not port_is_free(): 56 raise IOError("Port %s is in use; perhaps the previous server " 57 "did not shut down properly." % port) 58 t = threading.Thread(target=cpg.server.start, args=(False, serverClass)) 59 t.start() 60 time.sleep(1) 40 61 41 class EmptyClass:42 pass43 62 44 def getPage(url, cookies, extraRequestHeader = []): 63 def stopServer(): 64 cpg.server.stop() 65 if cpg.config.get('server.threadPool') > 1: 66 # With thread-pools, it can take up to 1 sec for the server to stop 67 time.sleep(1.1) 68 69 70 def getPage(url, headers=None, method="GET"): 71 45 72 # The trying 10 times is simply in case of socket errors. 46 73 # Normal case--it should run once. … … 48 75 while trial < 10: 49 76 try: 50 conn = httplib.HTTPConnection(' 127.0.0.1:%s' % PORT)77 conn = httplib.HTTPConnection('%s:%s' % (HOST, PORT)) 51 78 ## conn.set_debuglevel(1) 52 conn.putrequest("GET", url) 53 ## conn.putheader("Host", "127.0.0.1") 79 conn.putrequest(method.upper(), url) 54 80 55 if cookies: 56 for cookie in cookies: 57 name, value = cookie.split(":", 1) 58 conn.putheader("Cookie", value.strip()) 59 60 for key, value in extraRequestHeader: 81 for key, value in headers: 61 82 conn.putheader(key, value) 62 63 83 conn.endheaders() 64 84 85 # Handle response 65 86 response = conn.getresponse() 66 87 67 c ookies = response.msg.getallmatchingheaders("Set-Cookie")88 cpg.response.status = "%s %s" % (response.status, response.reason) 68 89 69 cpg = EmptyClass()70 cpg.response = EmptyClass()71 90 cpg.response.headerMap = {} 72 cpg.response.status = "%s %s" % (response.status, response.reason)73 91 for line in response.msg.headers: 74 92 key, value = line.split(":", 1) 75 93 cpg.response.headerMap[key.strip()] = value.strip() 94 cpg.response.headers = cpg.response.headerMap 76 95 77 cpg.response.body = response.read() 96 b = cpg.response.body = response.read() 97 ## print "body:", repr(b) 78 98 79 99 conn.close() 80 return cpg, cookies100 return 81 101 except socket.error: 82 102 trial += 1 … … 86 106 time.sleep(0.5) 87 107 88 def shutdownServer(mode):89 urllib.urlopen("http://127.0.0.1:%s/shutdown/all" % PORT)90 if mode.startswith('tp'):91 # In thread-pool mode, it can take up to 1 sec for the server92 # to shutdown93 time.sleep(1.1)94 return95 108 96 def checkResult(testName, infoMap, serverMode, cpg, rule, failedList): 97 result = False 98 try: 99 result = eval(rule) 100 if result: 101 return result 102 except: 103 pass 104 if not result: 105 failedList.append(testName + 106 " for python%s" % infoMap['exactVersionShort'] + 107 " in " + serverMode + " mode failed." + """ 108 * Rule: 109 %s 110 * cpg.response.status: 111 %s 112 * cpg.response.headerMap: 113 %s 114 * cpg.response.body: 115 %s""" % (rule, repr(cpg.response.status), 116 repr(cpg.response.headerMap), repr(cpg.response.body))) 117 return False 109 def request(url, headers=None, method="GET"): 110 if headers is None: 111 headers = [] 112 113 if cpg._httpserver is None: 114 requestLine = "%s %s HTTP/1.0" % (method.upper(), url) 115 found = False 116 for k, v in headers: 117 if k.lower() == 'host': 118 found = True 119 break 120 if not found: 121 headers.append(("Host", "%s:%s" % (HOST, PORT))) 122 cpg.server.request(HOST, HOST, requestLine, headers, None) 123 cpg.response.body = "".join(cpg.response.body) 124 else: 125 getPage(url, headers, method) 118 126 119 def prepareCode(code, serverClass):120 f = open('testsite.py', 'w')121 122 includePathsToSysPath = """123 import sys,os,os.path124 sys.path.insert(0,os.path.normpath(os.path.join(os.getcwd(),'../../')))125 """126 f.write(includePathsToSysPath)127 128 beforeStart = '''129 class Shutdown:130 def all(self):131 cpg.server.stop()132 return "Shut down"133 all.exposed = True134 cpg.root.shutdown = Shutdown()135 def f(*a, **kw): return ""136 cpg.root._cpLogMessage = f137 cpg.config.update(file = 'testsite.cfg')138 '''139 newcode = code.replace('cpg.config.update', beforeStart + 'cpg.config.update')140 if serverClass:141 serverClass = "serverClass='%s'" % serverClass142 newcode = newcode.replace('cpg.server.start(',143 'cpg.config.configMap["/"]["server.logToScreen"] = False\n'144 'cpg.server.start(' + serverClass)145 f.write(newcode)146 147 f.close()148 149 PORT = 8000150 def port_is_free():151 try:152 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)153 s.connect(('127.0.0.1', PORT))154 s.close()155 return False156 except socket.error:157 return True158 159 def checkPageResult(testName, infoMap, code, testList, failedList, extraConfig = '', extraRequestHeader = []):160 response = None161 162 if not port_is_free():163 print "\n### Error: port", PORT, "is busy. The previous server did not shut down properly."164 sys.exit(-1)165 166 # Try it in all 4 modes (regular, threadPooling x normal, WSGI)167 for name, serverClass in [("native", "cherrypy._cphttpserver.embedded_server"),168 ("wsgi", ""),169 ]:170 sys.stdout.write(name + ": ")171 prepareCode(code, serverClass)172 for mode, modeConfig in [('r', ""), ('tp', 'server.threadPool = 3')]:173 sys.stdout.write(mode)174 sys.stdout.flush()175 f = open("testsite.cfg", "w")176 f.write(extraConfig)177 f.write('''178 [/]179 session.storageType = "ram"180 server.socketPort = %s181 server.environment = "production"182 server.logToScreen = False183 ''' % PORT)184 f.write(modeConfig + "\n")185 f.close()186 187 pid = startServer(infoMap)188 passed=True189 cookies=None190 for url, rule in testList:191 sys.stdout.write(".")192 sys.stdout.flush()193 cpg, cookies = getPage(url, cookies, extraRequestHeader)194 if not checkResult(testName, infoMap, mode, cpg, rule, failedList):195 passed = 0196 print "*** FAILED ***",197 break198 shutdownServer(mode)199 if passed:200 sys.stdout.write("ok ")201 sys.stdout.flush()202 if not passed:203 break204 if passed:205 print "passed"206 sys.stdout.flush()207 return response208 branches/ticket-177/cherrypy/test/test.py
r243 r256 27 27 """ 28 28 29 # Regression test suite for CherryPy 29 import time 30 import sys 31 import os 32 import unittest 30 33 31 import sys,os,os.path32 sys.path.insert(0,os.path.normpath(os.path.join(os.getcwd(),'../../')))33 if not os.path.exists(os.path.join(os.curdir,'buildInfoMap.py')):34 print "Run the test from the test directory (cherrypy/test) from the cherrypy you wish to test."35 print "If no python executables are found, change this file (test.py) near line 31"36 sys.exit(1)37 if len(sys.argv) == 2 and sys.argv[1] in ('-h', '--help'):38 print "Usage: unittest.py [testName+]"39 print "Run from the test directory from within cherrypy"40 sys.exit(0)41 34 42 python2={} 43 python2[3]={} # Infos about python-2.3 44 python2[4]={} # Infos about python-2.4 35 class CPTestResult(unittest._TextTestResult): 36 def printErrors(self): 37 # Overridden to avoid unnecessary empty line 38 if self.errors or self.failures: 39 if self.dots or self.showAll: 40 self.stream.writeln() 41 self.printErrorList('ERROR', self.errors) 42 self.printErrorList('FAIL', self.failures) 45 43 46 # Edit these lines to match your setup47 if sys.platform=="win32":48 python2[3]['path']="c:\\python23\\python.exe"49 python2[4]['path']="c:\\python24\\python.exe"50 else:51 python2[3]['path']="python2.3"52 python2[4]['path']="python2.4"53 44 54 print 45 class CPTestRunner(unittest.TextTestRunner): 46 """A test runner class that displays results in textual form.""" 47 48 def _makeResult(self): 49 return CPTestResult(self.stream, self.descriptions, self.verbosity) 50 51 def run(self, test): 52 "Run the given test case or test suite." 53 # Overridden to remove unnecessary empty lines and separators 54 result = self._makeResult() 55 startTime = time.time() 56 test(result) 57 timeTaken = float(time.time() - startTime) 58 result.printErrors() 59 if not result.wasSuccessful(): 60 self.stream.write("FAILED (") 61 failed, errored = map(len, (result.failures, result.errors)) 62 if failed: 63 self.stream.write("failures=%d" % failed) 64 if errored: 65 if failed: self.stream.write(", ") 66 self.stream.write("errors=%d" % errored) 67 self.stream.writeln(")") 68 return result 55 69 56 print "Examining your system..."57 print58 print "Python version used to run this test script:", sys.version.split()[0]59 print60 import buildInfoMap61 python2 = buildInfoMap.buildInfoMap(python2)62 70 63 print 64 print "Checking CherryPy version..." 65 import os 66 try: 67 import cherrypy 68 except ImportError: 69 print "Error: couln't find CherryPy !" 70 os._exit(-1) 71 class ReloadingTestLoader(unittest.TestLoader): 72 73 def loadTestsFromName(self, name, module=None): 74 """Return a suite of all tests cases given a string specifier. 71 75 72 print " Found version " + cherrypy.__version__ 73 print 76 The name may resolve either to a module, a test case class, a 77 test method within a test case class, or a callable object which 78 returns a TestCase or TestSuite instance. 74 79 75 print "Testing CherryPy..." 76 failedList=[] 77 skippedList=[] 80 The method optionally resolves the names relative to a given module. 81 """ 82 parts = name.split('.') 83 if module is None: 84 if not parts: 85 raise ValueError, "incomplete test name: %s" % name 86 else: 87 parts_copy = parts[:] 88 while parts_copy: 89 target = ".".join(parts_copy) 90 if target in sys.modules: 91 module = reload(sys.modules[target]) 92 break 93 else: 94 try: 95 module = __import__(target) 96 break 97 except ImportError: 98 del parts_copy[-1] 99 if not parts_copy: raise 100 parts = parts[1:] 101 obj = module 102 for part in parts: 103 obj = getattr(obj, part) 104 105 import unittest 106 import types 107 if type(obj) == types.ModuleType: 108 return self.loadTestsFromModule(obj) 109 elif (isinstance(obj, (type, types.ClassType)) and 110 issubclass(obj, unittest.TestCase)): 111 return self.loadTestsFromTestCase(obj) 112 elif type(obj) == types.UnboundMethodType: 113 return obj.im_class(obj.__name__) 114 elif callable(obj): 115 test = obj() 116 if not isinstance(test, unittest.TestCase) and \ 117 not isinstance(test, unittest.TestSuite): 118 raise ValueError, \ 119 "calling %s returned %s, not a test" % (obj,test) 120 return test 121 else: 122 raise ValueError, "don't know how to make test from: %s" % obj 78 123 79 tutorialTestList = [ 80 ('01_helloworld.py', 81 [('/', "cpg.response.body == 'Hello world!'")]), 82 ('02_expose_methods.py', 83 [('/showMessage', "cpg.response.body == 'Hello world!'")]), 84 ('03_get_and_post.py', 85 [('/greetUser?name=Bob', '''cpg.response.body == "Hey Bob, what's up?"''')]), 86 ('03_get_and_post.py', 87 [('/greetUser', """cpg.response.body == 'Please enter your name <a href="./">here</a>.'""")]), 88 ('03_get_and_post.py', 89 [('/greetUser?name=', """cpg.response.body == 'No, really, enter your name <a href="./">here</a>.'""")]), 90 ('04_complex_site.py', 91 [('/links/extra/', r"""cpg.response.body == '\n <p>Here are some extra useful links:</p>\n\n <ul>\n <li><a href="http://del.icio.us">del.icio.us</a></li>\n <li><a href="http://www.mornography.de">Hendrik\'s weblog</a></li>\n </ul>\n\n <p>[<a href="../">Return to links page</a>]</p>\n '""")]), 92 ('05_derived_objects.py', 93 [('/another/', r"""cpg.response.body == '\n <html>\n <head>\n <title>Another Page</title>\n <head>\n <body>\n <h2>Another Page</h2>\n \n <p>\n And this is the amazing second page!\n </p>\n \n </body>\n </html>\n '""")]), 94 ('06_aspects.py', 95 [('/', r"""cpg.response.body == '\n <html>\n <head>\n <title>Tutorial 6 -- Aspect Powered!</title>\n <head>\n <body>\n <h2>Tutorial 6 -- Aspect Powered!</h2>\n \n <p>\n Isn\'t this exciting? There\'s\n <a href="./another/">another page</a>, too!\n </p>\n \n </body>\n </html>\n '""")]), 96 ('07_default_method.py', 97 [('/hendrik', r"""cpg.response.body == 'Hendrik Mans, CherryPy co-developer & crazy German (<a href="./">back</a>)'""")]), 98 ('08_sessions.py', 99 [('/', r'''cpg.response.body == "\n During your current session, you've viewed this\n page 1 times! Your life is a patio of fun!\n "'''), ('/', r'''cpg.response.body == "\n During your current session, you've viewed this\n page 2 times! Your life is a patio of fun!\n "''')]), 100 ('09_generators_and_yield.py', 101 [('/', r"""cpg.response.body == '<html><body><h2>Generators rule!</h2><h3>List of users:</h3>Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/></body></html>'""")]), 102 ] 124 CPTestLoader = ReloadingTestLoader() 103 125 104 testList = [105 'testBaseUrlFilter',106 'testCacheFilter',107 'testCombinedFilters',108 'testCore',109 'testDecodingEncodingFilter',110 'testGzipFilter',111 'testLogDebugInfoFilter',112 'testObjectMapping',113 'testStaticFilter',114 'testVirtualHostFilter',115 ]116 126 117 if len(sys.argv) > 1: 118 # Some specific tests were specified on the command line 119 # Limit the tests to these ones 120 newTutorialTestList = [] 121 newTestList = [] 122 for number, myTestList in tutorialTestList: 123 if "tutorial%s" % number in sys.argv[1:]: 124 newTutorialTestList.append((number, myTestList)) 125 for t in testList: 126 if t in sys.argv[1:]: 127 newTestList.append(t) 128 tutorialTestList = newTutorialTestList 129 testList = newTestList 127 def main(): 128 print "Python version used to run this test script:", sys.version.split()[0] 129 try: 130 import cherrypy 131 except ImportError: 132 print "Error: couln't find CherryPy !" 133 os._exit(-1) 134 print "CherryPy version", cherrypy.__version__ 135 print 136 137 testList = [ 138 'test_baseurl_filter', 139 'test_cache_filter', 140 'test_combinedfilters', 141 'test_core', 142 'test_decodingencoding_filter', 143 'test_gzip_filter', 144 'test_logdebuginfo_filter', 145 'test_objectmapping', 146 'test_static_filter', 147 'test_tutorials', 148 'test_virtualhost_filter', 149 ] 150 151 from cherrypy import cpg 152 import helper 153 154 server_conf = {'server.socketHost': helper.HOST, 155 'server.socketPort': helper.PORT, 156 'server.threadPool': 10, 157 'server.socketQueueSize': 5, 158 'server.logToScreen': False, 159 } 160 161 for name, server in [("Serverless", None), 162 ("Native HTTP Server", "cherrypy._cphttpserver.embedded_server"), 163 ("Native WSGI Server", "cherrypy._cpwsgi.WSGIServer"), 164 ]: 165 print 166 print "Running tests:", name 167 168 cpg.config.update({'/': server_conf.copy()}) 169 helper.startServer(server) 170 for testmod in testList: 171 # Must run each module in a separate suite, 172 # because each module uses/overwrites cpg globals. 173 cpg.config.configMap.clear() 174 cpg.config.update({'/': server_conf.copy()}) 175 suite = CPTestLoader.loadTestsFromName(testmod) 176 CPTestRunner(verbosity=2).run(suite) 177 helper.stopServer() 178 179 raw_input('hit enter') 130 180 131 import helper 132 import time 133 starttime = time.time() 134 135 for version, infoMap in python2.items(): 136 print 137 print "Running tests for python %s..." % infoMap['exactVersionShort'] 138 139 count = 0 140 # Run tests based on tutorials 141 for filename, myTestList in tutorialTestList: 142 count += 1 143 code = open('../tutorial/%s' % filename, 'r').read() 144 code = code.replace('tutorial.conf', 'testsite.cfg') 145 print " Testing tutorial %s..." % filename, 146 #if ((version == 1 and number in ('06', '09')) or 147 # (version == 2 and number in ('09'))): 148 # print "skipped" 149 # skippedList.append("Tutorial %s for python2.%s" % (number, version)) 150 # continue 151 152 helper.checkPageResult('Tutorial %s' % filename, infoMap, code, myTestList, failedList) 153 154 # Running actual unittests 155 for test in testList: 156 count += 1 157 exec("import " + test) 158 eval(test + ".test(infoMap, failedList, skippedList)") 159 160 print 161 print 162 print "#####################################" 163 print "#####################################" 164 print "### TEST RESULT ###" 165 print "#####################################" 166 print "#####################################" 167 print 168 print "%d tests run in %f seconds" % (count, time.time() - starttime) 169 170 if skippedList: 171 print 172 print "*** THE FOLLOWING TESTS WERE SKIPPED:" 173 for skipped in skippedList: print skipped 174 175 print "**** THE ABOVE TESTS WERE SKIPPED" 176 print 177 178 if failedList: 179 print 180 print "*** THE FOLLOWING TESTS FAILED:" 181 for failed in failedList: print failed 182 183 print "**** THE ABOVE TESTS FAILED" 184 print 185 print "**** Some errors occured: please add a ticket in our Trac system (http://www.cherrypy.org/newticket) with the output of this test script" 186 187 else: 188 print 189 print "**** NO TEST FAILED: EVERYTHING LOOKS OK ****" 190 191 ############" 192 # Ideas for future tests: 193 # - test if tabs and whitespaces are handled correctly in source file (option -W) 194 # - test if absolute pathnames work fine on windows 195 # - test sessions 196 # - test threading server 197 # - test forking server 198 # - test process pooling server 199 # - test SSL 200 # - test compilator errors 201 # - test abstract classes 202 # - test hidden classes 203 # ... 204 205 raw_input('hit enter') 181 if __name__ == '__main__': 182 main() branches/ticket-177/cherrypy/test/test_baseurl_filter.py
r251 r256 26 26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 27 """ 28 import helper29 28 30 code = r"""31 29 from cherrypy import cpg 32 30 from cherrypy.lib import httptools 31 33 32 class Root: 34 33 def index(self): 35 34 return httptools.redirect('dummy') 36 35 index.exposed = True 36 37 37 cpg.root = Root() 38 38 cpg.config.update({ 39 39 '/': { 40 'server.socketPort': 8000,41 40 'server.environment': 'production', 42 41 'baseUrlFilter.on': True, … … 44 43 } 45 44 }) 46 cpg.server.start()47 """48 config = ""49 45 50 testList = [ 51 ('/', "cpg.response.headerMap['Location'] == " 52 "'http://www.mydomain.com/dummy'") 53 ] 46 import unittest 47 import helper 54 48 55 def test(infoMap, failedList, skippedList): 56 print " Testing baseUrlFilter ...", 57 helper.checkPageResult('baseUrlFilter', infoMap, code, testList, failedList) 49 class BaseUrlFilterTest(unittest.TestCase): 50 51 def testBaseUrlFilter(self): 52 helper.request("/") 53 self.assertEqual(cpg.response.headerMap['Location'], 54 "http://www.mydomain.com/dummy") 55 56 57 if __name__ == '__main__': 58 cpg.server.start(initOnly=True) 59 unittest.main() 60 branches/ticket-177/cherrypy/test/test_cache_filter.py
r251 r256 26 26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 27 """ 28 import helper, time29 28 30 code = r"""31 29 from cherrypy import cpg 32 30 import time 31 33 32 class Root: 33 def __init__(self): 34 cpg.counter = 0 35 34 36 def index(self): 35 counter = getattr(cpg, 'counter', 0) 36 counter += 1 37 counter = cpg.counter + 1 37 38 cpg.counter = counter 38 return str(counter)39 return "visit #%s" % counter 39 40 index.exposed = True 41 40 42 cpg.root = Root() 41 43 cpg.config.update({ 42 44 '/': { 43 'server. socketPort': 8000,45 'server.logToScreen': False, 44 46 'server.environment': 'production', 45 47 'cacheFilter.on': True, 46 48 } 47 49 }) 48 cpg.server.start()49 """50 config = ""51 50 52 51 53 def test(infoMap, failedList, skippedList): 54 print " Testing cacheFilter ...", 55 testList = [ 56 ('/', "cpg.response.body == '1'"), 57 ('/', "cpg.response.body == '1'"), 58 ] 59 helper.checkPageResult('cacheFilter', infoMap, code, testList, failedList) 52 import unittest 53 import helper 60 54 55 class CacheFilterTest(unittest.TestCase): 56 57 def testCaching(self): 58 for trial in xrange(2): 59 helper.request("/") 60 self.assertEqual(cpg.response.body, 'visit #1') 61 62 if __name__ == '__main__': 63 cpg.server.start(initOnly=True) 64 unittest.main() branches/ticket-177/cherrypy/test/test_combinedfilters.py
r251 r256 26 26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 27 """ 28 import helper, gzip, StringIO29 28 30 code = r""" 29 import gzip, StringIO 31 30 from cherrypy import cpg 31 32 32 europoundUnicode = u'\x80\xa3' 33 33 34 class Root: 34 35 def index(self): … … 37 38 yield europoundUnicode 38 39 index.exposed = True 40 39 41 cpg.root = Root() 40 42 cpg.config.update({ 41 43 '/': { 42 'server. socketPort': 8000,44 'server.logToScreen': False, 43 45 'server.environment': 'production', 44 46 'gzipFilter.on': True, … … 46 48 } 47 49 }) 48 cpg.server.start() 49 """ 50 config = "" 51 europoundUnicode = u'\x80\xa3' 52 expectedResult = (u"Hello," + u"world" + europoundUnicode).encode('utf-8') 53 zbuf = StringIO.StringIO() 54 zfile = gzip.GzipFile(mode='wb', fileobj = zbuf, compresslevel = 9) 55 zfile.write(expectedResult) 56 zfile.close() 50 cpg.server.start(initOnly=True) 57 51 58 testList = [ 59 ('/', '%s in cpg.response.body' % repr(zbuf.getvalue()[:3])), 60 ] 52 import unittest 53 import helper 61 54 62 def test(infoMap, failedList, skippedList): 63 print " Testing combined filters ...", 64 # Gzip compression doesn't always return the same exact result ! 65 # So we just check that the first few bytes are the same 66 helper.checkPageResult('combined filters', infoMap, code, testList, failedList, extraRequestHeader = [("Accept-Encoding", "gzip")]) 55 class CombinedFiltersTest(unittest.TestCase): 56 57 def testCombinedFilters(self): 58 expectedResult = (u"Hello,world" + europoundUnicode).encode('utf-8') 59 zbuf = StringIO.StringIO() 60 zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9) 61 zfile.write(expectedResult) 62 zfile.close() 63 64 helper.request("/", headers=[("Accept-Encoding", "gzip")]) 65 self.assertEqual(zbuf.getvalue()[:3] in cpg.response.body, True) 66 67 68 if __name__ == '__main__': 69 unittest.main() branches/ticket-177/cherrypy/test/test_core.py
r251 r256 29 29 """Basic tests for the CherryPy core: request handling.""" 30 30 31 import helper32 33 code = """34 31 from cherrypy import cpg 32 import types 35 33 36 34 class Root: … … 38 36 return "hello" 39 37 index.exposed = True 38 40 39 cpg.root = Root() 41 40 42 41 43 import types44 42 class TestType(type): 45 43 def __init__(cls, name, bases, dct): … … 79 77 return "hello" 80 78 79 81 80 class Redirect(Test): 82 81 83 82 def index(self): 84 83 return "child" 84 85 85 86 86 class Flatten(Test): … … 102 102 yield chunk 103 103 104 104 105 class Error(Test): 105 106 … … 119 120 return inner() 120 121 122 121 123 cpg.config.update({ 122 124 '/': { 123 'server. socketPort': 8000,125 'server.logToScreen': False, 124 126 'server.environment': 'production', 125 127 } 126 128 }) 127 cpg.server.start() 128 """ 129 cpg.server.start(initOnly=True) 129 130 130 testList = [ 131 ("/status/", "cpg.response.body == 'normal' and cpg.response.status == '200 OK'"), 132 ("/status/blank", "cpg.response.body == '' and cpg.response.status == '200 OK'"), 133 ("/status/illegal", "cpg.response.body == 'oops' and cpg.response.status == '500 Internal error'"), 134 ("/status/unknown", "cpg.response.body == 'funky' and cpg.response.status == '431 My custom error'"), 135 ("/status/bad", "cpg.response.body == 'hello' and cpg.response.status == '500 Internal error'"), 131 import unittest 132 import helper 136 133 137 ("/redirect/", "cpg.response.body == 'child' and cpg.response.status == '200 OK'"), 138 ("/redirect", "cpg.response.body == '' and cpg.response.status == '302 Found'"), 134 class CoreRequestHandlingTest(unittest.TestCase): 135 136 def testStatus(self): 137 helper.request("/status/") 138 self.assertEqual(cpg.response.body, 'normal') 139 self.assertEqual(cpg.response.status, '200 OK') 140 141 helper.request("/status/blank") 142 self.assertEqual(cpg.response.body, '') 143 self.assertEqual(cpg.response.status, '200 OK') 144 145 helper.request("/status/illegal") 146 self.assertEqual(cpg.response.body, 'oops') 147 self.assertEqual(cpg.response.status, '500 Internal error') 148 149 helper.request("/status/unknown") 150 self.assertEqual(cpg.response.body, 'funky') 151 self.assertEqual(cpg.response.status, '431 My custom error') 152 153 helper.request("/status/bad") 154 self.assertEqual(cpg.response.body, 'hello') 155 self.assertEqual(cpg.response.status, '500 Internal error') 156 157 def testRedirect(self): 158 helper.request("/redirect/") 159 self.assertEqual(cpg.response.body, 'child') 160 self.assertEqual(cpg.response.status, '200 OK') 161 162 &n
