diff options
author | Cyril Roelandt <cyril.roelandt@enovance.com> | 2014-03-18 12:49:12 +0100 |
---|---|---|
committer | Cyril Roelandt <cyril.roelandt@enovance.com> | 2014-03-18 12:49:12 +0100 |
commit | 674ae7718bc06a8b8c8b658075bf82c8198fb632 (patch) | |
tree | 0075bace24ead7f03ae7cb18935e4c707f71a860 | |
parent | 3cdb7e4227cbaad690b1c1557c03fa6da0decc36 (diff) | |
download | paste-674ae7718bc06a8b8c8b658075bf82c8198fb632.tar.gz |
Python 3: use new names of standard library modules
Use "try/except ImportError" to try Python 2 and Python 3 names.
35 files changed, 162 insertions, 104 deletions
diff --git a/paste/auth/auth_tkt.py b/paste/auth/auth_tkt.py index 280355b..e94f539 100644 --- a/paste/auth/auth_tkt.py +++ b/paste/auth/auth_tkt.py @@ -43,7 +43,11 @@ try: except ImportError: # mimic hashlib (will work for md5, fail for secure hashes) import md5 as hashlib -import Cookie +try: + from http.cookies import SimpleCookie +except ImportError: + # Python 2 + from Cookie import SimpleCookie from paste import request from urllib import quote as url_quote from urllib import unquote as url_unquote @@ -123,7 +127,7 @@ class AuthTicket(object): return v def cookie(self): - c = Cookie.SimpleCookie() + c = SimpleCookie() c[self.cookie_name] = self.cookie_value().encode('base64').strip().replace('\n', '') c[self.cookie_name]['path'] = '/' if self.secure: diff --git a/paste/auth/cas.py b/paste/auth/cas.py index c3521a0..44e4e98 100644 --- a/paste/auth/cas.py +++ b/paste/auth/cas.py @@ -18,7 +18,7 @@ passed to the system so that it can be used as middleware at any stage of processing. It has the secondary goal of allowing for other authentication methods to be used concurrently. """ -import urllib +from six.moves.urllib.parse import urlencode from paste.request import construct_url from paste.httpexceptions import HTTPSeeOther, HTTPForbidden @@ -69,10 +69,10 @@ def AuthCASHandler(application, authority): ticket = qs.pop().split("=", 1)[1] environ['QUERY_STRING'] = "&".join(qs) service = construct_url(environ) - args = urllib.urlencode( + args = urlencode( {'service': service,'ticket': ticket}) requrl = authority + "validate?" + args - result = urllib.urlopen(requrl).read().split("\n") + result = urlopen(requrl).read().split("\n") if 'yes' == result[0]: environ['REMOTE_USER'] = result[1] environ['AUTH_TYPE'] = 'cas' @@ -80,7 +80,7 @@ def AuthCASHandler(application, authority): exce = CASLoginFailure() else: service = construct_url(environ) - args = urllib.urlencode({'service': service}) + args = urlencode({'service': service}) location = authority + "login?" + args exce = CASAuthenticate(location) return exce.wsgi_application(environ, start_response) diff --git a/paste/auth/digest.py b/paste/auth/digest.py index 9b427aa..798f447 100644 --- a/paste/auth/digest.py +++ b/paste/auth/digest.py @@ -36,7 +36,7 @@ try: except ImportError: from md5 import md5 import time, random -from urllib import quote as url_quote +from six.moves.urllib.parse import quote as url_quote def _split_auth_string(auth_string): """ split a digest auth string into individual key=value strings """ diff --git a/paste/cgiapp.py b/paste/cgiapp.py index 8801750..2718506 100644 --- a/paste/cgiapp.py +++ b/paste/cgiapp.py @@ -7,7 +7,7 @@ Application that runs a CGI script. import os import sys import subprocess -import urllib +from six.moves.urllib.parse import quote try: import select except ImportError: @@ -69,8 +69,8 @@ class CGIApplication(object): def __call__(self, environ, start_response): if 'REQUEST_URI' not in environ: environ['REQUEST_URI'] = ( - urllib.quote(environ.get('SCRIPT_NAME', '')) - + urllib.quote(environ.get('PATH_INFO', ''))) + quote(environ.get('SCRIPT_NAME', '')) + + quote(environ.get('PATH_INFO', ''))) if self.include_os_environ: cgi_environ = os.environ.copy() else: diff --git a/paste/cgitb_catcher.py b/paste/cgitb_catcher.py index 1c815b7..2679d81 100644 --- a/paste/cgitb_catcher.py +++ b/paste/cgitb_catcher.py @@ -10,7 +10,8 @@ for more. """ import cgitb -from cStringIO import StringIO +import six +from six.moves import cStringIO as StringIO import sys from paste.util import converters diff --git a/paste/debug/fsdiff.py b/paste/debug/fsdiff.py index 2849ea8..f680bf6 100644 --- a/paste/debug/fsdiff.py +++ b/paste/debug/fsdiff.py @@ -12,7 +12,17 @@ the file was. import os from fnmatch import fnmatch from datetime import datetime -from paste.util.UserDict24 import IterableUserDict + +try: + # Python 3 + import collections.UserDict as IterableUserDict +except ImportError: + try: + # Python 2.5-2.7 + from UserDict import IterableUserDict + except ImportError: + # Python <= 2.4 + from paste.util.UserDict24 import IterableUserDict import operator import re diff --git a/paste/debug/testserver.py b/paste/debug/testserver.py index 26c477a..0adeefc 100755 --- a/paste/debug/testserver.py +++ b/paste/debug/testserver.py @@ -67,7 +67,7 @@ def serve(application, host=None, port=None, handler=None): return server if __name__ == '__main__': - import urllib + from six.moves.urllib.request import urlopen from paste.wsgilib import dump_environ server = serve(dump_environ) baseuri = ("http://%s:%s" % server.server_address) @@ -80,7 +80,7 @@ if __name__ == '__main__': import socket socket.setdefaulttimeout(5) # build a uri, fetch and return - return urllib.urlopen(baseuri + path).read() + return urlopen(baseuri + path).read() assert "PATH_INFO: /foo" in fetch("/foo") assert "PATH_INFO: /womble" in fetch("/womble") @@ -90,4 +90,4 @@ if __name__ == '__main__': # and then schedule a stop() server.stop() # and then... fetch it... - urllib.urlopen(baseuri) + urlopen(baseuri) diff --git a/paste/errordocument.py b/paste/errordocument.py index e57c162..8b7d81c 100644 --- a/paste/errordocument.py +++ b/paste/errordocument.py @@ -11,7 +11,7 @@ URL where the content can be displayed to the user as an error document. import warnings import sys -from urlparse import urlparse +from six.moves.urllib import parse as urlparse from paste.recursive import ForwardRequestException, RecursiveMiddleware, RecursionLoop from paste.util import converters from paste.response import replace_header @@ -342,7 +342,7 @@ class _StatusBasedRedirect(object): new_environ = {} for k, v in environ.items(): if k != 'QUERY_STRING': - new_environ['QUERY_STRING'] = urlparse(url_)[4] + new_environ['QUERY_STRING'] = urlparse.urlparse(url_)[4] else: new_environ[k] = v class InvalidForward(Exception): diff --git a/paste/evalexception/evalcontext.py b/paste/evalexception/evalcontext.py index dca2a97..dbd49fb 100644 --- a/paste/evalexception/evalcontext.py +++ b/paste/evalexception/evalcontext.py @@ -1,6 +1,6 @@ # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php -from cStringIO import StringIO +from six.moves import cStringIO as StringIO import traceback import threading import pdb diff --git a/paste/evalexception/middleware.py b/paste/evalexception/middleware.py index 4349b88..a31d7e1 100644 --- a/paste/evalexception/middleware.py +++ b/paste/evalexception/middleware.py @@ -28,7 +28,7 @@ import sys import os import cgi import traceback -from cStringIO import StringIO +from six.moves import cStringIO as StringIO import pprint import itertools import time diff --git a/paste/exceptions/collector.py b/paste/exceptions/collector.py index 65f9ec0..4f6d4c6 100644 --- a/paste/exceptions/collector.py +++ b/paste/exceptions/collector.py @@ -23,10 +23,7 @@ supplements import sys import traceback import time -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO +from six.moves import cStringIO as StringIO import linecache from paste.exceptions import serial_number_generator import warnings diff --git a/paste/exceptions/errormiddleware.py b/paste/exceptions/errormiddleware.py index 784414f..5654598 100644 --- a/paste/exceptions/errormiddleware.py +++ b/paste/exceptions/errormiddleware.py @@ -7,10 +7,7 @@ Error handler middleware import sys import traceback import cgi -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO +from six.moves import cStringIO as StringIO from paste.exceptions import formatter, collector, reporter from paste import wsgilib from paste import request diff --git a/paste/fixture.py b/paste/fixture.py index 242a1de..0cf3a27 100644 --- a/paste/fixture.py +++ b/paste/fixture.py @@ -11,8 +11,6 @@ effects of command-line scripts. import sys import random -import urllib -import urlparse import mimetypes import time import cgi @@ -20,16 +18,19 @@ import os import shutil import smtplib import shlex -from Cookie import BaseCookie -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO import re +import subprocess +from six.moves import cStringIO as StringIO +from six.moves.urllib.parse import urlencode +from six.moves.urllib import parse as urlparse try: - import subprocess + # Python 3 + from http.cookies import BaseCookie + from urllib.parse import splittype, splithost except ImportError: - from paste.util import subprocess24 as subprocess + # Python 2 + from Cookie import BaseCookie + from urllib import splittype, splithost from paste import wsgilib from paste import lint @@ -190,7 +191,7 @@ class TestApp(object): __tracebackhide__ = True if params: if not isinstance(params, (str, unicode)): - params = urllib.urlencode(params, doseq=True) + params = urlencode(params, doseq=True) if '?' in url: url += '&' else: @@ -219,10 +220,10 @@ class TestApp(object): environ = self._make_environ() # @@: Should this be all non-strings? if isinstance(params, (list, tuple, dict)): - params = urllib.urlencode(params) + params = urlencode(params) if hasattr(params, 'items'): # Some other multi-dict like format - params = urllib.urlencode(params.items()) + params = urlencode(params.items()) if upload_files: params = cgi.parse_qsl(params, keep_blank_values=True) content_type, params = self.encode_multipart( @@ -597,8 +598,8 @@ class TestResponse(object): "You can only follow redirect responses (not %s)" % self.full_status) location = self.header('location') - type, rest = urllib.splittype(location) - host, path = urllib.splithost(rest) + type, rest = splittype(location) + host, path = splithost(rest) # @@: We should test that it's not a remote redirect return self.test_app.get(location, **kw) diff --git a/paste/gzipper.py b/paste/gzipper.py index 1431490..21b4164 100644 --- a/paste/gzipper.py +++ b/paste/gzipper.py @@ -14,10 +14,7 @@ import gzip from paste.response import header_value, remove_header from paste.httpheaders import CONTENT_LENGTH -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO +from six.moves import cStringIO as StringIO class GzipOutput(object): pass diff --git a/paste/httpheaders.py b/paste/httpheaders.py index 728fa39..cd21069 100644 --- a/paste/httpheaders.py +++ b/paste/httpheaders.py @@ -135,11 +135,18 @@ dashes to give CamelCase style names. """ import mimetypes -import urllib2 import re -from rfc822 import formatdate, parsedate_tz, mktime_tz from time import time as now from httpexceptions import HTTPBadRequest +try: + # Python 3 + from email.utils import formatdate, parsedate_tz, mktime_tz + from urllib.request import AbstractDigestAuthHandler, parse_keqv_list, parse_http_list +except ImportError: + # Python 2 + from rfc822 import formatdate, parsedate_tz, mktime_tz + from urllib2 import AbstractDigestAuthHandler, parse_keqv_list, parse_http_list + __all__ = ['get_header', 'list_headers', 'normalize_headers', 'HTTPHeader', 'EnvironVariable' ] @@ -1007,10 +1014,10 @@ class _Authorization(_SingleValueHeader): path = path or "/" (_, realm) = challenge.split('realm="') (realm, _) = realm.split('"', 1) - auth = urllib2.AbstractDigestAuthHandler() + auth = AbstractDigestAuthHandler() auth.add_password(realm, path, username, password) (token, challenge) = challenge.split(' ', 1) - chal = urllib2.parse_keqv_list(urllib2.parse_http_list(challenge)) + chal = parse_keqv_list(parse_http_list(challenge)) class FakeRequest(object): def get_full_url(self): return path diff --git a/paste/httpserver.py b/paste/httpserver.py index b7d6640..126c28a 100755 --- a/paste/httpserver.py +++ b/paste/httpserver.py @@ -19,7 +19,8 @@ if pyOpenSSL is installed, it also provides SSL capabilities. import atexit import traceback -import socket, sys, threading, urlparse, Queue, urllib +from six.moves.urllib.parse import unquote +import socket, sys, threading, urlparse, Queue import posixpath import time import thread @@ -179,7 +180,7 @@ class WSGIHandlerMixin: dummy_url = 'http://dummy%s' % (self.path,) (scheme, netloc, path, query, fragment) = urlparse.urlsplit(dummy_url) - path = urllib.unquote(path) + path = unquote(path) endslash = path.endswith('/') path = posixpath.normpath(path) if endslash and path != '/': diff --git a/paste/proxy.py b/paste/proxy.py index 155128f..a33efbc 100644 --- a/paste/proxy.py +++ b/paste/proxy.py @@ -29,9 +29,9 @@ TODO: """ -import httplib -import urlparse -import urllib +from six.moves import http_client as httplib +from six.moves.urllib import parse as urlparse +from six.moves.urllib.parse import quote from paste import httpexceptions from paste.util.converters import aslist @@ -101,7 +101,7 @@ class Proxy(object): else: body = '' - path_info = urllib.quote(environ['PATH_INFO']) + path_info = quote(environ['PATH_INFO']) if self.path: request_path = path_info if request_path and request_path[0] == '/': @@ -227,7 +227,7 @@ class TransparentProxy(object): path = (environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')) - path = urllib.quote(path) + path = quote(path) if 'QUERY_STRING' in environ: path += '?' + environ['QUERY_STRING'] conn.request(environ['REQUEST_METHOD'], diff --git a/paste/recursive.py b/paste/recursive.py index 8ea7038..944b002 100644 --- a/paste/recursive.py +++ b/paste/recursive.py @@ -23,8 +23,8 @@ Raise ``ForwardRequestException(new_path_info)`` to do a forward (aborting the current request). """ -from cStringIO import StringIO import warnings +from six.moves import cStringIO as StringIO __all__ = ['RecursiveMiddleware'] __pudge_all__ = ['RecursiveMiddleware', 'ForwardRequestException'] diff --git a/paste/request.py b/paste/request.py index 9af494d..5649b7b 100644 --- a/paste/request.py +++ b/paste/request.py @@ -18,14 +18,21 @@ environment to solve common requirements. """ import cgi -from Cookie import SimpleCookie, CookieError -from StringIO import StringIO -import urlparse -import urllib +from six.moves import StringIO +from six.moves.urllib import parse as urlparse +from six.moves.urllib.parse import quote +try: + # Python 3 + from http.cookies import SimpleCookie, CookieError +except ImportError: + # Python 2 + from Cookie import SimpleCookie, CookieError + try: from UserDict import DictMixin except ImportError: - from paste.util.UserDict24 import DictMixin + from collections import MutableMapping as DictMixin + from paste.util.multidict import MultiDict __all__ = ['get_cookies', 'get_cookie_dict', 'parse_querystring', @@ -231,14 +238,14 @@ def construct_url(environ, with_query_string=True, with_path_info=True, url += ':' + environ['SERVER_PORT'] if script_name is None: - url += urllib.quote(environ.get('SCRIPT_NAME','')) + url += quote(environ.get('SCRIPT_NAME','')) else: - url += urllib.quote(script_name) + url += quote(script_name) if with_path_info: if path_info is None: - url += urllib.quote(environ.get('PATH_INFO','')) + url += quote(environ.get('PATH_INFO','')) else: - url += urllib.quote(path_info) + url += quote(path_info) if with_query_string: if querystring is None: if environ.get('QUERY_STRING'): diff --git a/paste/session.py b/paste/session.py index 16a7739..7558533 100644 --- a/paste/session.py +++ b/paste/session.py @@ -23,7 +23,12 @@ session for each request, with no caching. Also, sessions aren't expired. """ -from Cookie import SimpleCookie +try: + # Python 3 + from http.cookies import SimpleCookie +except ImportError: + # Python 2 + from Cookie import SimpleCookie import time import random import os diff --git a/paste/translogger.py b/paste/translogger.py index 47de2d3..355af9b 100644 --- a/paste/translogger.py +++ b/paste/translogger.py @@ -6,7 +6,7 @@ Middleware for logging requests, using Apache combined log format import logging import time -import urllib +from six.moves.urllib.parse import quote class TransLogger(object): """ @@ -50,7 +50,7 @@ class TransLogger(object): def __call__(self, environ, start_response): start = time.localtime() - req_uri = urllib.quote(environ.get('SCRIPT_NAME', '') + req_uri = quote(environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')) if environ.get('QUERY_STRING'): req_uri += '?'+environ['QUERY_STRING'] diff --git a/paste/url.py b/paste/url.py index afc4fca..87a6e8a 100644 --- a/paste/url.py +++ b/paste/url.py @@ -4,7 +4,7 @@ """ This module implements a class for handling URLs. """ -import urllib +from six.moves.urllib.parse import quote, unquote, urlencode import cgi from paste import request # Imported lazily from FormEncode: @@ -20,9 +20,7 @@ def html_quote(v): def url_quote(v): if v is None: return '' - return urllib.quote(str(v)) - -url_unquote = urllib.unquote + return quote(str(v)) def js_repr(v): if v is None: @@ -102,7 +100,7 @@ class URLResource(object): def __getitem__(self, item): if '=' in item: name, value = item.split('=', 1) - return self._add_vars({url_unquote(name): url_unquote(value)}) + return self._add_vars({unquote(name): unquote(value)}) return self._add_positional((item,)) def attr(self, **kw): @@ -202,7 +200,7 @@ class URLResource(object): elif val is None: continue vars.append((name, val)) - s += urllib.urlencode(vars, True) + s += urlencode(vars, True) return s href = property(href__get) diff --git a/paste/urlmap.py b/paste/urlmap.py index a636531..8b9a7c3 100644 --- a/paste/urlmap.py +++ b/paste/urlmap.py @@ -4,10 +4,16 @@ Map URL prefixes to WSGI applications. See ``URLMap`` """ -from UserDict import DictMixin import re import os import cgi +try: + # Python 3 + from collections import MutableMapping as DictMixin +except ImportError: + # Python 2 + from UserDict import DictMixin + from paste import httpexceptions __all__ = ['URLMap', 'PathProxyURLMap'] diff --git a/paste/util/PySourceColor.py b/paste/util/PySourceColor.py index 65406ec..d9f451f 100644 --- a/paste/util/PySourceColor.py +++ b/paste/util/PySourceColor.py @@ -195,10 +195,7 @@ import keyword import token
import tokenize
import traceback
-try :
- import cStringIO as StringIO
-except:
- import StringIO
+from six.moves import cStringIO as StringIO
# Do not edit
NAME = token.NAME
NUMBER = token.NUMBER
diff --git a/paste/util/multidict.py b/paste/util/multidict.py index d3eb1e9..867f309 100644 --- a/paste/util/multidict.py +++ b/paste/util/multidict.py @@ -3,7 +3,13 @@ import cgi import copy import sys -from UserDict import DictMixin + +try: + # Python 3 + from collections import MutableMapping as DictMixin +except ImportError: + # Python 2 + from UserDict import DictMixin class MultiDict(DictMixin): diff --git a/paste/util/quoting.py b/paste/util/quoting.py index 6184752..2052a90 100644 --- a/paste/util/quoting.py +++ b/paste/util/quoting.py @@ -2,9 +2,10 @@ # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import cgi -import htmlentitydefs -import urllib import re +from six.moves import html_entities +from six.moves.urllib.parse import quote, unquote + __all__ = ['html_quote', 'html_unquote', 'url_quote', 'url_unquote', 'strip_html'] @@ -36,7 +37,7 @@ def html_quote(v, encoding=None): return cgi.escape(unicode(v).encode(encoding), 1) _unquote_re = re.compile(r'&([a-zA-Z]+);') -def _entity_subber(match, name2c=htmlentitydefs.name2codepoint): +def _entity_subber(match, name2c=html_entities.name2codepoint): code = name2c.get(match.group(1)) if code: return unichr(code) @@ -90,8 +91,8 @@ def comment_quote(s): comment = _comment_quote_re.sub('->', comment) return comment -url_quote = urllib.quote -url_unquote = urllib.unquote +url_quote = quote +url_unquote = unquote if __name__ == '__main__': import doctest diff --git a/paste/util/template.py b/paste/util/template.py index 1e42b5a..fd9e802 100644 --- a/paste/util/template.py +++ b/paste/util/template.py @@ -33,7 +33,7 @@ If there are syntax errors ``TemplateError`` will be raised. import re import sys import cgi -import urllib +from six.moves.urllib.parse import quote from paste.util.looper import looper __all__ = ['TemplateError', 'Template', 'sub', 'HTMLTemplate', @@ -335,7 +335,7 @@ def url(v): v = str(v) if isinstance(v, unicode): v = v.encode('utf8') - return urllib.quote(v) + return quote(v) def attr(**kw): kw = kw.items() diff --git a/paste/wsgilib.py b/paste/wsgilib.py index 67ced97..a44bc9d 100644 --- a/paste/wsgilib.py +++ b/paste/wsgilib.py @@ -13,10 +13,9 @@ from paste.response import HeaderDict, has_header, header_value, remove_header from paste.response import error_body_response, error_response, error_response_app from traceback import print_exception -import urllib -from cStringIO import StringIO import sys -from urlparse import urlsplit +from six.moves import cStringIO as StringIO +from six.moves.urllib.parse import unquote, urlsplit import warnings __all__ = ['add_close', 'add_start_close', 'capture_output', 'catch_errors', @@ -303,7 +302,7 @@ def raw_interactive(application, path='', raise_on_wsgi_error=False, } if path: (_, _, path_info, query, fragment) = urlsplit(str(path)) - path_info = urllib.unquote(path_info) + path_info = unquote(path_info) # urlsplit returns unicode so coerce it back to str path_info, query = str(path_info), str(query) basic_environ['PATH_INFO'] = path_info diff --git a/paste/wsgiwrappers.py b/paste/wsgiwrappers.py index 7821d26..7074923 100644 --- a/paste/wsgiwrappers.py +++ b/paste/wsgiwrappers.py @@ -8,7 +8,13 @@ to deal with an incoming request and sending a response. import re import warnings from pprint import pformat -from Cookie import SimpleCookie +try: + # Python 3 + from http.cookies import SimpleCookie +except ImportError: + # Python 2 + from Cookie import SimpleCookie + from paste.request import EnvironHeaders, get_cookie_dict, \ parse_dict_querystring, parse_formvars from paste.util.multidict import MultiDict, UnicodeMultiDict diff --git a/tests/test_auth/test_auth_cookie.py b/tests/test_auth/test_auth_cookie.py index 1cf50c2..876f24f 100644 --- a/tests/test_auth/test_auth_cookie.py +++ b/tests/test_auth/test_auth_cookie.py @@ -2,12 +2,18 @@ # This module is part of the Python Paste Project and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php +import os +try: + # Python 3 + from http.cookies import SimpleCookie +except ImportError: + # Python 2 + from Cookie import SimpleCookie + from paste.auth import cookie from paste.wsgilib import raw_interactive, dump_environ from paste.response import header_value from paste.httpexceptions import * -from Cookie import SimpleCookie -import urllib2, os def build(application,setenv, *args, **kwargs): def setter(environ, start_response): diff --git a/tests/test_auth/test_auth_digest.py b/tests/test_auth/test_auth_digest.py index 4721db3..55f953d 100644 --- a/tests/test_auth/test_auth_digest.py +++ b/tests/test_auth/test_auth_digest.py @@ -57,7 +57,8 @@ def test_digest(): # if os.environ.get("TEST_SOCKET",""): - import urllib2 + from six.moves.urllib.error import HTTPError + from six.moves.urllib.request import build_opener, HTTPDigestAuthHandler from paste.debug.testserver import serve server = serve(application) @@ -66,9 +67,9 @@ if os.environ.get("TEST_SOCKET",""): import socket socket.setdefaulttimeout(5) uri = ("http://%s:%s" % server.server_address) + path - auth = urllib2.HTTPDigestAuthHandler() + auth = HTTPDigestAuthHandler() auth.add_password(realm,uri,username,password) - opener = urllib2.build_opener(auth) + opener = build_opener(auth) result = opener.open(uri) return result.read() diff --git a/tests/test_fileapp.py b/tests/test_fileapp.py index edb4e4c..c0013fb 100644 --- a/tests/test_fileapp.py +++ b/tests/test_fileapp.py @@ -1,10 +1,17 @@ # (c) 2005 Ian Bicking, Clark C. Evans and contributors # This module is part of the Python Paste Project and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php +import string +import time +try: + # Python 3 + from email.utils import parsedate_tz, mktime_tz +except ImportError: + # Python 2 + from rfc822 import parsedate_tz, mktime_tz + from paste.fileapp import * from paste.fixture import * -from rfc822 import parsedate_tz, mktime_tz -import time, string def test_data(): harness = TestApp(DataApp('mycontent')) diff --git a/tests/test_gzipper.py b/tests/test_gzipper.py index 0832700..4f929b0 100644 --- a/tests/test_gzipper.py +++ b/tests/test_gzipper.py @@ -1,6 +1,7 @@ from paste.fixture import TestApp from paste.gzipper import middleware -import gzip, cStringIO +import gzip +from six.moves import cStringIO as StringIO def simple_app(environ, start_response): start_response('200 OK', [('content-type', 'text/plain')]) @@ -14,5 +15,5 @@ def test_gzip(): '/', extra_environ=dict(HTTP_ACCEPT_ENCODING='gzip')) assert int(res.header('content-length')) == len(res.body) assert res.body != 'this is a test' - actual = gzip.GzipFile(fileobj=cStringIO.StringIO(res.body)).read() + actual = gzip.GzipFile(fileobj=StringIO(res.body)).read() assert actual == 'this is a test' diff --git a/tests/test_multidict.py b/tests/test_multidict.py index c99b10f..893bfcd 100644 --- a/tests/test_multidict.py +++ b/tests/test_multidict.py @@ -2,8 +2,10 @@ # (c) 2007 Ian Bicking and Philip Jenvey; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import cgi +from six.moves import StringIO + from nose.tools import assert_raises -from StringIO import StringIO + from paste.fixture import TestApp from paste.wsgiwrappers import WSGIRequest from paste.util.multidict import MultiDict, UnicodeMultiDict diff --git a/tests/test_request_form.py b/tests/test_request_form.py index 321b3b0..036da3e 100644 --- a/tests/test_request_form.py +++ b/tests/test_request_form.py @@ -1,5 +1,6 @@ import cgi -from cStringIO import StringIO +from six.moves import cStringIO as StringIO + from paste.request import * from paste.util.multidict import MultiDict |