diff options
50 files changed, 125 insertions, 416 deletions
diff --git a/cherrypy/_cpchecker.py b/cherrypy/_cpchecker.py index 39b7c972..f26f319c 100644 --- a/cherrypy/_cpchecker.py +++ b/cherrypy/_cpchecker.py @@ -1,9 +1,7 @@ """Checker for CherryPy sites and mounted apps.""" import os import warnings - -import six -from six.moves import builtins +import builtins import cherrypy @@ -70,14 +68,14 @@ class Checker(object): def check_site_config_entries_in_app_config(self): """Check for mounted Applications that have site-scoped config.""" - for sn, app in six.iteritems(cherrypy.tree.apps): + for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue msg = [] - for section, entries in six.iteritems(app.config): + for section, entries in app.config.items(): if section.startswith('/'): - for key, value in six.iteritems(entries): + for key, value in entries.items(): for n in ('engine.', 'server.', 'tree.', 'checker.'): if key.startswith(n): msg.append('[%s] %s = %s' % diff --git a/cherrypy/_cpcompat.py b/cherrypy/_cpcompat.py index f454505c..bdb727d1 100644 --- a/cherrypy/_cpcompat.py +++ b/cherrypy/_cpcompat.py @@ -18,15 +18,13 @@ Instead, use unicode literals (from __future__) and bytes literals and their .encode/.decode methods as needed. """ -import re import sys import threading +import urllib.parse +import http.client -import six -from six.moves import urllib - -if six.PY3: +if True: def ntob(n, encoding='ISO-8859-1'): """Return the given native string as a byte string in the given encoding. @@ -49,43 +47,6 @@ if six.PY3: if isinstance(n, bytes): return n.decode(encoding) return n -else: - # Python 2 - def ntob(n, encoding='ISO-8859-1'): - """Return the given native string as a byte string in the given - encoding. - """ - assert_native(n) - # In Python 2, the native string type is bytes. Assume it's already - # in the given encoding, which for ISO-8859-1 is almost always what - # was intended. - return n - - def ntou(n, encoding='ISO-8859-1'): - """Return the given native string as a unicode string with the given - encoding. - """ - assert_native(n) - # In Python 2, the native string type is bytes. - # First, check for the special encoding 'escape'. The test suite uses - # this to signal that it wants to pass a string with embedded \uXXXX - # escapes, but without having to prefix it with u'' for Python 2, - # but no prefix for Python 3. - if encoding == 'escape': - return six.text_type( # unicode for Python 2 - re.sub(r'\\u([0-9a-zA-Z]{4})', - lambda m: six.unichr(int(m.group(1), 16)), - n.decode('ISO-8859-1'))) - # Assume it's already in the given encoding, which for ISO-8859-1 - # is almost always what was intended. - return n.decode(encoding) - - def tonative(n, encoding='ISO-8859-1'): - """Return the given string as a native string in the given encoding.""" - # In Python 2, the native string type is bytes. - if isinstance(n, six.text_type): # unicode for Python 2 - return n.encode(encoding) - return n def assert_native(n): @@ -94,24 +55,12 @@ def assert_native(n): # Some platforms don't expose HTTPSConnection, so handle it separately -HTTPSConnection = getattr(six.moves.http_client, 'HTTPSConnection', None) - +HTTPSConnection = getattr(http.client, 'HTTPSConnection', None) -def _unquote_plus_compat(string, encoding='utf-8', errors='replace'): - return urllib.parse.unquote_plus(string).decode(encoding, errors) - -def _unquote_compat(string, encoding='utf-8', errors='replace'): - return urllib.parse.unquote(string).decode(encoding, errors) - - -def _quote_compat(string, encoding='utf-8', errors='replace'): - return urllib.parse.quote(string.encode(encoding, errors)) - - -unquote_plus = urllib.parse.unquote_plus if six.PY3 else _unquote_plus_compat -unquote = urllib.parse.unquote if six.PY3 else _unquote_compat -quote = urllib.parse.quote if six.PY3 else _quote_compat +unquote_plus = urllib.parse.unquote_plus +unquote = urllib.parse.unquote +quote = urllib.parse.quote try: # Prefer simplejson @@ -124,16 +73,14 @@ json_decode = json.JSONDecoder().decode _json_encode = json.JSONEncoder().iterencode -if six.PY3: +if True: # Encode to bytes on Python 3 def json_encode(value): for chunk in _json_encode(value): yield chunk.encode('utf-8') -else: - json_encode = _json_encode -text_or_bytes = six.text_type, bytes +text_or_bytes = str, bytes if sys.version_info >= (3, 3): diff --git a/cherrypy/_cperror.py b/cherrypy/_cperror.py index e2a8fad8..100c6a6f 100644 --- a/cherrypy/_cperror.py +++ b/cherrypy/_cperror.py @@ -119,13 +119,11 @@ and not simply return an error message as a result. import io import contextlib +import urllib.parse from sys import exc_info as _exc_info from traceback import format_exception as _format_exception from xml.sax import saxutils -import six -from six.moves import urllib - from more_itertools import always_iterable import cherrypy @@ -496,7 +494,7 @@ def get_error_page(status, **kwargs): if kwargs.get('version') is None: kwargs['version'] = cherrypy.__version__ - for k, v in six.iteritems(kwargs): + for k, v in kwargs.items(): if v is None: kwargs[k] = '' else: @@ -520,13 +518,13 @@ def get_error_page(status, **kwargs): if cherrypy.lib.is_iterator(result): from cherrypy.lib.encoding import UTF8StreamEncoder return UTF8StreamEncoder(result) - elif isinstance(result, six.text_type): + elif isinstance(result, str): return result.encode('utf-8') else: if not isinstance(result, bytes): raise ValueError( 'error page function did not ' - 'return a bytestring, six.text_type or an ' + 'return a bytestring, str or an ' 'iterator - returned object of type %s.' % (type(result).__name__)) return result diff --git a/cherrypy/_cplogging.py b/cherrypy/_cplogging.py index 53b9addb..026161ee 100644 --- a/cherrypy/_cplogging.py +++ b/cherrypy/_cplogging.py @@ -113,8 +113,6 @@ import logging import os import sys -import six - import cherrypy from cherrypy import _cperror @@ -155,11 +153,7 @@ class LogManager(object): access_log = None """The actual :class:`logging.Logger` instance for access messages.""" - access_log_format = ( - '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"' - if six.PY3 else - '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' - ) + access_log_format = '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"' logger_root = None """The "top-level" logger name. @@ -254,8 +248,7 @@ class LogManager(object): status = '-' else: status = response.output_status.split(b' ', 1)[0] - if six.PY3: - status = status.decode('ISO-8859-1') + status = status.decode('ISO-8859-1') atoms = {'h': remote.name or remote.ip, 'l': '-', @@ -270,7 +263,7 @@ class LogManager(object): 'i': request.unique_id, 'z': LazyRfc3339UtcTime(), } - if six.PY3: + if True: for k, v in atoms.items(): if not isinstance(v, str): v = str(v) @@ -292,23 +285,6 @@ class LogManager(object): logging.INFO, self.access_log_format.format(**atoms)) except Exception: self(traceback=True) - else: - for k, v in atoms.items(): - if isinstance(v, six.text_type): - v = v.encode('utf8') - elif not isinstance(v, str): - v = str(v) - # Fortunately, repr(str) escapes unprintable chars, \n, \t, etc - # and backslash for us. All we have to do is strip the quotes. - v = repr(v)[1:-1] - # Escape double-quote. - atoms[k] = v.replace('"', '\\"') - - try: - self.access_log.log( - logging.INFO, self.access_log_format % atoms) - except Exception: - self(traceback=True) def time(self): """Return now() in Apache Common Log Format (no timezone).""" diff --git a/cherrypy/_cpmodpy.py b/cherrypy/_cpmodpy.py index ac91e625..85db4017 100644 --- a/cherrypy/_cpmodpy.py +++ b/cherrypy/_cpmodpy.py @@ -61,8 +61,6 @@ import os import re import sys -import six - from more_itertools import always_iterable import cherrypy @@ -197,7 +195,7 @@ def handler(req): path = req.uri qs = req.args or '' reqproto = req.protocol - headers = list(six.iteritems(req.headers_in)) + headers = list(req.headers_in.items()) rfile = _ReadOnlyRequest(req) prev = None diff --git a/cherrypy/_cpreqbody.py b/cherrypy/_cpreqbody.py index 893fe5f5..c898b072 100644 --- a/cherrypy/_cpreqbody.py +++ b/cherrypy/_cpreqbody.py @@ -131,7 +131,6 @@ except ImportError: pass return b''.join(atoms) -import six import cheroot.server import cherrypy @@ -986,12 +985,6 @@ class RequestBody(Entity): # add them in here. request_params = self.request_params for key, value in self.params.items(): - # Python 2 only: keyword arguments must be byte strings (type - # 'str'). - if sys.version_info < (3, 0): - if isinstance(key, six.text_type): - key = key.encode('ISO-8859-1') - if key in request_params: if not isinstance(request_params[key], list): request_params[key] = [request_params[key]] diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py index 3cc0c811..aa42f428 100644 --- a/cherrypy/_cprequest.py +++ b/cherrypy/_cprequest.py @@ -1,11 +1,9 @@ import sys import time +from http.cookies import SimpleCookie, CookieError import uuid -import six -from six.moves.http_cookies import SimpleCookie, CookieError - from more_itertools import consume import cherrypy @@ -141,7 +139,7 @@ def hooks_namespace(k, v): # hookpoint per path (e.g. "hooks.before_handler.1"). # Little-known fact you only get from reading source ;) hookpoint = k.split('.', 1)[0] - if isinstance(v, six.string_types): + if isinstance(v, str): v = cherrypy.lib.reprconf.attributes(v) if not isinstance(v, Hook): v = Hook(v) @@ -704,12 +702,6 @@ class Request(object): 'strings for this resource must be encoded with %r.' % self.query_string_encoding) - # Python 2 only: keyword arguments must be byte strings (type 'str'). - if six.PY2: - for key, value in p.items(): - if isinstance(key, six.text_type): - del p[key] - p[key.encode(self.query_string_encoding)] = value self.params.update(p) def process_headers(self): @@ -786,11 +778,11 @@ class ResponseBody(object): def __set__(self, obj, value): # Convert the given value to an iterable object. - if isinstance(value, six.text_type): + if isinstance(value, str): raise ValueError(self.unicode_err) elif isinstance(value, list): # every item in a list must be bytes... - if any(isinstance(item, six.text_type) for item in value): + if any(isinstance(item, str) for item in value): raise ValueError(self.unicode_err) obj._body = encoding.prepare_iter(value) @@ -903,9 +895,9 @@ class Response(object): if cookie: for line in cookie.split('\r\n'): name, value = line.split(': ', 1) - if isinstance(name, six.text_type): + if isinstance(name, str): name = name.encode('ISO-8859-1') - if isinstance(value, six.text_type): + if isinstance(value, str): value = headers.encode(value) h.append((name, value)) diff --git a/cherrypy/_cpserver.py b/cherrypy/_cpserver.py index 0f60e2c8..dd66b52a 100644 --- a/cherrypy/_cpserver.py +++ b/cherrypy/_cpserver.py @@ -1,7 +1,5 @@ """Manage HTTP servers with CherryPy.""" -import six - import cherrypy from cherrypy.lib.reprconf import attributes from cherrypy._cpcompat import text_or_bytes @@ -116,21 +114,13 @@ class Server(ServerAdapter): ssl_ciphers = None """The ciphers list of SSL.""" - if six.PY3: + if True: ssl_module = 'builtin' """The name of a registered SSL adaptation module to use with the builtin WSGI server. Builtin options are: 'builtin' (to use the SSL library built into recent versions of Python). You may also register your own classes in the cheroot.server.ssl_adapters dict.""" - else: - ssl_module = 'pyopenssl' - """The name of a registered SSL adaptation module to use with the - builtin WSGI server. Builtin options are 'builtin' (to use the SSL - library built into recent versions of Python) and 'pyopenssl' (to - use the PyOpenSSL project, which you must install separately). You - may also register your own classes in the cheroot.server.ssl_adapters - dict.""" statistics = False """Turns statistics-gathering on or off for aware HTTP servers.""" diff --git a/cherrypy/_cptools.py b/cherrypy/_cptools.py index 57460285..716f99a4 100644 --- a/cherrypy/_cptools.py +++ b/cherrypy/_cptools.py @@ -22,8 +22,6 @@ Tools may be implemented as any object with a namespace. The builtins are generally either modules or instances of the tools.Tool class. """ -import six - import cherrypy from cherrypy._helper import expose @@ -37,14 +35,9 @@ def _getargs(func): """Return the names of all static arguments to the given function.""" # Use this instead of importing inspect for less mem overhead. import types - if six.PY3: - if isinstance(func, types.MethodType): - func = func.__func__ - co = func.__code__ - else: - if isinstance(func, types.MethodType): - func = func.im_func - co = func.func_code + if isinstance(func, types.MethodType): + func = func.__func__ + co = func.__code__ return co.co_varnames[:co.co_argcount] diff --git a/cherrypy/_cptree.py b/cherrypy/_cptree.py index ceb54379..40a725a8 100644 --- a/cherrypy/_cptree.py +++ b/cherrypy/_cptree.py @@ -2,8 +2,6 @@ import os -import six - import cherrypy from cherrypy._cpcompat import ntou from cherrypy import _cpconfig, _cplogging, _cprequest, _cpwsgi, tools @@ -289,8 +287,6 @@ class Tree(object): # to '' (some WSGI servers always set SCRIPT_NAME to ''). # Try to look up the app using the full path. env1x = environ - if six.PY2 and environ.get(ntou('wsgi.version')) == (ntou('u'), 0): - env1x = _cpwsgi.downgrade_wsgi_ux_to_1x(environ) path = httputil.urljoin(env1x.get('SCRIPT_NAME', ''), env1x.get('PATH_INFO', '')) sn = self.script_name(path or '/') @@ -302,12 +298,6 @@ class Tree(object): # Correct the SCRIPT_NAME and PATH_INFO environ entries. environ = environ.copy() - if six.PY2 and environ.get(ntou('wsgi.version')) == (ntou('u'), 0): - # Python 2/WSGI u.0: all strings MUST be of type unicode - enc = environ[ntou('wsgi.url_encoding')] - environ[ntou('SCRIPT_NAME')] = sn.decode(enc) - environ[ntou('PATH_INFO')] = path[len(sn.rstrip('/')):].decode(enc) - else: - environ['SCRIPT_NAME'] = sn - environ['PATH_INFO'] = path[len(sn.rstrip('/')):] + environ['SCRIPT_NAME'] = sn + environ['PATH_INFO'] = path[len(sn.rstrip('/')):] return app(environ, start_response) diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py index 0b4942ff..c2d36f67 100644 --- a/cherrypy/_cpwsgi.py +++ b/cherrypy/_cpwsgi.py @@ -10,8 +10,6 @@ still be translatable to bytes via the Latin-1 encoding!" import sys as _sys import io -import six - import cherrypy as _cherrypy from cherrypy._cpcompat import ntou from cherrypy import _cperror @@ -28,7 +26,7 @@ def downgrade_wsgi_ux_to_1x(environ): for k, v in list(environ.items()): if k in [ntou('PATH_INFO'), ntou('SCRIPT_NAME'), ntou('QUERY_STRING')]: v = v.encode(url_encoding) - elif isinstance(v, six.text_type): + elif isinstance(v, str): v = v.encode('ISO-8859-1') env1x[k.encode('ISO-8859-1')] = v @@ -177,10 +175,6 @@ class _TrappedResponse(object): def __next__(self): return self.trap(next, self.iter_response) - # todo: https://pythonhosted.org/six/#six.Iterator - if six.PY2: - next = __next__ - def close(self): if hasattr(self.response, 'close'): self.response.close() @@ -198,7 +192,7 @@ class _TrappedResponse(object): if not _cherrypy.request.show_tracebacks: tb = '' s, h, b = _cperror.bare_error(tb) - if six.PY3: + if True: # What fun. s = s.decode('ISO-8859-1') h = [ @@ -238,9 +232,6 @@ class AppResponse(object): def __init__(self, environ, start_response, cpapp): self.cpapp = cpapp try: - if six.PY2: - if environ.get(ntou('wsgi.version')) == (ntou('u'), 0): - environ = downgrade_wsgi_ux_to_1x(environ) self.environ = environ self.run() @@ -262,7 +253,7 @@ class AppResponse(object): raise TypeError(tmpl % v) outheaders.append((k, v)) - if six.PY3: + if True: # According to PEP 3333, when using Python 3, the response # status and headers must be bytes masquerading as unicode; # that is, they must be of type "str" but are restricted to @@ -285,10 +276,6 @@ class AppResponse(object): def __next__(self): return next(self.iter_response) - # todo: https://pythonhosted.org/six/#six.Iterator - if six.PY2: - next = __next__ - def close(self): """Close and de-reference the current request and response. (Core)""" streaming = _cherrypy.serving.response.stream @@ -356,9 +343,6 @@ class AppResponse(object): } def recode_path_qs(self, path, qs): - if not six.PY3: - return - # This isn't perfect; if the given PATH_INFO is in the # wrong encoding, it may fail to match the appropriate config # section URI. But meh. diff --git a/cherrypy/_helper.py b/cherrypy/_helper.py index 314550cb..328e4edb 100644 --- a/cherrypy/_helper.py +++ b/cherrypy/_helper.py @@ -1,7 +1,6 @@ """Helper functions for CP apps.""" -import six -from six.moves import urllib +import urllib.parse from cherrypy._cpcompat import text_or_bytes @@ -26,9 +25,6 @@ def expose(func=None, alias=None): import sys import types decoratable_types = types.FunctionType, types.MethodType, type, - if six.PY2: - # Old-style classes are type types.ClassType. - decoratable_types += types.ClassType, if isinstance(func, decoratable_types): if alias is None: # @expose diff --git a/cherrypy/lib/auth_digest.py b/cherrypy/lib/auth_digest.py index 9b4f55c8..fbb5df64 100644 --- a/cherrypy/lib/auth_digest.py +++ b/cherrypy/lib/auth_digest.py @@ -23,8 +23,7 @@ of plaintext passwords as the credentials store:: import time import functools from hashlib import md5 - -from six.moves.urllib.request import parse_http_list, parse_keqv_list +from urllib.request import parse_http_list, parse_keqv_list import cherrypy from cherrypy._cpcompat import ntob, tonative diff --git a/cherrypy/lib/caching.py b/cherrypy/lib/caching.py index fed325a6..5d9e5cfb 100644 --- a/cherrypy/lib/caching.py +++ b/cherrypy/lib/caching.py @@ -37,8 +37,6 @@ import sys import threading import time -import six - import cherrypy from cherrypy.lib import cptools, httputil from cherrypy._cpcompat import Event @@ -199,7 +197,7 @@ class MemoryCache(Cache): now = time.time() # Must make a copy of expirations so it doesn't change size # during iteration - items = list(six.iteritems(self.expirations)) + items = list(self.expirations.items()) for expiration_time, objects in items: if expiration_time <= now: for obj_size, uri, sel_header_values in objects: diff --git a/cherrypy/lib/covercp.py b/cherrypy/lib/covercp.py index 0bafca13..3e219713 100644 --- a/cherrypy/lib/covercp.py +++ b/cherrypy/lib/covercp.py @@ -25,8 +25,7 @@ import sys import cgi import os import os.path - -from six.moves import urllib +import urllib.parse import cherrypy diff --git a/cherrypy/lib/cpstats.py b/cherrypy/lib/cpstats.py index ae9f7475..1bfd354a 100644 --- a/cherrypy/lib/cpstats.py +++ b/cherrypy/lib/cpstats.py @@ -193,8 +193,6 @@ import sys import threading import time -import six - import cherrypy from cherrypy._cpcompat import json @@ -613,7 +611,7 @@ table.stats2 th { """Return ([headers], [rows]) for the given collection.""" # E.g., the 'Requests' dict. headers = [] - vals = six.itervalues(v) + vals = v.values() for record in vals: for k3 in record: format = formatting.get(k3, missing) diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py index 1c079634..82f897a0 100644 --- a/cherrypy/lib/cptools.py +++ b/cherrypy/lib/cptools.py @@ -3,9 +3,7 @@ import logging import re from hashlib import md5 - -import six -from six.moves import urllib +import urllib.parse import cherrypy from cherrypy._cpcompat import text_or_bytes @@ -307,7 +305,7 @@ class SessionAuth(object): def login_screen(self, from_page='..', username='', error_msg='', **kwargs): - return (six.text_type("""<html><body> + return (str("""<html><body> Message: %(error_msg)s <form method="post" action="do_login"> Login: <input type="text" name="username" value="%(username)s" size="10" /> diff --git a/cherrypy/lib/encoding.py b/cherrypy/lib/encoding.py index 3d001ca6..54a7a8a8 100644 --- a/cherrypy/lib/encoding.py +++ b/cherrypy/lib/encoding.py @@ -2,8 +2,6 @@ import struct import time import io -import six - import cherrypy from cherrypy._cpcompat import text_or_bytes from cherrypy.lib import file_generator @@ -50,7 +48,7 @@ class UTF8StreamEncoder: def __next__(self): res = next(self._iterator) - if isinstance(res, six.text_type): + if isinstance(res, str): res = res.encode('utf-8') return res @@ -99,7 +97,7 @@ class ResponseEncoder: def encoder(body): for chunk in body: - if isinstance(chunk, six.text_type): + if isinstance(chunk, str): chunk = chunk.encode(encoding, self.errors) yield chunk self.body = encoder(self.body) @@ -112,7 +110,7 @@ class ResponseEncoder: self.attempted_charsets.add(encoding) body = [] for chunk in self.body: - if isinstance(chunk, six.text_type): + if isinstance(chunk, str): try: chunk = chunk.encode(encoding, self.errors) except (LookupError, UnicodeError): diff --git a/cherrypy/lib/httputil.py b/cherrypy/lib/httputil.py index b68d8dd5..db35b6e3 100644 --- a/cherrypy/lib/httputil.py +++ b/cherrypy/lib/httputil.py @@ -10,13 +10,11 @@ to a public caning. import functools import email.utils import re +import builtins from binascii import b2a_base64 from cgi import parse_header from email.header import decode_header - -import six -from six.moves import range, builtins, map -from six.moves.BaseHTTPServer import BaseHTTPRequestHandler +from http.server import BaseHTTPRequestHandler import cherrypy from cherrypy._cpcompat import ntob, ntou @@ -143,7 +141,7 @@ class HeaderElement(object): return self.value < other.value def __str__(self): - p = [';%s=%s' % (k, v) for k, v in six.iteritems(self.params)] + p = [';%s=%s' % (k, v) for k, v in self.params.items()] return str('%s%s' % (self.value, ''.join(p))) def __bytes__(self): @@ -209,14 +207,11 @@ class AcceptElement(HeaderElement): Ref: https://github.com/cherrypy/cherrypy/issues/1370 """ - six.raise_from( - cherrypy.HTTPError( - 400, - 'Malformed HTTP header: `{}`'. - format(str(self)), - ), - val_err, - ) + raise cherrypy.HTTPError( + 400, + 'Malformed HTTP header: `{}`'. + format(str(self)), + ) from val_err def __cmp__(self, other): diff = builtins.cmp(self.qvalue, other.qvalue) @@ -295,7 +290,7 @@ def valid_status(status): status = 200 code, reason = status, None - if isinstance(status, six.string_types): + if isinstance(status, str): code, _, reason = status.partition(' ') reason = reason.strip() or None @@ -518,14 +513,14 @@ class HeaderMap(CaseInsensitiveDict): transmitting on the wire for HTTP. """ for k, v in header_items: - if not isinstance(v, six.string_types): - v = six.text_type(v) + if not isinstance(v, str): + v = str(v) yield tuple(map(cls.encode_header_item, (k, v))) @classmethod def encode_header_item(cls, item): - if isinstance(item, six.text_type): + if isinstance(item, str): item = cls.encode(item) # See header_translate_* constants above. diff --git a/cherrypy/lib/reprconf.py b/cherrypy/lib/reprconf.py index 291ab663..baa7248a 100644 --- a/cherrypy/lib/reprconf.py +++ b/cherrypy/lib/reprconf.py @@ -18,13 +18,13 @@ by adding a named handler to Config.namespaces. The name can be any string, and the handler must be either a callable or a context manager. """ -from cherrypy._cpcompat import text_or_bytes -from six.moves import configparser -from six.moves import builtins - +import configparser +import builtins import operator import sys +from cherrypy._cpcompat import text_or_bytes + class NamespaceSet(dict): @@ -62,9 +62,9 @@ class NamespaceSet(dict): # I chose __enter__ and __exit__ so someday this could be # rewritten using Python 2.5's 'with' statement: - # for ns, handler in six.iteritems(self): + # for ns, handler in self.items(): # with handler as callable: - # for k, v in six.iteritems(ns_confs.get(ns, {})): + # for k, v in ns_confs.get(ns, {}).items(): # callable(k, v) for ns, handler in self.items(): exit = getattr(handler, '__exit__', None) diff --git a/cherrypy/lib/sessions.py b/cherrypy/lib/sessions.py index 5b49ee13..2eeaa216 100644 --- a/cherrypy/lib/sessions.py +++ b/cherrypy/lib/sessions.py @@ -106,9 +106,8 @@ import os import time import threading import binascii +import pickle -import six -from six.moves import cPickle as pickle import contextlib2 import zc.lockfile @@ -119,10 +118,6 @@ from cherrypy.lib import locking from cherrypy.lib import is_iterator -if six.PY2: - FileNotFoundError = OSError - - missing = object() @@ -410,7 +405,7 @@ class RamSession(Session): """Clean up expired sessions.""" now = self.now() - for _id, (data, expiration_time) in list(six.iteritems(self.cache)): + for _id, (data, expiration_time) in list(self.cache.items()): if expiration_time <= now: try: del self.cache[_id] diff --git a/cherrypy/lib/static.py b/cherrypy/lib/static.py index da9d9373..9a3b8e83 100644 --- a/cherrypy/lib/static.py +++ b/cherrypy/lib/static.py @@ -5,12 +5,11 @@ import platform import re import stat import mimetypes +import urllib.parse from email.generator import _make_boundary as make_boundary from io import UnsupportedOperation -from six.moves import urllib - import cherrypy from cherrypy._cpcompat import ntob from cherrypy.lib import cptools, httputil, file_generator_limited diff --git a/cherrypy/lib/xmlrpcutil.py b/cherrypy/lib/xmlrpcutil.py index ddaac86a..29d9c4a2 100644 --- a/cherrypy/lib/xmlrpcutil.py +++ b/cherrypy/lib/xmlrpcutil.py @@ -1,7 +1,6 @@ """XML-RPC tool helpers.""" import sys - -from six.moves.xmlrpc_client import ( +from xmlrpc.client import ( loads as xmlrpc_loads, dumps as xmlrpc_dumps, Fault as XMLRPCFault ) diff --git a/cherrypy/process/plugins.py b/cherrypy/process/plugins.py index 8c246c81..212ed250 100644 --- a/cherrypy/process/plugins.py +++ b/cherrypy/process/plugins.py @@ -6,8 +6,7 @@ import signal as _signal import sys import time import threading - -from six.moves import _thread +import _thread from cherrypy._cpcompat import text_or_bytes from cherrypy._cpcompat import ntob, Timer diff --git a/cherrypy/process/wspbus.py b/cherrypy/process/wspbus.py index d91dba48..8f762ef0 100644 --- a/cherrypy/process/wspbus.py +++ b/cherrypy/process/wspbus.py @@ -81,8 +81,6 @@ import warnings import subprocess import functools -import six - # Here I save the value of os.getcwd(), which, if I am imported early enough, # will be the directory from which the startup script was run. This is needed @@ -436,7 +434,7 @@ class Bus(object): :seealso: http://stackoverflow.com/a/28414807/595220 """ try: - char_p = ctypes.c_char_p if six.PY2 else ctypes.c_wchar_p + char_p = ctypes.c_wchar_p argv = ctypes.POINTER(char_p)() argc = ctypes.c_int() diff --git a/cherrypy/test/helper.py b/cherrypy/test/helper.py index 01c5a0c0..1f8ab236 100644 --- a/cherrypy/test/helper.py +++ b/cherrypy/test/helper.py @@ -13,7 +13,6 @@ import warnings import portend import pytest -import six from cheroot.test import webtest @@ -93,7 +92,7 @@ class LocalSupervisor(Supervisor): cherrypy.engine.exit() - servers_copy = list(six.iteritems(getattr(cherrypy, 'servers', {}))) + servers_copy = list(getattr(cherrypy, 'servers', {}).items()) for name, server in servers_copy: server.unsubscribe() del cherrypy.servers[name] @@ -449,7 +448,7 @@ server.ssl_private_key: r'%s' 'extra': extra, } with io.open(self.config_file, 'w', encoding='utf-8') as f: - f.write(six.text_type(conf)) + f.write(str(conf)) def start(self, imports=None): """Start cherryd in a subprocess.""" diff --git a/cherrypy/test/logtest.py b/cherrypy/test/logtest.py index ed8f1540..cc3afcfe 100644 --- a/cherrypy/test/logtest.py +++ b/cherrypy/test/logtest.py @@ -4,8 +4,6 @@ import sys import time from uuid import UUID -import six - from cherrypy._cpcompat import text_or_bytes, ntob @@ -121,7 +119,7 @@ class LogCase(object): if marker is None: return open(logfile, 'rb').readlines() - if isinstance(marker, six.text_type): + if isinstance(marker, str): marker = marker.encode('utf-8') data = [] in_region = False @@ -201,7 +199,7 @@ class LogCase(object): # Single arg. Use __getitem__ and allow lines to be str or list. if isinstance(lines, (tuple, list)): lines = lines[0] - if isinstance(lines, six.text_type): + if isinstance(lines, str): lines = lines.encode('utf-8') if lines not in data[sliceargs]: msg = '%r not found on log line %r' % (lines, sliceargs) @@ -221,7 +219,7 @@ class LogCase(object): start, stop = sliceargs for line, logline in zip(lines, data[start:stop]): - if isinstance(line, six.text_type): + if isinstance(line, str): line = line.encode('utf-8') if line not in logline: msg = '%r not found in log' % line diff --git a/cherrypy/test/sessiondemo.py b/cherrypy/test/sessiondemo.py index 8226c1b9..3849a259 100755 --- a/cherrypy/test/sessiondemo.py +++ b/cherrypy/test/sessiondemo.py @@ -5,8 +5,6 @@ import calendar from datetime import datetime import sys -import six - import cherrypy from cherrypy.lib import sessions @@ -123,7 +121,7 @@ class Root(object): 'changemsg': '<br>'.join(changemsg), 'respcookie': cherrypy.response.cookie.output(), 'reqcookie': cherrypy.request.cookie.output(), - 'sessiondata': list(six.iteritems(cherrypy.session)), + 'sessiondata': list(cherrypy.session.items()), 'servertime': ( datetime.utcnow().strftime('%Y/%m/%d %H:%M') + ' UTC' ), diff --git a/cherrypy/test/test_auth_digest.py b/cherrypy/test/test_auth_digest.py index 512e39a5..745f89e6 100644 --- a/cherrypy/test/test_auth_digest.py +++ b/cherrypy/test/test_auth_digest.py @@ -2,8 +2,6 @@ # -*- coding: utf-8 -*- # vim:ts=4:sw=4:expandtab:fileencoding=utf-8 -import six - import cherrypy from cherrypy.lib import auth_digest @@ -92,8 +90,7 @@ class DigestAuthTest(helper.CPWebCase): 'cnonce="1522e61005789929"') encoded_user = username - if six.PY3: - encoded_user = encoded_user.encode('utf-8') + encoded_user = encoded_user.encode('utf-8') encoded_user = encoded_user.decode('latin1') auth_header = base_auth % ( encoded_user, realm, nonce, test_uri, diff --git a/cherrypy/test/test_caching.py b/cherrypy/test/test_caching.py index 1a6ed4f2..19ef05bd 100644 --- a/cherrypy/test/test_caching.py +++ b/cherrypy/test/test_caching.py @@ -3,9 +3,7 @@ from itertools import count import os import threading import time - -from six.moves import range -from six.moves import urllib +import urllib.parse import pytest diff --git a/cherrypy/test/test_compat.py b/cherrypy/test/test_compat.py index 44a9fa31..21786a82 100644 --- a/cherrypy/test/test_compat.py +++ b/cherrypy/test/test_compat.py @@ -3,26 +3,9 @@ from __future__ import unicode_literals import unittest -import pytest -import six - from cherrypy import _cpcompat as compat -class StringTester(unittest.TestCase): - """Tests for string conversion.""" - - @pytest.mark.skipif(six.PY3, reason='Only useful on Python 2') - def test_ntob_non_native(self): - """ntob should raise an Exception on unicode. - - (Python 2 only) - - See #1132 for discussion. - """ - self.assertRaises(TypeError, compat.ntob, 'fight') - - class EscapeTester(unittest.TestCase): """Class to test escape_html function from _cpcompat.""" diff --git a/cherrypy/test/test_config.py b/cherrypy/test/test_config.py index be17df90..4dfea74d 100644 --- a/cherrypy/test/test_config.py +++ b/cherrypy/test/test_config.py @@ -5,8 +5,6 @@ import os import sys import unittest -import six - import cherrypy from cherrypy.test import helper @@ -16,7 +14,7 @@ localDir = os.path.join(os.getcwd(), os.path.dirname(__file__)) def StringIOFromNative(x): - return io.StringIO(six.text_type(x)) + return io.StringIO(str(x)) def setup_server(): @@ -105,18 +103,12 @@ def setup_server(): def incr(self, num): return num + 1 - if not six.PY3: - thing3 = "thing3: unicode('test', errors='ignore')" - else: - thing3 = '' - ioconf = StringIOFromNative(""" [/] neg: -1234 filename: os.path.join(sys.prefix, "hello.py") thing1: cherrypy.lib.httputil.response_codes[404] thing2: __import__('cherrypy.tutorial', globals(), locals(), ['']).thing2 -%s complex: 3+2j mul: 6*3 ones: "11" @@ -125,7 +117,7 @@ stradd: %%(ones)s + %%(twos)s + "33" [/favicon.ico] tools.staticfile.filename = %r -""" % (thing3, os.path.join(localDir, 'static/dirback.jpg'))) +""" % os.path.join(localDir, 'static/dirback.jpg')) root = Root() root.foo = Foo() @@ -203,10 +195,6 @@ class ConfigTests(helper.CPWebCase): from cherrypy.tutorial import thing2 self.assertBody(repr(thing2)) - if not six.PY3: - self.getPage('/repr?key=thing3') - self.assertBody(repr(six.text_type('test'))) - self.getPage('/repr?key=complex') self.assertBody('(3+2j)') diff --git a/cherrypy/test/test_conn.py b/cherrypy/test/test_conn.py index 7d60c6fb..1e160b4e 100644 --- a/cherrypy/test/test_conn.py +++ b/cherrypy/test/test_conn.py @@ -4,10 +4,8 @@ import errno import socket import sys import time - -import six -from six.moves import urllib -from six.moves.http_client import BadStatusLine, HTTPConnection, NotConnected +import urllib.parse +from http.client import BadStatusLine, HTTPConnection, NotConnected import pytest @@ -91,7 +89,7 @@ def setup_server(): body = [body] newbody = [] for chunk in body: - if isinstance(chunk, six.text_type): + if isinstance(chunk, str): chunk = chunk.encode('ISO-8859-1') newbody.append(chunk) return newbody @@ -441,8 +439,7 @@ class PipelineTests(helper.CPWebCase): # ``conn.sock``. Until that bug get's fixed we will # monkey patch the ``response`` instance. # https://bugs.python.org/issue23377 - if six.PY3: - response.fp = conn.sock.makefile('rb', 0) + response.fp = conn.sock.makefile('rb', 0) response.begin() body = response.read(13) self.assertEqual(response.status, 200) diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index 9834c1f3..eae90b10 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -6,8 +6,6 @@ import os import sys import types -import six - import cherrypy from cherrypy._cpcompat import ntou from cherrypy import _cptools, tools @@ -57,7 +55,7 @@ class CoreRequestHandlingTest(helper.CPWebCase): """ def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) - for value in six.itervalues(dct): + for value in dct.values(): if isinstance(value, types.FunctionType): value.exposed = True setattr(root, name.lower(), cls()) diff --git a/cherrypy/test/test_dynamicobjectmapping.py b/cherrypy/test/test_dynamicobjectmapping.py index 725a3ce0..aaa89ca7 100644 --- a/cherrypy/test/test_dynamicobjectmapping.py +++ b/cherrypy/test/test_dynamicobjectmapping.py @@ -1,5 +1,3 @@ -import six - import cherrypy from cherrypy.test import helper @@ -79,7 +77,7 @@ def setup_server(): self.name = name def __unicode__(self): - return six.text_type(self.name) + return str(self.name) def __str__(self): return str(self.name) @@ -105,7 +103,7 @@ def setup_server(): return 'POST %d' % make_user(name) def GET(self): - return six.text_type(sorted(user_lookup.keys())) + return str(sorted(user_lookup.keys())) def dynamic_dispatch(self, vpath): try: @@ -130,7 +128,7 @@ def setup_server(): """ Return the appropriate representation of the instance. """ - return six.text_type(self.user) + return str(self.user) def POST(self, name): """ diff --git a/cherrypy/test/test_encoding.py b/cherrypy/test/test_encoding.py index ab24ab93..44cc08f7 100644 --- a/cherrypy/test/test_encoding.py +++ b/cherrypy/test/test_encoding.py @@ -3,9 +3,8 @@ import gzip import io from unittest import mock - -from six.moves.http_client import IncompleteRead -from six.moves.urllib.parse import quote as url_quote +from http.client import IncompleteRead +from urllib.parse import quote as url_quote import cherrypy from cherrypy._cpcompat import ntob, ntou diff --git a/cherrypy/test/test_http.py b/cherrypy/test/test_http.py index 0899d4d0..16b1e819 100644 --- a/cherrypy/test/test_http.py +++ b/cherrypy/test/test_http.py @@ -6,10 +6,8 @@ import mimetypes import socket import sys from unittest import mock - -import six -from six.moves.http_client import HTTPConnection -from six.moves import urllib +import urllib.parse +from http.client import HTTPConnection import cherrypy from cherrypy._cpcompat import HTTPSConnection, quote @@ -105,14 +103,12 @@ class HTTPTests(helper.CPWebCase): count += 1 else: if count: - if six.PY3: - curchar = chr(curchar) + curchar = chr(curchar) summary.append('%s * %d' % (curchar, count)) count = 1 curchar = c if count: - if six.PY3: - curchar = chr(curchar) + curchar = chr(curchar) summary.append('%s * %d' % (curchar, count)) return ', '.join(summary) diff --git a/cherrypy/test/test_httputil.py b/cherrypy/test/test_httputil.py index 656b8a3d..fe6a3f41 100644 --- a/cherrypy/test/test_httputil.py +++ b/cherrypy/test/test_httputil.py @@ -1,6 +1,6 @@ """Test helpers from ``cherrypy.lib.httputil`` module.""" import pytest -from six.moves import http_client +import http.client from cherrypy.lib import httputil @@ -49,12 +49,12 @@ EXPECTED_444 = (444, 'Non-existent reason', '') (None, EXPECTED_200), (200, EXPECTED_200), ('500', EXPECTED_500), - (http_client.NOT_FOUND, EXPECTED_404), + (http.client.NOT_FOUND, EXPECTED_404), ('444 Non-existent reason', EXPECTED_444), ] ) def test_valid_status(status, expected_status): - """Check valid int, string and http_client-constants + """Check valid int, string and http.client-constants statuses processing.""" assert httputil.valid_status(status) == expected_status diff --git a/cherrypy/test/test_iterator.py b/cherrypy/test/test_iterator.py index 92f08e7c..6600a78d 100644 --- a/cherrypy/test/test_iterator.py +++ b/cherrypy/test/test_iterator.py @@ -1,5 +1,3 @@ -import six - import cherrypy from cherrypy.test import helper @@ -88,7 +86,7 @@ class IteratorTest(helper.CPWebCase): @cherrypy.expose def count(self, clsname): cherrypy.response.headers['Content-Type'] = 'text/plain' - return six.text_type(globals()[clsname].created) + return str(globals()[clsname].created) @cherrypy.expose def getall(self, clsname): @@ -139,7 +137,7 @@ class IteratorTest(helper.CPWebCase): headers = response.getheaders() for header_name, header_value in headers: if header_name.lower() == 'content-length': - expected = six.text_type(1024 * 16 * 256) + expected = str(1024 * 16 * 256) assert header_value == expected, header_value break else: diff --git a/cherrypy/test/test_logging.py b/cherrypy/test/test_logging.py index c4948c20..26ba5bbf 100644 --- a/cherrypy/test/test_logging.py +++ b/cherrypy/test/test_logging.py @@ -3,8 +3,6 @@ import os from unittest import mock -import six - import cherrypy from cherrypy._cpcompat import ntou from cherrypy.test import helper, logtest @@ -109,9 +107,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): @mock.patch( 'cherrypy._cplogging.LogManager.access_log_format', - '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}" {o}' - if six.PY3 else - '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s' + '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}" {o}', ) def testCustomLogFormat(self): """Test a customized access_log_format string, which is a @@ -126,9 +122,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): @mock.patch( 'cherrypy._cplogging.LogManager.access_log_format', - '{h} {l} {u} {z} "{r}" {s} {b} "{f}" "{a}" {o}' - if six.PY3 else - '%(h)s %(l)s %(u)s %(z)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s' + '{h} {l} {u} {z} "{r}" {s} {b} "{f}" "{a}" {o}', ) def testTimezLogFormat(self): """Test a customized access_log_format string, which is a @@ -150,7 +144,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): @mock.patch( 'cherrypy._cplogging.LogManager.access_log_format', - '{i}' if six.PY3 else '%(i)s' + '{i}', ) def testUUIDv4ParameterLogFormat(self): """Test rendering of UUID4 within access log.""" @@ -163,11 +157,8 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): self.markLog() self.getPage('/uni_code') self.assertStatus(200) - if six.PY3: - # The repr of a bytestring in six.PY3 includes a b'' prefix - self.assertLog(-1, repr(tartaros.encode('utf8'))[2:-1]) - else: - self.assertLog(-1, repr(tartaros.encode('utf8'))[1:-1]) + # The repr of a bytestring includes a b'' prefix + self.assertLog(-1, repr(tartaros.encode('utf8'))[2:-1]) # Test the erebos value. Included inline for your enlightenment. # Note the 'r' prefix--those backslashes are literals. self.assertLog(-1, r'\xce\x88\xcf\x81\xce\xb5\xce\xb2\xce\xbf\xcf\x82') @@ -176,10 +167,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): self.markLog() self.getPage('/slashes') self.assertStatus(200) - if six.PY3: - self.assertLog(-1, b'"GET /slashed\\path HTTP/1.1"') - else: - self.assertLog(-1, r'"GET /slashed\\path HTTP/1.1"') + self.assertLog(-1, b'"GET /slashed\\path HTTP/1.1"') # Test whitespace in output. self.markLog() diff --git a/cherrypy/test/test_refleaks.py b/cherrypy/test/test_refleaks.py index c2fe9e66..95813679 100644 --- a/cherrypy/test/test_refleaks.py +++ b/cherrypy/test/test_refleaks.py @@ -3,8 +3,7 @@ import itertools import platform import threading - -from six.moves.http_client import HTTPConnection +from http.client import HTTPConnection import cherrypy from cherrypy._cpcompat import HTTPSConnection diff --git a/cherrypy/test/test_request_obj.py b/cherrypy/test/test_request_obj.py index 6b93e13d..31023e8f 100644 --- a/cherrypy/test/test_request_obj.py +++ b/cherrypy/test/test_request_obj.py @@ -5,9 +5,7 @@ import os import sys import types import uuid - -import six -from six.moves.http_client import IncompleteRead +from http.client import IncompleteRead import cherrypy from cherrypy._cpcompat import ntou @@ -243,7 +241,7 @@ class RequestObjectTests(helper.CPWebCase): def ifmatch(self): val = cherrypy.request.headers['If-Match'] - assert isinstance(val, six.text_type) + assert isinstance(val, str) cherrypy.response.headers['ETag'] = val return val @@ -251,7 +249,7 @@ class RequestObjectTests(helper.CPWebCase): def get_elements(self, headername): e = cherrypy.request.headers.elements(headername) - return '\n'.join([six.text_type(x) for x in e]) + return '\n'.join([str(x) for x in e]) class Method(Test): diff --git a/cherrypy/test/test_session.py b/cherrypy/test/test_session.py index 0083c97c..0bf48181 100755 --- a/cherrypy/test/test_session.py +++ b/cherrypy/test/test_session.py @@ -3,8 +3,7 @@ import threading import time import socket import importlib - -from six.moves.http_client import HTTPConnection +from http.client import HTTPConnection import pytest from path import Path diff --git a/cherrypy/test/test_states.py b/cherrypy/test/test_states.py index 606ca4f6..a5addbca 100644 --- a/cherrypy/test/test_states.py +++ b/cherrypy/test/test_states.py @@ -3,8 +3,7 @@ import signal import time import unittest import warnings - -from six.moves.http_client import BadStatusLine +from http.client import BadStatusLine import pytest import portend diff --git a/cherrypy/test/test_static.py b/cherrypy/test/test_static.py index 5dc5a144..5bb74e6f 100644 --- a/cherrypy/test/test_static.py +++ b/cherrypy/test/test_static.py @@ -5,10 +5,8 @@ import os import sys import platform import tempfile - -from six import text_type as str -from six.moves import urllib -from six.moves.http_client import HTTPConnection +import urllib.parse +from http.client import HTTPConnection import pytest import py.path diff --git a/cherrypy/test/test_tools.py b/cherrypy/test/test_tools.py index a73a3898..3a0fd389 100644 --- a/cherrypy/test/test_tools.py +++ b/cherrypy/test/test_tools.py @@ -7,10 +7,7 @@ import time import types import unittest import operator - -import six -from six.moves import range, map -from six.moves.http_client import IncompleteRead +from http.client import IncompleteRead import cherrypy from cherrypy import tools @@ -52,7 +49,7 @@ class ToolTests(helper.CPWebCase): def _setup(self): def makemap(): m = self._merged_args().get('map', {}) - cherrypy.request.numerify_map = list(six.iteritems(m)) + cherrypy.request.numerify_map = list(m.items()) cherrypy.request.hooks.attach('on_start_resource', makemap) def critical(): @@ -105,10 +102,7 @@ class ToolTests(helper.CPWebCase): def __call__(self, scale): r = cherrypy.response r.collapse_body() - if six.PY3: - r.body = [bytes([(x + scale) % 256 for x in r.body[0]])] - else: - r.body = [chr((ord(x) + scale) % 256) for x in r.body[0]] + r.body = [bytes([(x + scale) % 256 for x in r.body[0]])] cherrypy.tools.rotator = cherrypy.Tool('before_finalize', Rotator()) def stream_handler(next_handler, *args, **kwargs): @@ -179,7 +173,7 @@ class ToolTests(helper.CPWebCase): """ def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) - for value in six.itervalues(dct): + for value in dct.values(): if isinstance(value, types.FunctionType): cherrypy.expose(value) setattr(root, name.lower(), cls()) @@ -346,7 +340,7 @@ class ToolTests(helper.CPWebCase): self.getPage('/demo/err_in_onstart') self.assertErrorPage(502) tmpl = "AttributeError: 'str' object has no attribute '{attr}'" - expected_msg = tmpl.format(attr='items' if six.PY3 else 'iteritems') + expected_msg = tmpl.format(attr='items') self.assertInBody(expected_msg) def testCombinedTools(self): @@ -377,11 +371,7 @@ class ToolTests(helper.CPWebCase): # but it proves the priority was changed. self.getPage('/decorated_euro/subpath', headers=[('Accept-Encoding', 'gzip')]) - if six.PY3: - self.assertInBody(bytes([(x + 3) % 256 for x in zbuf.getvalue()])) - else: - self.assertInBody(''.join([chr((ord(x) + 3) % 256) - for x in zbuf.getvalue()])) + self.assertInBody(bytes([(x + 3) % 256 for x in zbuf.getvalue()])) def testBareHooks(self): content = 'bit of a pain in me gulliver' @@ -446,8 +436,8 @@ class SessionAuthTest(unittest.TestCase): username and password were unicode. """ sa = cherrypy.lib.cptools.SessionAuth() - res = sa.login_screen(None, username=six.text_type('nobody'), - password=six.text_type('anypass')) + res = sa.login_screen(None, username=str('nobody'), + password=str('anypass')) self.assertTrue(isinstance(res, bytes)) diff --git a/cherrypy/test/test_tutorials.py b/cherrypy/test/test_tutorials.py index efa35b99..fcae18ce 100644 --- a/cherrypy/test/test_tutorials.py +++ b/cherrypy/test/test_tutorials.py @@ -3,8 +3,6 @@ import imp import types import importlib -import six - import cherrypy from cherrypy.test import helper @@ -39,8 +37,6 @@ class TutorialTest(helper.CPWebCase): root = getattr(module, root_name) conf = getattr(module, 'tutconf') class_types = type, - if six.PY2: - class_types += types.ClassType, if isinstance(root, class_types): root = root() cherrypy.tree.mount(root, config=conf) diff --git a/cherrypy/test/test_wsgi_unix_socket.py b/cherrypy/test/test_wsgi_unix_socket.py index 8f1cc00b..df0ab5f8 100644 --- a/cherrypy/test/test_wsgi_unix_socket.py +++ b/cherrypy/test/test_wsgi_unix_socket.py @@ -2,8 +2,7 @@ import os import socket import atexit import tempfile - -from six.moves.http_client import HTTPConnection +from http.client import HTTPConnection import pytest diff --git a/cherrypy/test/test_xmlrpc.py b/cherrypy/test/test_xmlrpc.py index ad93b821..f3b07f81 100644 --- a/cherrypy/test/test_xmlrpc.py +++ b/cherrypy/test/test_xmlrpc.py @@ -1,54 +1,21 @@ import sys -import six - -from six.moves.xmlrpc_client import ( +from xmlrpc.client import ( DateTime, Fault, - ProtocolError, ServerProxy, SafeTransport + ServerProxy, SafeTransport ) import cherrypy from cherrypy import _cptools from cherrypy.test import helper -if six.PY3: +if True: HTTPSTransport = SafeTransport # Python 3.0's SafeTransport still mistakenly checks for socket.ssl import socket if not hasattr(socket, 'ssl'): socket.ssl = True -else: - class HTTPSTransport(SafeTransport): - - """Subclass of SafeTransport to fix sock.recv errors (by using file). - """ - - def request(self, host, handler, request_body, verbose=0): - # issue XML-RPC request - h = self.make_connection(host) - if verbose: - h.set_debuglevel(1) - - self.send_request(h, handler, request_body) - self.send_host(h, host) - self.send_user_agent(h) - self.send_content(h, request_body) - - errcode, errmsg, headers = h.getreply() - if errcode != 200: - raise ProtocolError(host + handler, errcode, errmsg, headers) - - self.verbose = verbose - - # Here's where we differ from the superclass. It says: - # try: - # sock = h._conn.sock - # except AttributeError: - # sock = None - # return self._parse_response(h.getfile(), sock) - - return self.parse_response(h.getfile()) def setup_server(): @@ -58,7 +58,6 @@ params = dict( entry_points={'console_scripts': ['cherryd = cherrypy.__main__:run']}, include_package_data=True, install_requires=[ - 'six>=1.11.0', 'cheroot>=6.2.4', 'portend>=2.1.1', 'more_itertools', |