Commits

Robert Brewer committed acd079f

Syncing webtest from py2 to py3

Comments (0)

Files changed (2)

py2/cherrypy/test/webtest.py

 from unittest import *
 from unittest import _TextTestResult
 
-from cherrypy._cpcompat import basestring, HTTPConnection, HTTPSConnection, unicodestr
+from cherrypy._cpcompat import basestring, ntob, py3k, HTTPConnection, HTTPSConnection, unicodestr
 
 
 
 
         if type(obj) == types.ModuleType:
             return self.loadTestsFromModule(obj)
-        elif (isinstance(obj, (type, types.ClassType)) and
-              issubclass(obj, TestCase)):
+        elif (((py3k and isinstance(obj, type))
+               or isinstance(obj, (type, types.ClassType)))
+              and issubclass(obj, TestCase)):
             return self.loadTestsFromTestCase(obj)
         elif type(obj) == types.UnboundMethodType:
-            return obj.im_class(obj.__name__)
+            if py3k:
+                return obj.__self__.__class__(obj.__name__)
+            else:
+                return obj.im_class(obj.__name__)
         elif hasattr(obj, '__call__'):
             test = obj()
             if not isinstance(test, TestCase) and \
         sys.stdout.flush()
         while True:
             i = getchar().upper()
+            if not isinstance(i, type("")):
+                i = i.decode('ascii')
             if i not in "BHSUIRX":
                 continue
             print(i.upper())  # Also prints new line
 
     def assertBody(self, value, msg=None):
         """Fail if value != self.body."""
+        if isinstance(value, unicodestr):
+            value = value.encode(self.encoding)
         if value != self.body:
             if msg is None:
                 msg = 'expected body:\n%r\n\nactual body:\n%r' % (value, self.body)
 
     def assertInBody(self, value, msg=None):
         """Fail if value not in self.body."""
+        if isinstance(value, unicodestr):
+            value = value.encode(self.encoding)
         if value not in self.body:
             if msg is None:
                 msg = '%r not in body: %s' % (value, self.body)
 
     def assertNotInBody(self, value, msg=None):
         """Fail if value in self.body."""
+        if isinstance(value, unicodestr):
+            value = value.encode(self.encoding)
         if value in self.body:
             if msg is None:
                 msg = '%r found in body' % value
 
     def assertMatchesBody(self, pattern, msg=None, flags=0):
         """Fail if value (a regex pattern) is not in self.body."""
+        if isinstance(pattern, unicodestr):
+            pattern = pattern.encode(self.encoding)
         if re.search(pattern, self.body, flags) is None:
             if msg is None:
                 msg = 'No match for %r in body' % pattern
 
 def shb(response):
     """Return status, headers, body the way we like from a response."""
-    h = []
-    key, value = None, None
-    for line in response.msg.headers:
-        if line:
-            if line[0] in " \t":
-                value += line.strip()
-            else:
-                if key and value:
-                    h.append((key, value))
-                key, value = line.split(":", 1)
-                key = key.strip()
-                value = value.strip()
-    if key and value:
-        h.append((key, value))
+    if py3k:
+        h = response.getheaders()
+    else:
+        h = []
+        key, value = None, None
+        for line in response.msg.headers:
+            if line:
+                if line[0] in " \t":
+                    value += line.strip()
+                else:
+                    if key and value:
+                        h.append((key, value))
+                    key, value = line.split(":", 1)
+                    key = key.strip()
+                    value = value.strip()
+        if key and value:
+            h.append((key, value))
 
     return "%s %s" % (response.status, response.reason), h, response.read()
 
                 import new
                 conn.putheader = new.instancemethod(putheader, conn, conn.__class__)
                 conn.putrequest(method.upper(), url, skip_host=True)
-            else:
+            elif not py3k:
                 conn.putrequest(method.upper(), url, skip_host=True,
                                 skip_accept_encoding=True)
+            else:
+                import http.client
+                # Replace the stdlib method, which only accepts ASCII url's
+                def putrequest(self, method, url):
+                    if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
+                        self._HTTPConnection__response = None
+                    
+                    if self._HTTPConnection__state == http.client._CS_IDLE:
+                        self._HTTPConnection__state = http.client._CS_REQ_STARTED
+                    else:
+                        raise http.client.CannotSendRequest()
+                    
+                    self._method = method
+                    if not url:
+                        url = b'/'
+                    request = b' '.join((method.encode("ASCII"), url,
+                                         self._http_vsn_str.encode("ASCII")))
+                    self._output(request)
+                import types
+                conn.putrequest = types.MethodType(putrequest, conn)
+                
+                conn.putrequest(method.upper(), url)
 
             for key, value in headers:
-                conn.putheader(key, value)
+                conn.putheader(key, ntob(value, "Latin-1"))
             conn.endheaders()
 
             if body is not None:
             return s, h, b
         except socket.error:
             time.sleep(0.5)
-    raise
+            if trial == 9:
+                raise
 
 
 # Add any exceptions which your web framework handles

py3/cherrypy/test/webtest.py

 be of further significance to your tests).
 """
 
-import http.client
 import os
 import pprint
 import re
 from unittest import *
 from unittest import _TextTestResult
 
-from cherrypy._cpcompat import basestring, HTTPConnection, HTTPSConnection, unicodestr
+from cherrypy._cpcompat import basestring, ntob, py3k, HTTPConnection, HTTPSConnection, unicodestr
 
 
 
 
         if type(obj) == types.ModuleType:
             return self.loadTestsFromModule(obj)
-        elif (isinstance(obj, type) and
-              issubclass(obj, TestCase)):
+        elif (((py3k and isinstance(obj, type))
+               or isinstance(obj, (type, types.ClassType)))
+              and issubclass(obj, TestCase)):
             return self.loadTestsFromTestCase(obj)
         elif type(obj) == types.UnboundMethodType:
-            return obj.__self__.__class__(obj.__name__)
+            if py3k:
+                return obj.__self__.__class__(obj.__name__)
+            else:
+                return obj.im_class(obj.__name__)
         elif hasattr(obj, '__call__'):
             test = obj()
             if not isinstance(test, TestCase) and \
         sys.stdout.flush()
         while True:
             i = getchar().upper()
-            if isinstance(i, bytes):
+            if not isinstance(i, type("")):
                 i = i.decode('ascii')
             if i not in "BHSUIRX":
                 continue
 
     def assertBody(self, value, msg=None):
         """Fail if value != self.body."""
-        if isinstance(value, str):
+        if isinstance(value, unicodestr):
             value = value.encode(self.encoding)
         if value != self.body:
             if msg is None:
 
     def assertInBody(self, value, msg=None):
         """Fail if value not in self.body."""
-        if isinstance(value, str):
+        if isinstance(value, unicodestr):
             value = value.encode(self.encoding)
         if value not in self.body:
             if msg is None:
 
     def assertNotInBody(self, value, msg=None):
         """Fail if value in self.body."""
-        if isinstance(value, str):
+        if isinstance(value, unicodestr):
             value = value.encode(self.encoding)
         if value in self.body:
             if msg is None:
 
     def assertMatchesBody(self, pattern, msg=None, flags=0):
         """Fail if value (a regex pattern) is not in self.body."""
-        if isinstance(pattern, str):
+        if isinstance(pattern, unicodestr):
             pattern = pattern.encode(self.encoding)
         if re.search(pattern, self.body, flags) is None:
             if msg is None:
 
 def shb(response):
     """Return status, headers, body the way we like from a response."""
-    h = response.getheaders()
+    if py3k:
+        h = response.getheaders()
+    else:
+        h = []
+        key, value = None, None
+        for line in response.msg.headers:
+            if line:
+                if line[0] in " \t":
+                    value += line.strip()
+                else:
+                    if key and value:
+                        h.append((key, value))
+                    key, value = line.split(":", 1)
+                    key = key.strip()
+                    value = value.strip()
+        if key and value:
+            h.append((key, value))
+
     return "%s %s" % (response.status, response.reason), h, response.read()
 
 
 
             conn._http_vsn_str = protocol
             conn._http_vsn = int("".join([x for x in protocol if x.isdigit()]))
-            
-            # Replace the stdlib method, which only accepts ASCII url's
-            def putrequest(self, method, url):
-                if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
-                    self._HTTPConnection__response = None
+
+            # skip_accept_encoding argument added in python version 2.4
+            if sys.version_info < (2, 4):
+                def putheader(self, header, value):
+                    if header == 'Accept-Encoding' and value == 'identity':
+                        return
+                    self.__class__.putheader(self, header, value)
+                import new
+                conn.putheader = new.instancemethod(putheader, conn, conn.__class__)
+                conn.putrequest(method.upper(), url, skip_host=True)
+            elif not py3k:
+                conn.putrequest(method.upper(), url, skip_host=True,
+                                skip_accept_encoding=True)
+            else:
+                import http.client
+                # Replace the stdlib method, which only accepts ASCII url's
+                def putrequest(self, method, url):
+                    if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
+                        self._HTTPConnection__response = None
+                    
+                    if self._HTTPConnection__state == http.client._CS_IDLE:
+                        self._HTTPConnection__state = http.client._CS_REQ_STARTED
+                    else:
+                        raise http.client.CannotSendRequest()
+                    
+                    self._method = method
+                    if not url:
+                        url = b'/'
+                    request = b' '.join((method.encode("ASCII"), url,
+                                         self._http_vsn_str.encode("ASCII")))
+                    self._output(request)
+                import types
+                conn.putrequest = types.MethodType(putrequest, conn)
                 
-                if self._HTTPConnection__state == http.client._CS_IDLE:
-                    self._HTTPConnection__state = http.client._CS_REQ_STARTED
-                else:
-                    raise http.client.CannotSendRequest()
-                
-                self._method = method
-                if not url:
-                    url = b'/'
-                request = b' '.join((method.encode("ASCII"), url,
-                                     self._http_vsn_str.encode("ASCII")))
-                self._output(request)
-            import types
-            conn.putrequest = types.MethodType(putrequest, conn)
-            
-            conn.putrequest(method.upper(), url)
-            
+                conn.putrequest(method.upper(), url)
+
             for key, value in headers:
-                conn.putheader(key, bytes(value, "Latin-1"))
+                conn.putheader(key, ntob(value, "Latin-1"))
             conn.endheaders()
 
             if body is not None:
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.