[py3k] import HTTP client constants and exceptions using six.moves
authorRémi Cardona <remi.cardona@logilab.fr>
Mon, 14 Sep 2015 12:40:57 +0200
changeset 10604 d4bf85db41f2
parent 10603 65ad6980976e
child 10605 61521bee2b68
[py3k] import HTTP client constants and exceptions using six.moves
devtools/httptest.py
devtools/test/unittest_httptest.py
devtools/test/unittest_webtest.py
web/_exceptions.py
web/application.py
web/request.py
web/test/unittest_application.py
--- a/devtools/httptest.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/devtools/httptest.py	Mon Sep 14 12:40:57 2015 +0200
@@ -25,8 +25,8 @@
 import random
 import threading
 import socket
-import httplib
 
+from six.moves import http_client
 from six.moves.urllib.parse import urlparse
 
 from twisted.internet import reactor, error
@@ -113,8 +113,8 @@
         #pre init utils connection
         parseurl = urlparse(self.config['base-url'])
         assert parseurl.port == self.config['port'], (self.config['base-url'], self.config['port'])
-        self._web_test_cnx = httplib.HTTPConnection(parseurl.hostname,
-                                                    parseurl.port)
+        self._web_test_cnx = http_client.HTTPConnection(parseurl.hostname,
+                                                        parseurl.port)
         self._ident_cookie = None
 
     def stop_server(self, timeout=15):
@@ -142,7 +142,7 @@
             passwd = user
         response = self.web_get("login?__login=%s&__password=%s" %
                                 (user, passwd))
-        assert response.status == httplib.SEE_OTHER, response.status
+        assert response.status == http_client.SEE_OTHER, response.status
         self._ident_cookie = response.getheader('Set-Cookie')
         assert self._ident_cookie
         return True
@@ -154,7 +154,7 @@
         self._ident_cookie = None
 
     def web_request(self, path='', method='GET', body=None, headers=None):
-        """Return an httplib.HTTPResponse object for the specified path
+        """Return an http_client.HTTPResponse object for the specified path
 
         Use available credential if available.
         """
--- a/devtools/test/unittest_httptest.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/devtools/test/unittest_httptest.py	Mon Sep 14 12:40:57 2015 +0200
@@ -17,7 +17,7 @@
 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
 """unittest for cubicweb.devtools.httptest module"""
 
-import httplib
+from six.moves import http_client
 
 from logilab.common.testlib import Tags
 from cubicweb.devtools.httptest import CubicWebServerTC
@@ -28,12 +28,12 @@
     def test_response(self):
         try:
             response = self.web_get()
-        except httplib.NotConnected as ex:
+        except http_client.NotConnected as ex:
             self.fail("Can't connection to test server: %s" % ex)
 
     def test_response_anon(self):
         response = self.web_get()
-        self.assertEqual(response.status, httplib.OK)
+        self.assertEqual(response.status, http_client.OK)
 
     def test_base_url(self):
         if self.config['base-url'] not in self.web_get().read():
@@ -47,20 +47,20 @@
 
     def test_response_denied(self):
         response = self.web_get()
-        self.assertEqual(response.status, httplib.FORBIDDEN)
+        self.assertEqual(response.status, http_client.FORBIDDEN)
 
     def test_login(self):
         response = self.web_get()
-        if response.status != httplib.FORBIDDEN:
+        if response.status != http_client.FORBIDDEN:
             self.skipTest('Already authenticated, "test_response_denied" must have failed')
         # login
         self.web_login(self.admlogin, self.admpassword)
         response = self.web_get()
-        self.assertEqual(response.status, httplib.OK, response.body)
+        self.assertEqual(response.status, http_client.OK, response.body)
         # logout
         self.web_logout()
         response = self.web_get()
-        self.assertEqual(response.status, httplib.FORBIDDEN, response.body)
+        self.assertEqual(response.status, http_client.FORBIDDEN, response.body)
 
 
 
--- a/devtools/test/unittest_webtest.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/devtools/test/unittest_webtest.py	Mon Sep 14 12:40:57 2015 +0200
@@ -1,4 +1,4 @@
-import httplib
+from six.moves import http_client
 
 from logilab.common.testlib import Tags
 from cubicweb.devtools.webtest import CubicWebTestTC
@@ -21,19 +21,19 @@
 
     def test_reponse_denied(self):
         res = self.webapp.get('/', expect_errors=True)
-        self.assertEqual(httplib.FORBIDDEN, res.status_int)
+        self.assertEqual(http_client.FORBIDDEN, res.status_int)
 
     def test_login(self):
         res = self.webapp.get('/', expect_errors=True)
-        self.assertEqual(httplib.FORBIDDEN, res.status_int)
+        self.assertEqual(http_client.FORBIDDEN, res.status_int)
 
         self.login(self.admlogin, self.admpassword)
         res = self.webapp.get('/')
-        self.assertEqual(httplib.OK, res.status_int)
+        self.assertEqual(http_client.OK, res.status_int)
 
         self.logout()
         res = self.webapp.get('/', expect_errors=True)
-        self.assertEqual(httplib.FORBIDDEN, res.status_int)
+        self.assertEqual(http_client.FORBIDDEN, res.status_int)
 
 
 if __name__ == '__main__':
--- a/web/_exceptions.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/web/_exceptions.py	Mon Sep 14 12:40:57 2015 +0200
@@ -20,7 +20,7 @@
 
 __docformat__ = "restructuredtext en"
 
-import httplib
+from six.moves import http_client
 
 from cubicweb._exceptions import *
 from cubicweb.utils import json_dumps
@@ -41,7 +41,7 @@
     """base class for publishing related exception"""
 
     def __init__(self, *args, **kwargs):
-        self.status = kwargs.pop('status', httplib.OK)
+        self.status = kwargs.pop('status', http_client.OK)
         super(PublishException, self).__init__(*args, **kwargs)
 
 class LogOut(PublishException):
@@ -52,7 +52,7 @@
 
 class Redirect(PublishException):
     """raised to redirect the http request"""
-    def __init__(self, location, status=httplib.SEE_OTHER):
+    def __init__(self, location, status=http_client.SEE_OTHER):
         super(Redirect, self).__init__(status=status)
         self.location = location
 
@@ -71,7 +71,7 @@
     """raised when a request can't be served because of a bad input"""
 
     def __init__(self, *args, **kwargs):
-        kwargs.setdefault('status', httplib.BAD_REQUEST)
+        kwargs.setdefault('status', http_client.BAD_REQUEST)
         super(RequestError, self).__init__(*args, **kwargs)
 
 
@@ -79,14 +79,14 @@
     """raised when an edit request doesn't specify any eid to edit"""
 
     def __init__(self, *args, **kwargs):
-        kwargs.setdefault('status', httplib.BAD_REQUEST)
+        kwargs.setdefault('status', http_client.BAD_REQUEST)
         super(NothingToEdit, self).__init__(*args, **kwargs)
 
 class ProcessFormError(RequestError):
     """raised when posted data can't be processed by the corresponding field
     """
     def __init__(self, *args, **kwargs):
-        kwargs.setdefault('status', httplib.BAD_REQUEST)
+        kwargs.setdefault('status', http_client.BAD_REQUEST)
         super(ProcessFormError, self).__init__(*args, **kwargs)
 
 class NotFound(RequestError):
@@ -94,13 +94,13 @@
        a 404 error should be returned"""
 
     def __init__(self, *args, **kwargs):
-        kwargs.setdefault('status', httplib.NOT_FOUND)
+        kwargs.setdefault('status', http_client.NOT_FOUND)
         super(NotFound, self).__init__(*args, **kwargs)
 
 class RemoteCallFailed(RequestError):
     """raised when a json remote call fails
     """
-    def __init__(self, reason='', status=httplib.INTERNAL_SERVER_ERROR):
+    def __init__(self, reason='', status=http_client.INTERNAL_SERVER_ERROR):
         super(RemoteCallFailed, self).__init__(reason, status=status)
         self.reason = reason
 
--- a/web/application.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/web/application.py	Mon Sep 14 12:40:57 2015 +0200
@@ -25,7 +25,7 @@
 from warnings import warn
 import json
 
-import httplib
+from six.moves import http_client
 
 from logilab.common.deprecation import deprecated
 
@@ -290,7 +290,7 @@
                 if self.vreg.config['auth-mode'] == 'cookie' and ex.url:
                     req.headers_out.setHeader('location', str(ex.url))
                 if ex.status is not None:
-                    req.status_out = httplib.SEE_OTHER
+                    req.status_out = http_client.SEE_OTHER
                 # When the authentification is handled by http we must
                 # explicitly ask for authentification to flush current http
                 # authentification information
@@ -310,18 +310,18 @@
             # the request does not use https, redirect to login form
             https_url = self.vreg.config['https-url']
             if https_url and req.base_url() != https_url:
-                req.status_out = httplib.SEE_OTHER
+                req.status_out = http_client.SEE_OTHER
                 req.headers_out.setHeader('location', https_url + 'login')
             else:
                 # We assume here that in http auth mode the user *May* provide
                 # Authentification Credential if asked kindly.
                 if self.vreg.config['auth-mode'] == 'http':
-                    req.status_out = httplib.UNAUTHORIZED
+                    req.status_out = http_client.UNAUTHORIZED
                 # In the other case (coky auth) we assume that there is no way
                 # for the user to provide them...
                 # XXX But WHY ?
                 else:
-                    req.status_out = httplib.FORBIDDEN
+                    req.status_out = http_client.FORBIDDEN
                 # If previous error handling already generated a custom content
                 # do not overwrite it. This is used by LogOut Except
                 # XXX ensure we don't actually serve content
@@ -394,12 +394,12 @@
         except Unauthorized as ex:
             req.data['errmsg'] = req._('You\'re not authorized to access this page. '
                                        'If you think you should, please contact the site administrator.')
-            req.status_out = httplib.FORBIDDEN
+            req.status_out = http_client.FORBIDDEN
             result = self.error_handler(req, ex, tb=False)
         except Forbidden as ex:
             req.data['errmsg'] = req._('This action is forbidden. '
                                        'If you think it should be allowed, please contact the site administrator.')
-            req.status_out = httplib.FORBIDDEN
+            req.status_out = http_client.FORBIDDEN
             result = self.error_handler(req, ex, tb=False)
         except (BadRQLQuery, RequestError) as ex:
             result = self.error_handler(req, ex, tb=False)
@@ -413,7 +413,7 @@
             raise
         ### Last defense line
         except BaseException as ex:
-            req.status_out = httplib.INTERNAL_SERVER_ERROR
+            req.status_out = http_client.INTERNAL_SERVER_ERROR
             result = self.error_handler(req, ex, tb=True)
         finally:
             if req.cnx and not commited:
@@ -453,9 +453,9 @@
             # messages.
             location = req.form['__errorurl'].rsplit('#', 1)[0]
             req.headers_out.setHeader('location', str(location))
-            req.status_out = httplib.SEE_OTHER
+            req.status_out = http_client.SEE_OTHER
             return ''
-        req.status_out = httplib.CONFLICT
+        req.status_out = http_client.CONFLICT
         return self.error_handler(req, ex, tb=False)
 
     def error_handler(self, req, ex, tb=False):
@@ -491,7 +491,7 @@
 
     def ajax_error_handler(self, req, ex):
         req.set_header('content-type', 'application/json')
-        status = httplib.INTERNAL_SERVER_ERROR
+        status = http_client.INTERNAL_SERVER_ERROR
         if isinstance(ex, PublishException) and ex.status is not None:
             status = ex.status
         if req.status_out < 400:
--- a/web/request.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/web/request.py	Mon Sep 14 12:40:57 2015 +0200
@@ -27,9 +27,9 @@
 from Cookie import SimpleCookie
 from calendar import timegm
 from datetime import date, datetime
-import httplib
 from warnings import warn
 
+from six.moves import http_client
 from six.moves.urllib.parse import urlsplit, quote as urlquote
 
 from rql.utils import rqlvar_maker
@@ -738,9 +738,9 @@
             # overwrite headers_out to forge a brand new not-modified response
             self.headers_out = self._forge_cached_headers()
             if self.http_method() in ('HEAD', 'GET'):
-                self.status_out = httplib.NOT_MODIFIED
+                self.status_out = http_client.NOT_MODIFIED
             else:
-                self.status_out = httplib.PRECONDITION_FAILED
+                self.status_out = http_client.PRECONDITION_FAILED
             # XXX replace by True once validate_cache bw compat method is dropped
             return self.status_out
         # XXX replace by False once validate_cache bw compat method is dropped
--- a/web/test/unittest_application.py	Tue Sep 22 09:39:30 2015 +0200
+++ b/web/test/unittest_application.py	Mon Sep 14 12:40:57 2015 +0200
@@ -18,7 +18,8 @@
 """unit tests for cubicweb.web.application"""
 
 import base64, Cookie
-import httplib
+
+from six.moves import http_client
 
 from logilab.common.testlib import TestCase, unittest_main
 from logilab.common.decorators import clear_cache, classproperty
@@ -267,7 +268,7 @@
                 with self.admin_access.web_request(vid='test.ajax.error') as req:
                     req.ajax_request = True
                     page = app.handle_request(req, '')
-        self.assertEqual(httplib.INTERNAL_SERVER_ERROR,
+        self.assertEqual(http_client.INTERNAL_SERVER_ERROR,
                          req.status_out)
 
     def _test_cleaned(self, kwargs, injected, cleaned):