Commits

Anonymous committed 9eda626

Renamed "unittest" to "test"

Comments (0)

Files changed (8)

+"""
+Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""
+
+# Regression test suite for CherryPy
+
+import sys
+if len(sys.argv) == 2 and sys.argv[1] in ('-h', '--help'):
+    print "Usage: unittest.py [testName+]"
+    sys.exit(0)
+
+python2={}
+python2[3]={}    # Infos about python-2.3
+python2[4]={}    # Infos about python-2.4
+
+# Edit these lines to match your setup
+if sys.platform=="win32":
+    python2[3]['path']="c:\\python23\\python"
+    python2[4]['path']="c:\\python24\\python"
+else:
+    python2[3]['path']="python2.3"
+    python2[4]['path']="python2.4"
+
+print "Checking that port 8000 is free...",
+try:
+    import socket
+    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    s.connect(('127.0.0.1', 8000))
+    s.close()
+    print "\n### Error: port 8000 is busy. This port must be free to run this test script"
+    sys.exit(-1)
+except socket.error:
+    print "OK"
+
+print
+
+print "Examining your system..."
+print
+print "Python version used to run this test script:", sys.version.split()[0]
+print
+import buildInfoMap
+python2 = buildInfoMap.buildInfoMap(python2)
+
+print
+print "Checking CherryPy version..."
+import os
+try:
+    import cherrypy
+except ImportError:
+    print "Error: couln't find CherryPy !"
+    os._exit(-1)
+
+print "    Found version " + cherrypy.__version__
+print
+
+print "Testing CherryPy..."
+failedList=[]
+skippedList=[]
+
+tutorialTestList = [
+    ('01', ['/'], ['Hello world!']),
+    ('02', ['/showMessage'], ['Hello world!']),
+    ('03', ['/greetUser?name=Bob'], ["Hey Bob, what's up?"]),
+    ('04', ['/links/extra/'], ['\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        ']),
+    ('05', ['/another/'], ['\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        ']),
+    ('06', ['/'], ['\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        ']), 
+    ('07', ['/hendrik'], ['Hendrik Mans, CherryPy co-developer & crazy German (<a href="./">back</a>)']), 
+    ('08', ['/', '/'], ["\n            During your current session, you've viewed this\n            page 1 times! Your life is a patio of fun!\n        ", "\n            During your current session, you've viewed this\n            page 2 times! Your life is a patio of fun!\n        "]), 
+    ('09', ['/'], ['<html><body><h2>Generators rule!</h2><h3>List of users:</h3>Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/></body></html>']), 
+]
+
+testList = [
+    'testObjectMapping',
+    'testFilter1',
+]
+
+if len(sys.argv) > 1:
+    # Some specific tests were specified on the command line
+    # Limit the tests to these ones
+    newTutorialTestList = []
+    newTestList = []
+    for number, urlList, resultList in tutorialTestList:
+        if "tutorial%s" % number in sys.argv[1:]:
+            newTutorialTestList.append([number, urlList, resultList])
+    for t in testList:
+        if t in sys.argv[1:]:
+            newTestList.append(t)
+    tutorialTestList = newTutorialTestList
+    testList = newTestList
+
+import helper
+
+for version, infoMap in python2.items():
+    print
+    print "Running tests for python %s..."%infoMap['exactVersionShort']
+
+    # Run tests based on tutorials
+    for number, urlList, resultList in tutorialTestList:
+        code = open('../tutorial/tutorial%s.py' % number, 'r').read()
+        code = code.replace('tutorial.conf', 'testsite.cfg')
+        print "    Testing tutorial %s..." % number,
+        #if ((version == 1 and number in ('06', '09')) or
+        #        (version == 2 and number in ('09'))):
+        #    print "skipped"
+        #    skippedList.append("Tutorial %s for python2.%s" % (number, version))
+        #    continue
+           
+        helper.checkPageResult('Tutorial %s' % number, infoMap, code, "", urlList, resultList, failedList)
+
+    # Running actual unittests
+    for test in testList:
+        exec("import "+test)
+        eval(test+".test(infoMap, failedList, skippedList)")
+
+print
+print
+print "#####################################"
+print "#####################################"
+print "###          TEST RESULT          ###"
+print "#####################################"
+print "#####################################"
+if skippedList:
+    print
+    print "*** THE FOLLOWING TESTS WERE SKIPPED:"
+    for skipped in skippedList: print skipped
+
+    print "**** THE ABOVE TESTS WERE SKIPPED"
+    print
+
+if failedList:
+    print
+    print "*** THE FOLLOWING TESTS FAILED:"
+    for failed in failedList: print failed
+
+    print "**** THE ABOVE TESTS FAILED"
+    print
+    print "**** Some errors occured: please add a ticket in our Trac system (http://trac.cherrypy.org/cgi-bin/trac.cgi/newticket) with the output of this test script"
+
+else:
+    print
+    print "**** NO TEST FAILED: EVERYTHING LOOKS OK ****"
+
+############"
+# Ideas for future tests:
+#    - test if tabs and whitespaces are handled correctly in source file (option -W)
+#    - test if absolute pathnames work fine on windows
+#    - test sessions
+#    - test threading server
+#    - test forking server
+#    - test process pooling server
+#    - test SSL
+#    - test compilator errors
+#    - test abstract classes
+#    - test hidden classes
+#    ...
+

test/unittest.py

-"""
-Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-
-# Regression test suite for CherryPy
-
-import sys
-if len(sys.argv) == 2 and sys.argv[1] in ('-h', '--help'):
-    print "Usage: unittest.py [testName+]"
-    sys.exit(0)
-
-python2={}
-python2[3]={}    # Infos about python-2.3
-python2[4]={}    # Infos about python-2.4
-
-# Edit these lines to match your setup
-if sys.platform=="win32":
-    python2[3]['path']="c:\\python23\\python"
-    python2[4]['path']="c:\\python24\\python"
-else:
-    python2[3]['path']="python2.3"
-    python2[4]['path']="python2.4"
-
-print "Checking that port 8000 is free...",
-try:
-    import socket
-    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    s.connect(('127.0.0.1', 8000))
-    s.close()
-    print "\n### Error: port 8000 is busy. This port must be free to run this test script"
-    sys.exit(-1)
-except socket.error:
-    print "OK"
-
-print
-
-print "Examining your system..."
-print
-print "Python version used to run this test script:", sys.version.split()[0]
-print
-import buildInfoMap
-python2 = buildInfoMap.buildInfoMap(python2)
-
-print
-print "Checking CherryPy version..."
-import os
-try:
-    import cherrypy
-except ImportError:
-    print "Error: couln't find CherryPy !"
-    os._exit(-1)
-
-print "    Found version " + cherrypy.__version__
-print
-
-print "Testing CherryPy..."
-failedList=[]
-skippedList=[]
-
-tutorialTestList = [
-    ('01', ['/'], ['Hello world!']),
-    ('02', ['/showMessage'], ['Hello world!']),
-    ('03', ['/greetUser?name=Bob'], ["Hey Bob, what's up?"]),
-    ('04', ['/links/extra/'], ['\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        ']),
-    ('05', ['/another/'], ['\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        ']),
-    ('06', ['/'], ['\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        ']), 
-    ('07', ['/hendrik'], ['Hendrik Mans, CherryPy co-developer & crazy German (<a href="./">back</a>)']), 
-    ('08', ['/', '/'], ["\n            During your current session, you've viewed this\n            page 1 times! Your life is a patio of fun!\n        ", "\n            During your current session, you've viewed this\n            page 2 times! Your life is a patio of fun!\n        "]), 
-    ('09', ['/'], ['<html><body><h2>Generators rule!</h2><h3>List of users:</h3>Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/></body></html>']), 
-]
-
-testList = [
-    'testObjectMapping',
-    'testFilter1',
-]
-
-if len(sys.argv) > 1:
-    # Some specific tests were specified on the command line
-    # Limit the tests to these ones
-    newTutorialTestList = []
-    newTestList = []
-    for number, urlList, resultList in tutorialTestList:
-        if "tutorial%s" % number in sys.argv[1:]:
-            newTutorialTestList.append([number, urlList, resultList])
-    for t in testList:
-        if t in sys.argv[1:]:
-            newTestList.append(t)
-    tutorialTestList = newTutorialTestList
-    testList = newTestList
-
-import helper
-
-for version, infoMap in python2.items():
-    print
-    print "Running tests for python %s..."%infoMap['exactVersionShort']
-
-    # Run tests based on tutorials
-    for number, urlList, resultList in tutorialTestList:
-        code = open('../tutorial/tutorial%s.py' % number, 'r').read()
-        code = code.replace('tutorial.conf', 'testsite.cfg')
-        print "    Testing tutorial %s..." % number,
-        #if ((version == 1 and number in ('06', '09')) or
-        #        (version == 2 and number in ('09'))):
-        #    print "skipped"
-        #    skippedList.append("Tutorial %s for python2.%s" % (number, version))
-        #    continue
-           
-        helper.checkPageResult('Tutorial %s' % number, infoMap, code, "", urlList, resultList, failedList)
-
-    # Running actual unittests
-    for test in testList:
-        exec("import "+test)
-        eval(test+".test(infoMap, failedList, skippedList)")
-
-print
-print
-print "#####################################"
-print "#####################################"
-print "###          TEST RESULT          ###"
-print "#####################################"
-print "#####################################"
-if skippedList:
-    print
-    print "*** THE FOLLOWING TESTS WERE SKIPPED:"
-    for skipped in skippedList: print skipped
-
-    print "**** THE ABOVE TESTS WERE SKIPPED"
-    print
-
-if failedList:
-    print
-    print "*** THE FOLLOWING TESTS FAILED:"
-    for failed in failedList: print failed
-
-    print "**** THE ABOVE TESTS FAILED"
-    print
-    print "**** Some errors occured: please add a ticket in our Trac system (http://trac.cherrypy.org/cgi-bin/trac.cgi/newticket) with the output of this test script"
-
-else:
-    print
-    print "**** NO TEST FAILED: EVERYTHING LOOKS OK ****"
-
-############"
-# Ideas for future tests:
-#    - test if tabs and whitespaces are handled correctly in source file (option -W)
-#    - test if absolute pathnames work fine on windows
-#    - test sessions
-#    - test threading server
-#    - test forking server
-#    - test process pooling server
-#    - test SSL
-#    - test compilator errors
-#    - test abstract classes
-#    - test hidden classes
-#    ...
-
Add a comment to this file

unittest/__init__.py

Empty file removed.

unittest/buildInfoMap.py

-"""
-Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-
-import os, sys
-
-def buildInfoMap(python2):
-    print "Checking which python versions are installed..."
-    for version, infoMap in python2.items():
-        # Check if this version of python is installed:
-        path=infoMap.get('path', "python2.%s" % version)
-        if path:
-            exactVersion=os.popen('%s -c "import sys; import cherrypy; print sys.version; print cherrypy.__version__"'%path).read().strip()
-        if path and exactVersion and exactVersion.find('Traceback') == -1:
-            exactVersionShort=exactVersion.split()[0]
-            print "    Found python version %s with CherryPy version %s " % (exactVersionShort, exactVersion.split()[-1])
-            python2[version]['exactVersion']=exactVersion
-            python2[version]['exactVersionShort']=exactVersionShort
-            python2[version]['path']=path
-            if exactVersionShort.find("2.%s"%version)!=0:
-                print
-                print "*************************"
-                print "Error: the path for python2.%s appears to run python%s"%(version, exactVersionShort)
-                print 'By default, this script expects the python binaries to be in your PATH and to be called "python2.1", "python2.2", ...'
-                print "If your setup is different, please edit this script and change the path for the python binary"
-                sys.exit(-1)
-        else:
-            print "    Version 2.%s not found (or CherryPy not installed for this version)"%version
-            del python2[version]
-
-    if not python2:
-        print
-        print "*************************"
-        print "Error: couldn't find any python distribution on your machine."
-        print 'By default, this script expects the python binaries to be in your PATH and to be called "python2.1", "python2.2", ...'
-        print "If your setup is different, please edit this script and change the path for the python binary"
-        sys.exit(-1)
-    print
-    print "Finding out what modules are installed for these versions..."
-    for version, infoMap in python2.items():
-        print "    Checking modules for python%s..."%infoMap['exactVersionShort']
-
-        # Test if python has fork
-        res=os.popen('%s -c "import sys; sys.stderr=sys.stdout; import os; print hasattr(os,\'fork\')"'%infoMap['path']).read()
-        if res.find('1')!=-1 or res.find('True')!=-1:
-            print "        os.fork available"
-            infoMap['hasFork']=1
-        else:
-            print "        os.fork not available"
-            infoMap['hasFork']=0
-
-        # Test if threads are available
-        res=os.popen('%s -c "import sys; sys.stderr=sys.stdout; import thread"'%infoMap['path']).read()
-        if res.find("ImportError")==-1:
-            print "        thread available"
-            infoMap['hasThread']=1
-        else:
-            print "        thread not available"
-            infoMap['hasThread']=0
-
-        # Test if pyOpenSSL is available
-        res=os.popen('%s -c "import sys; sys.stderr=sys.stdout; from OpenSSL import SSL"'%infoMap['path']).read()
-        if res.find("ImportError")==-1:
-            print "        pyOpenSSL available"
-            infoMap['hasPyOpenSSL']=1
-        else:
-            print "        pyOpenSSL not available"
-            infoMap['hasPyOpenSSL']=0
-
-        # Test if xmlrpclib is available
-        res=os.popen('%s -c "import sys; sys.stderr=sys.stdout; import xmlrpclib"'%infoMap['path']).read()
-        if res.find("ImportError")==-1:
-            print "        xmlrpclib available"
-            infoMap['hasXmlrpclib']=1
-        else:
-            print "        xmlrpclib not available"
-            infoMap['hasXmlrpclib']=0
-
-    return python2

unittest/helper.py

-"""
-Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-import os,urllib,time,sys,signal,socket,httplib
-
-def startServer(infoMap):
-    # Start the server in another thread
-    if not hasattr(os, "fork"): # win32 mostly
-        pid=os.spawnl(os.P_NOWAIT, infoMap['path'], infoMap['path'], 'testsite.py')
-    else:
-        pid=os.fork()
-        if not pid:
-            os.execlp(infoMap['path'],infoMap['path'],'testsite.py')
-    return pid
-
-def getPage(url, cookies, isSSL=0, extraRequestHeader = []):
-    data=""
-    i=0
-    response = None
-    while i<10:
-        try:
-            if isSSL:
-                conn=httplib.HTTPSConnection('127.0.0.1:8000')
-            else:
-                conn=httplib.HTTPConnection('127.0.0.1:8000')
-
-            conn.putrequest("GET", url)
-
-            conn.putheader("Host", "127.0.0.1")
-            if cookies:
-                cookieList = []
-                for cookie in cookies:
-                    i = cookie.find(' ')
-                    j = cookie.find(';')
-                    cookieList.append(cookie[i+1:j])
-                cookieStr = '; '.join(cookieList)
-                conn.putheader("Cookie", cookies[:j])
-
-            for key, value in extraRequestHeader:
-                conn.putheader(key, value)
-
-            conn.endheaders()
-
-            response=conn.getresponse()
-
-            cookies=response.msg.getallmatchingheaders("Set-Cookie")
-
-            data=response.read()
-
-            conn.close()
-            break
-        except socket.error:
-            time.sleep(0.5)
-        i+=1
-    return data, cookies, response
-
-def getXmlrpc(url, func, isSSL=0):
-    import xmlrpclib
-    http="http"
-    if isSSL: http+="s"
-    if url: url='/'+url
-    data=""
-    i=0
-    try:
-        while i<10:
-            try:
-                testsvr=xmlrpclib.Server(http+"://127.0.0.1:8000"+url)
-                data=eval("testsvr.%s"%func)
-                break
-            except socket.error:
-                time.sleep(0.5)
-            i+=1
-    except xmlrpclib.Fault, msg:
-        return msg
-    return data
-
-
-def shutdownServer(pid, mode, isSSL=0):
-    if isSSL: h="https"
-    else: h="http"
-    if mode=='t':
-        u=urllib.urlopen(h+"://127.0.0.1:8000/shutdown/thread")
-        if hasattr(socket, 'sslerror'): sslError = socket.sslerror
-        else: sslError = 'dummy'
-        try: u=urllib.urlopen(h+"://127.0.0.1:8000/shutdown/dummy")
-        except IOError: pass
-        except sslError: pass
-        except AttributeError: pass # Happens on Mac OS X when run with Python-2.3
-    elif mode=='tp':
-        try: sslError = socket.sslerror
-        except: sslError = 'dummy'
-        u=urllib.urlopen(h+"://127.0.0.1:8000/shutdown/thread")
-        try: u=urllib.urlopen(h+"://127.0.0.1:8000/shutdown/dummy")
-        except IOError: pass # Happens on Windows
-        except sslError: pass # Happens on Windows for https requests
-    else:
-        try:
-            u=urllib.urlopen(h+"://127.0.0.1:8000/shutdown/regular")
-        except IOError: pass
-        except AttributeError: pass # For Python2.3
-
-def checkResult(testName, infoMap, serverMode, result, expectedResult, failedList, exactResult):
-    if result == expectedResult or ((not exactResult) and expectedResult in result):
-        return True
-    else:
-        failedList.append(testName+" for python%s"%infoMap['exactVersionShort']+" in "+serverMode+" mode failed: expected result was:\n%s, actual result was:\n%s"%(repr(expectedResult), repr(result)))
-        return False
-
-def prepareCode(code):
-    f = open('testsite.py', 'w')
-    beforeStart = '''
-class Shutdown:
-    def dummy(self):
-        return "OK"
-    dummy.exposed = True
-    def regular(self):
-        import os
-        os._exit(0)
-    regular.exposed = True
-    def thread(self):
-        import threading
-        for t in threading.enumerate(): t.setName("NOT RUNNING")
-        return "OK"
-    thread.exposed = True
-cpg.root.shutdown = Shutdown()
-def f(*a, **kw): return ""
-cpg.root._cpLogMessage = f
-'''
-    f.write(code.replace('cpg.server.start', beforeStart + 'cpg.server.start'))
-    f.close()
-
-def checkPageResult(testName, infoMap, code, config, urlList, expectedResultList, failedList, exactResult=True, isSSL=0, extraRequestHeader=[], expectedHeaderList=[]):
-    response = None
-    prepareCode(code)
-    # Try it in all 3 modes (regular, threading, threadPooling) (we're missing forking and process pooling)
-    modeList=[('r',''), ('tp', 'threadPool=3')]
-    # modeList=[('r','')] # TODO
-    for mode,modeConfig in modeList:
-        f=open("testsite.cfg", "w")
-        f.write(config)
-        f.write('''
-[session]
-storageType=ram
-[server]
-socketPort = 8000
-''')
-        f.write(config+"\n"+modeConfig)
-        f.close()
-
-        pid = startServer(infoMap)
-        passed=True
-        cookies=None
-        for i in range(len(urlList)):
-            url=urlList[i]
-            expectedResult=expectedResultList[i]
-            result, cookies, response=getPage(url, cookies, isSSL, extraRequestHeader)
-            if expectedHeaderList:
-                if response.status != expectedHeaderList[0]:
-                    failedList.append(testName+" for python%s"%infoMap['exactVersionShort']+" in "+mode+" mode failed: expected result status was %s, result status was %s"%(expectedHeaderList[0], response.status))
-                    passed=0
-                    print "*** FAILED ***"
-                    break
-            if not checkResult(testName, infoMap, mode, result, expectedResult, failedList, exactResult):
-                passed=0
-                print "*** FAILED ***"
-                break
-        shutdownServer(pid, mode, isSSL)
-        if passed:
-            print mode+"...",
-            sys.stdout.flush()
-        else: break
-    if passed: print "passed"
-    sys.stdout.flush()
-    return response
-

unittest/testFilter1.py

-"""
-Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-import helper, gzip, StringIO
-
-code = r"""
-from cherrypy import cpg
-import cherrypy.lib.filter.gzipfilter as gzipfilter
-import cherrypy.lib.filter.encodingfilter as encodingfilter
-import cherrypy.lib.filter.generatorfilter as generatorfilter
-europoundUnicode = u'\x80\xa3'
-class Root:
-    _cpFilterList = [
-        generatorfilter.GeneratorFilter(),
-        encodingfilter.EncodingFilter(),
-        gzipfilter.GzipFilter()
-    ]
-    def index(self):
-        yield u"Hello,"
-        yield u"world"
-        yield europoundUnicode
-    index.exposed = True
-cpg.root = Root()
-cpg.server.start(configFile = 'testsite.cfg')
-"""
-config = ""
-europoundUnicode = u'\x80\xa3'
-expectedResult = (u"Hello," + u"world" + europoundUnicode).encode('utf-8')
-
-def test(infoMap, failedList, skippedList):
-    print "    Testing Filters (1) ...",
-    zbuf = StringIO.StringIO()
-    zfile = gzip.GzipFile(mode='wb', fileobj = zbuf, compresslevel = 9)
-    zfile.write(expectedResult)
-    zfile.close()
-    # Gzip compression doesn't always return the same exact result !
-    # So we just check that the first few bytes are the same
-    helper.checkPageResult('Object mapping', infoMap, code, config, [""], [zbuf.getvalue()[:3]], failedList, exactResult = False, extraRequestHeader = [("Accept-Encoding", "gzip")])

unittest/testObjectMapping.py

-"""
-Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-
-# TODO: Have a real object mapping test once the object mapping -> URI
-#   algorithm is finalized
-
-import helper
-
-code = """
-from cherrypy import cpg
-class Root:
-    def index(self, name="world"):
-        return name
-    index.exposed = True
-    def default(self, *params):
-        return "default:"+repr(params)
-    default.exposed = True
-    def other(self):
-        return "other"
-    other.exposed = True
-    def notExposed(self):
-        return "not exposed"
-class Dir1:
-    def index(self):
-        return "index for dir1"
-    index.exposed = True
-    def default(self, *params):
-        return repr(params)
-    default.exposed = True
-class Dir2:
-    def index(self):
-        return "index for dir2, path is:" + cpg.request.path
-    index.exposed = True
-    def method(self):
-        return "method for dir2"
-    method.exposed = True
-cpg.root = Root()
-cpg.root.dir1 = Dir1()
-cpg.root.dir1.dir2 = Dir2()
-cpg.server.start(configFile = 'testsite.cfg')
-"""
-config = ""
-testList = [
-    ("", "world"),
-    ("/this/method/does/not/exist", "default:('this', 'method', 'does', 'not', 'exist')"),
-    ("/other", "other"),
-    ("/notExposed", "default:('notExposed',)"),
-    ("/dir1/dir2/", "index for dir2, path is:/dir1/dir2/"),
-]
-urlList = [test[0] for test in testList]
-expectedResultList = [test[1] for test in testList]
-
-def test(infoMap, failedList, skippedList):
-    print "    Testing object mapping...",
-    helper.checkPageResult('Object mapping', infoMap, code, config, urlList, expectedResultList, failedList)

unittest/unittest.py

-"""
-Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-    * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-"""
-
-# Regression test suite for CherryPy
-
-import sys
-if len(sys.argv) == 2 and sys.argv[1] in ('-h', '--help'):
-    print "Usage: unittest.py [testName+]"
-    sys.exit(0)
-
-python2={}
-python2[3]={}    # Infos about python-2.3
-python2[4]={}    # Infos about python-2.4
-
-# Edit these lines to match your setup
-if sys.platform=="win32":
-    python2[3]['path']="c:\\python23\\python"
-    python2[4]['path']="c:\\python24\\python"
-else:
-    python2[3]['path']="python2.3"
-    python2[4]['path']="python2.4"
-
-print "Checking that port 8000 is free...",
-try:
-    import socket
-    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    s.connect(('127.0.0.1', 8000))
-    s.close()
-    print "\n### Error: port 8000 is busy. This port must be free to run this test script"
-    sys.exit(-1)
-except socket.error:
-    print "OK"
-
-print
-
-print "Examining your system..."
-print
-print "Python version used to run this test script:", sys.version.split()[0]
-print
-import buildInfoMap
-python2 = buildInfoMap.buildInfoMap(python2)
-
-print
-print "Checking CherryPy version..."
-import os
-try:
-    import cherrypy
-except ImportError:
-    print "Error: couln't find CherryPy !"
-    os._exit(-1)
-
-print "    Found version " + cherrypy.__version__
-print
-
-print "Testing CherryPy..."
-failedList=[]
-skippedList=[]
-
-tutorialTestList = [
-    ('01', ['/'], ['Hello world!']),
-    ('02', ['/showMessage'], ['Hello world!']),
-    ('03', ['/greetUser?name=Bob'], ["Hey Bob, what's up?"]),
-    ('04', ['/links/extra/'], ['\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        ']),
-    ('05', ['/another/'], ['\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        ']),
-    ('06', ['/'], ['\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        ']), 
-    ('07', ['/hendrik'], ['Hendrik Mans, CherryPy co-developer & crazy German (<a href="./">back</a>)']), 
-    ('08', ['/', '/'], ["\n            During your current session, you've viewed this\n            page 1 times! Your life is a patio of fun!\n        ", "\n            During your current session, you've viewed this\n            page 2 times! Your life is a patio of fun!\n        "]), 
-    ('09', ['/'], ['<html><body><h2>Generators rule!</h2><h3>List of users:</h3>Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/></body></html>']), 
-]
-
-testList = [
-    'testObjectMapping',
-    'testFilter1',
-]
-
-if len(sys.argv) > 1:
-    # Some specific tests were specified on the command line
-    # Limit the tests to these ones
-    newTutorialTestList = []
-    newTestList = []
-    for number, urlList, resultList in tutorialTestList:
-        if "tutorial%s" % number in sys.argv[1:]:
-            newTutorialTestList.append([number, urlList, resultList])
-    for t in testList:
-        if t in sys.argv[1:]:
-            newTestList.append(t)
-    tutorialTestList = newTutorialTestList
-    testList = newTestList
-
-import helper
-
-for version, infoMap in python2.items():
-    print
-    print "Running tests for python %s..."%infoMap['exactVersionShort']
-
-    # Run tests based on tutorials
-    for number, urlList, resultList in tutorialTestList:
-        code = open('../tutorial/tutorial%s.py' % number, 'r').read()
-        code = code.replace('tutorial.conf', 'testsite.cfg')
-        print "    Testing tutorial %s..." % number,
-        #if ((version == 1 and number in ('06', '09')) or
-        #        (version == 2 and number in ('09'))):
-        #    print "skipped"
-        #    skippedList.append("Tutorial %s for python2.%s" % (number, version))
-        #    continue
-           
-        helper.checkPageResult('Tutorial %s' % number, infoMap, code, "", urlList, resultList, failedList)
-
-    # Running actual unittests
-    for test in testList:
-        exec("import "+test)
-        eval(test+".test(infoMap, failedList, skippedList)")
-
-print
-print
-print "#####################################"
-print "#####################################"
-print "###          TEST RESULT          ###"
-print "#####################################"
-print "#####################################"
-if skippedList:
-    print
-    print "*** THE FOLLOWING TESTS WERE SKIPPED:"
-    for skipped in skippedList: print skipped
-
-    print "**** THE ABOVE TESTS WERE SKIPPED"
-    print
-
-if failedList:
-    print
-    print "*** THE FOLLOWING TESTS FAILED:"
-    for failed in failedList: print failed
-
-    print "**** THE ABOVE TESTS FAILED"
-    print
-    print "**** Some errors occured: please add a ticket in our Trac system (http://trac.cherrypy.org/cgi-bin/trac.cgi/newticket) with the output of this test script"
-
-else:
-    print
-    print "**** NO TEST FAILED: EVERYTHING LOOKS OK ****"
-
-############"
-# Ideas for future tests:
-#    - test if tabs and whitespaces are handled correctly in source file (option -W)
-#    - test if absolute pathnames work fine on windows
-#    - test sessions
-#    - test threading server
-#    - test forking server
-#    - test process pooling server
-#    - test SSL
-#    - test compilator errors
-#    - test abstract classes
-#    - test hidden classes
-#    ...
-
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.