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

Changeset 256

Show
Ignore:
Timestamp:
06/08/05 16:20:47
Author:
fumanchu
Message:

Reworked test suite to 1) use unittest, 2) do no exec, eval or code generation (although there are some fancy module reloads), 3) use all-lowercase filenames, and 4) run servers in the main process.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/ticket-177/cherrypy/_cphttpserver.py

    r253 r256  
    293293     
    294294    # 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 
    296299     
    297300    # Select the appropriate server based on config options 
  • branches/ticket-177/cherrypy/cpg.py

    r199 r256  
    3333from __init__ import __version__ 
    3434 
     35_httpserver = None 
     36 
    3537# import server module 
    3638import _cpserver as server 
  • branches/ticket-177/cherrypy/test/__init__.py

    r8 r256  
     1"""Regression test suite for CherryPy. 
     2 
     3Run 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  
    2626OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
    2727""" 
    28 import os,urllib,time,sys,signal,socket,httplib,os.path  
    2928 
    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') + '"') 
     29import os, os.path 
     30import time 
     31import sys 
     32import socket 
     33import httplib 
     34import threading 
     35from cherrypy import cpg 
     36 
     37 
     38HOST = "127.0.0.1" 
     39PORT = 8000 
     40 
     41def 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 
     51def startServer(serverClass=None): 
     52    if serverClass is None: 
     53        cpg.server.start(initOnly=True) 
    3554    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) 
    4061 
    41 class EmptyClass: 
    42     pass 
    4362 
    44 def getPage(url, cookies, extraRequestHeader = []): 
     63def 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 
     70def getPage(url, headers=None, method="GET"): 
     71     
    4572    # The trying 10 times is simply in case of socket errors. 
    4673    # Normal case--it should run once. 
     
    4875    while trial < 10: 
    4976        try: 
    50             conn = httplib.HTTPConnection('127.0.0.1:%s' % PORT
     77            conn = httplib.HTTPConnection('%s:%s' % (HOST, PORT)
    5178##            conn.set_debuglevel(1) 
    52             conn.putrequest("GET", url) 
    53 ##            conn.putheader("Host", "127.0.0.1") 
     79            conn.putrequest(method.upper(), url) 
    5480             
    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: 
    6182                conn.putheader(key, value) 
    62              
    6383            conn.endheaders() 
    6484             
     85            # Handle response 
    6586            response = conn.getresponse() 
    6687             
    67             cookies = response.msg.getallmatchingheaders("Set-Cookie"
     88            cpg.response.status = "%s %s" % (response.status, response.reason
    6889             
    69             cpg = EmptyClass() 
    70             cpg.response = EmptyClass() 
    7190            cpg.response.headerMap = {} 
    72             cpg.response.status = "%s %s" % (response.status, response.reason) 
    7391            for line in response.msg.headers: 
    7492                key, value = line.split(":", 1) 
    7593                cpg.response.headerMap[key.strip()] = value.strip() 
     94            cpg.response.headers = cpg.response.headerMap 
    7695             
    77             cpg.response.body = response.read() 
     96            b = cpg.response.body = response.read() 
     97##            print "body:", repr(b) 
    7898             
    7999            conn.close() 
    80             return cpg, cookies 
     100            return 
    81101        except socket.error: 
    82102            trial += 1 
     
    86106                time.sleep(0.5) 
    87107 
    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 server 
    92         #   to shutdown 
    93         time.sleep(1.1) 
    94     return 
    95108 
    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 
     109def 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) 
    118126 
    119 def prepareCode(code, serverClass): 
    120     f = open('testsite.py', 'w') 
    121      
    122     includePathsToSysPath = """ 
    123 import sys,os,os.path 
    124 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 = True 
    134 cpg.root.shutdown = Shutdown() 
    135 def f(*a, **kw): return "" 
    136 cpg.root._cpLogMessage = f 
    137 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'" % serverClass 
    142     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 = 8000 
    150 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 False 
    156     except socket.error: 
    157         return True 
    158  
    159 def checkPageResult(testName, infoMap, code, testList, failedList, extraConfig = '', extraRequestHeader = []): 
    160     response = None 
    161      
    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 = %s 
    181 server.environment = "production" 
    182 server.logToScreen = False 
    183 ''' % PORT) 
    184             f.write(modeConfig + "\n") 
    185             f.close() 
    186              
    187             pid = startServer(infoMap) 
    188             passed=True 
    189             cookies=None 
    190             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 = 0 
    196                     print "*** FAILED ***", 
    197                     break 
    198             shutdownServer(mode) 
    199             if passed: 
    200                 sys.stdout.write("ok ") 
    201                 sys.stdout.flush() 
    202             if not passed: 
    203                 break 
    204     if passed: 
    205         print "passed" 
    206     sys.stdout.flush() 
    207     return response 
    208  
  • branches/ticket-177/cherrypy/test/test.py

    r243 r256  
    2727""" 
    2828 
    29 # Regression test suite for CherryPy 
     29import time 
     30import sys 
     31import os 
     32import unittest 
    3033 
    31 import sys,os,os.path 
    32 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) 
    4134 
    42 python2={} 
    43 python2[3]={}    # Infos about python-2.3 
    44 python2[4]={}    # Infos about python-2.4 
     35class 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) 
    4543 
    46 # Edit these lines to match your setup 
    47 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" 
    5344 
    54 print 
     45class 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 
    5569 
    56 print "Examining your system..." 
    57 print 
    58 print "Python version used to run this test script:", sys.version.split()[0] 
    59 print 
    60 import buildInfoMap 
    61 python2 = buildInfoMap.buildInfoMap(python2) 
    6270 
    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) 
     71class ReloadingTestLoader(unittest.TestLoader): 
     72     
     73    def loadTestsFromName(self, name, module=None): 
     74        """Return a suite of all tests cases given a string specifier. 
    7175 
    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. 
    7479 
    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 
    78123 
    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 
     124CPTestLoader = ReloadingTestLoader() 
    103125 
    104 testList = [ 
    105     'testBaseUrlFilter', 
    106     'testCacheFilter', 
    107     'testCombinedFilters', 
    108     'testCore', 
    109     'testDecodingEncodingFilter', 
    110     'testGzipFilter', 
    111     'testLogDebugInfoFilter', 
    112     'testObjectMapping', 
    113     'testStaticFilter', 
    114     'testVirtualHostFilter', 
    115 ] 
    116126 
    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 
     127def 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') 
    130180 
    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') 
     181if __name__ == '__main__': 
     182    main() 
  • branches/ticket-177/cherrypy/test/test_baseurl_filter.py

    r251 r256  
    2626OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
    2727""" 
    28 import helper 
    2928 
    30 code = r""" 
    3129from cherrypy import cpg 
    3230from cherrypy.lib import httptools 
     31 
    3332class Root: 
    3433    def index(self): 
    3534        return httptools.redirect('dummy') 
    3635    index.exposed = True 
     36 
    3737cpg.root = Root() 
    3838cpg.config.update({ 
    3939    '/': { 
    40         'server.socketPort': 8000, 
    4140        'server.environment': 'production', 
    4241        'baseUrlFilter.on': True, 
     
    4443    } 
    4544}) 
    46 cpg.server.start() 
    47 """ 
    48 config = "" 
    4945 
    50 testList = [ 
    51     ('/', "cpg.response.headerMap['Location'] == " 
    52             "'http://www.mydomain.com/dummy'") 
    53 
     46import unittest 
     47import helper 
    5448 
    55 def test(infoMap, failedList, skippedList): 
    56     print "    Testing baseUrlFilter ...", 
    57     helper.checkPageResult('baseUrlFilter', infoMap, code, testList, failedList) 
     49class 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 
     57if __name__ == '__main__': 
     58    cpg.server.start(initOnly=True) 
     59    unittest.main() 
     60 
  • branches/ticket-177/cherrypy/test/test_cache_filter.py

    r251 r256  
    2626OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
    2727""" 
    28 import helper, time 
    2928 
    30 code = r""" 
    3129from cherrypy import cpg 
    3230import time 
     31 
    3332class Root: 
     33    def __init__(self): 
     34        cpg.counter = 0 
     35     
    3436    def index(self): 
    35         counter = getattr(cpg, 'counter', 0) 
    36         counter += 1 
     37        counter = cpg.counter + 1 
    3738        cpg.counter = counter 
    38         return str(counter) 
     39        return "visit #%s" % counter 
    3940    index.exposed = True 
     41 
    4042cpg.root = Root() 
    4143cpg.config.update({ 
    4244    '/': { 
    43         'server.socketPort': 8000
     45        'server.logToScreen': False
    4446        'server.environment': 'production', 
    4547        'cacheFilter.on': True, 
    4648    } 
    4749}) 
    48 cpg.server.start() 
    49 """ 
    50 config = "" 
    5150 
    5251 
    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) 
     52import unittest 
     53import helper 
    6054 
     55class 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 
     62if __name__ == '__main__': 
     63    cpg.server.start(initOnly=True) 
     64    unittest.main() 
  • branches/ticket-177/cherrypy/test/test_combinedfilters.py

    r251 r256  
    2626OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
    2727""" 
    28 import helper, gzip, StringIO 
    2928 
    30 code = r""" 
     29import gzip, StringIO 
    3130from cherrypy import cpg 
     31 
    3232europoundUnicode = u'\x80\xa3' 
     33 
    3334class Root: 
    3435    def index(self): 
     
    3738        yield europoundUnicode 
    3839    index.exposed = True 
     40 
    3941cpg.root = Root() 
    4042cpg.config.update({ 
    4143    '/': { 
    42         'server.socketPort': 8000
     44        'server.logToScreen': False
    4345        'server.environment': 'production', 
    4446        'gzipFilter.on': True, 
     
    4648    } 
    4749}) 
    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() 
     50cpg.server.start(initOnly=True) 
    5751 
    58 testList = [ 
    59     ('/', '%s in cpg.response.body' % repr(zbuf.getvalue()[:3])), 
    60 
     52import unittest 
     53import helper 
    6154 
    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")]) 
     55class 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 
     68if __name__ == '__main__': 
     69    unittest.main() 
  • branches/ticket-177/cherrypy/test/test_core.py

    r251 r256  
    2929"""Basic tests for the CherryPy core: request handling.""" 
    3030 
    31 import helper 
    32  
    33 code = """ 
    3431from cherrypy import cpg 
     32import types 
    3533 
    3634class Root: 
     
    3836        return "hello" 
    3937    index.exposed = True 
     38 
    4039cpg.root = Root() 
    4140 
    4241 
    43 import types 
    4442class TestType(type): 
    4543    def __init__(cls, name, bases, dct): 
     
    7977        return "hello" 
    8078 
     79 
    8180class Redirect(Test): 
    8281     
    8382    def index(self): 
    8483        return "child" 
     84 
    8585 
    8686class Flatten(Test): 
     
    102102            yield chunk 
    103103 
     104 
    104105class Error(Test): 
    105106     
     
    119120        return inner() 
    120121 
     122 
    121123cpg.config.update({ 
    122124    '/': { 
    123         'server.socketPort': 8000
     125        'server.logToScreen': False
    124126        'server.environment': 'production', 
    125127    } 
    126128}) 
    127 cpg.server.start() 
    128 """ 
     129cpg.server.start(initOnly=True) 
    129130 
    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'"), 
     131import unittest 
     132import helper 
    136133 
    137     ("/redirect/", "cpg.response.body == 'child' and cpg.response.status == '200 OK'"), 
    138     ("/redirect", "cpg.response.body == '' and cpg.response.status == '302 Found'"), 
     134class 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